260804_01_ENH: api key에 특정 경로 허용 제외 추가

This commit is contained in:
2026-08-04 16:56:42 +09:00
parent 2954565fc7
commit 1ac8dab45a
6 changed files with 112 additions and 4 deletions

View File

@@ -112,8 +112,13 @@ Security note: default secrets in source are not production-safe. Documentation
Behavior:
- API key is read from `kri.auth.apikey.header-name`, default `X-API-Key`.
- `kri.auth.apikey.allowed-paths` limits where API key authentication is attempted. Unset, `null`, empty, or blank-only lists preserve the legacy all-request behavior; one or more valid patterns restrict authentication to matching paths.
- `kri.auth.apikey.excluded-paths` skips API key authentication on matching paths. Exclusions take precedence when a request matches both an allowed and an excluded pattern.
- API key path matching uses Spring `PathPatternRequestMatcher`, ignores HTTP method and query strings, and matches the path within the application after removing the context path.
- `allowed-paths` and `excluded-paths` do not grant access or alter `kri.security.public-paths`; they only scope the API key authentication filter.
- If authentication already exists in `SecurityContextHolder`, API key filter does nothing.
- If provider resolves a key, the result is converted to `Authentication` using `JwtService.toAuthentication`.
- DB preload auto-configuration requires Spring Data JPA on the classpath; a consumer-provided `ApiKeyUserClaimsProvider` remains usable without JPA.
- Preloaded provider returns empty cache when `service-code` is blank.
- Admin endpoint is exposed only when `admin-api-enabled=true` and the preload provider exists.
- Admin endpoint has IP allowlist enforcement.

View File

@@ -473,6 +473,8 @@ kri:
apikey:
enabled: false
header-name: "X-API-Key"
allowed-paths: []
excluded-paths: []
service-code: "example-service"
preload-on-startup: false
admin-api-enabled: false
@@ -554,13 +556,52 @@ kri:
- `enabled=true`일 때 API Key 인증 기능 활성화
- `header-name`으로 API Key를 읽을 HTTP header 지정
- `allowed-paths`가 한 개 이상이면 일치하는 요청에서만 API Key 인증 시도
- `excluded-paths`와 일치하는 요청은 허용 여부와 관계없이 API Key 인증에서 제외
- JPA repository를 통해 서비스별 활성 API Key를 preload cache로 적재
- `ApiKeyAuthFilter`가 API Key를 `Authentication`으로 변환
- `admin-api-enabled=true`일 때 내부 reload/cache endpoint 노출
API Key를 일부 API에서만 인증 수단으로 허용하려면 다음처럼 설정합니다.
```yaml
kri:
auth:
apikey:
enabled: true
header-name: X-API-Key
service-code: kric-contact-service
allowed-paths:
- /api/v1/list/update/**
- /api/v1/external/**
excluded-paths:
- /api/v1/external/admin/**
```
경로 설정의 동작은 다음과 같습니다. 두 설정이 겹치면 `excluded-paths`가 우선합니다.
| `allowed-paths` | `excluded-paths` | API Key 인증 대상 |
|---|---|---|
| 비어 있음 | 비어 있음 | 기존처럼 모든 요청 |
| 비어 있음 | 설정됨 | 제외 패턴과 일치하지 않는 요청 |
| 설정됨 | 비어 있음 | 허용 패턴과 일치하는 요청 |
| 설정됨 | 설정됨 | 허용 패턴과 일치하면서 제외 패턴과 일치하지 않는 요청 |
하위 호환 규칙과 매칭 방식은 다음과 같습니다.
- 각 속성의 미설정, `null`, 빈 목록 또는 공백 패턴만 있는 목록은 해당 경로 제한을 적용하지 않습니다.
- `allowed-paths`에 유효한 패턴이 하나 이상이면 그중 하나와 일치하는 요청만 인증 대상이 됩니다.
- `excluded-paths`에 유효한 패턴이 하나 이상이면 그중 하나와 일치하는 요청은 항상 인증 대상에서 제외됩니다.
- Spring 경로 패턴을 사용하며 `*`는 한 경로 구간, `**`는 하위 경로 전체와 매칭합니다.
- HTTP method는 구분하지 않고, context path와 query string은 매칭 대상에서 제외합니다.
- 패턴은 `/`로 시작해야 하며 잘못된 패턴은 애플리케이션 기동 시 오류로 처리됩니다.
- 두 설정은 API Key 인증 필터의 적용 범위만 제한합니다. 경로를 공개하거나 접근 권한을 직접 부여하지 않습니다.
- 공개 경로는 별도 설정인 `kri.security.public-paths`로 관리합니다.
주의:
- DB preload 방식은 JPA와 DataSource 관련 classpath가 필요합니다.
- JPA classpath가 없으면 DB preload 자동 구성만 건너뛰며, 서비스가 직접 등록한 `ApiKeyUserClaimsProvider`는 사용할 수 있습니다.
- `service-code`가 비어 있으면 preload cache는 비어 있게 됩니다.
- admin API는 IP allowlist를 통과해야 합니다.
@@ -717,3 +758,9 @@ Endpoint:
- Swagger 접근 제한은 운영망/관리망 정책에 맞춰 `allowed-ips`를 명시합니다.
- 대용량 Excel은 일반 `Workbook` 변환보다 streaming API를 우선 검토합니다.
- 배포 전 `./gradlew compileJava`로 컴파일을 확인합니다.
---
## 변경 이력
- 2026-08-04: `kri.auth.apikey.allowed-paths`와 `kri.auth.apikey.excluded-paths`를 추가했습니다. 미설정·`null`·빈 목록은 기존 전역 API Key 인증 동작을 유지하며, 제외 패턴은 허용 패턴보다 우선합니다.

View File

@@ -4,7 +4,7 @@ plugins {
}
// 버전 변경은 여기서
def commonVer = "beta.1.4.0"
def commonVer = "beta.1.5.0"
group = 'com.kri.common'
version = commonVer
@@ -176,4 +176,4 @@ tasks.register('checkGiteaPackageVersionNotExists') {
tasks.named('publishReleasePublicationToGiteaRepository') {
dependsOn 'checkGiteaPackageVersionNotExists'
}
}

View File

@@ -5,6 +5,7 @@ import com.kri.common.runtime.auth.apikey.PreloadedApiKeyUserClaimsProvider;
import com.kri.common.runtime.auth.apikey.persistence.repository.ApiKeyRepository;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@@ -12,6 +13,7 @@ import org.springframework.context.annotation.Bean;
@AutoConfiguration(after = ApiKeyJpaAutoConfiguration.class)
@EnableConfigurationProperties(ApiKeyProperties.class)
@ConditionalOnClass(name = "org.springframework.data.jpa.repository.JpaRepository")
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true")
public class ApiKeyPreloadAutoConfiguration {

View File

@@ -26,6 +26,16 @@ public class ApiKeyProperties {
*/
private String headerName = "X-API-Key";
/**
* API Key 인증을 시도할 URL 패턴. 미설정, null 또는 빈 목록이면 모든 요청에서 인증을 시도한다.
*/
private List<String> allowedPaths = List.of();
/**
* API Key 인증에서 제외할 URL 패턴. 허용 패턴보다 우선한다.
*/
private List<String> excludedPaths = List.of();
/**
* 이 서비스의 코드 (서비스별 preload 범위 결정)
*/

View File

@@ -8,18 +8,62 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.RequiredArgsConstructor;
import java.util.List;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
@RequiredArgsConstructor
public class ApiKeyAuthFilter extends OncePerRequestFilter {
private final ApiKeyProperties apiKeyProperties;
private final ApiKeyUserClaimsProvider apiKeyUserClaimsProvider;
private final JwtService jwtService;
private final List<RequestMatcher> allowedPathMatchers;
private final List<RequestMatcher> excludedPathMatchers;
public ApiKeyAuthFilter(
ApiKeyProperties apiKeyProperties,
ApiKeyUserClaimsProvider apiKeyUserClaimsProvider,
JwtService jwtService
) {
this.apiKeyProperties = apiKeyProperties;
this.apiKeyUserClaimsProvider = apiKeyUserClaimsProvider;
this.jwtService = jwtService;
this.allowedPathMatchers = createPathMatchers(apiKeyProperties.getAllowedPaths());
this.excludedPathMatchers = createPathMatchers(apiKeyProperties.getExcludedPaths());
}
private static List<RequestMatcher> createPathMatchers(List<String> paths) {
if (paths == null || paths.isEmpty()) {
return List.of();
}
PathPatternRequestMatcher.Builder matcherBuilder = PathPatternRequestMatcher.withDefaults();
return paths.stream()
.filter(StringUtils::hasText)
.map(String::trim)
.map(matcherBuilder::matcher)
.map(RequestMatcher.class::cast)
.toList();
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
if (matchesAny(excludedPathMatchers, request)) {
return true;
}
return !allowedPathMatchers.isEmpty() && !matchesAny(allowedPathMatchers, request);
}
private static boolean matchesAny(
List<RequestMatcher> matchers,
HttpServletRequest request
) {
return matchers.stream().anyMatch(matcher -> matcher.matches(request));
}
@Override
protected void doFilterInternal(