fix(security)!: 공개 경로 스냅숏이 profile 덮어쓰기와 모듈 chain의 permitAll까지 고정한다
문제: 공개 경로 스냅숏(publicPathSnapshotTest)은 config/security.yml의 기본값 한 줄만 읽었다. 문서(docs/build.md, gates.md 「공개 경로·보안 체인」)는 보안 체인 전체를 지킨다고 했다. 그래서 둘이 검사를 지나갔다. - application-local.yml이 public-paths를 /api/healthcheck로 덮는다. - web-notification의 callback chain이 /internal/notification/callbacks/**를 anyRequest().permitAll()로 연다. actuator chain의 health·info·prometheus도 같다. docs/build.md는 지운 PublicPathSnapshotPlugin.java와 없는 updatePublicPathSnapshot 태스크를 승인 방법으로 적었다. 관리 포트도 문서와 compose가 갈렸다. 관리 포트가 컨테이너 loopback에 묶인 뒤(MANAGEMENT_SERVER_ADDRESS 기본 127.0.0.1) compose.yaml·dev lane의 127.0.0.1:9001 publish는 아무것도 답하지 않는 줄이 됐고, service-runtime README·Dockerfile은 Kubernetes 프로브가 닿는다고 적었다. dev lane은 원격 JMX(9999)를 인증·TLS 없이, jmxremote.host 없이 열었다(주석은 「localhost only」). 고른 방법: - 스냅숏에 두 절을 더한다. profile 파일이 public-paths를 리터럴로 덮으면 그 값, 모든 leaf 운영 코드에서 Spring Security를 import한 파일의 permitAll·securityMatcher 문장(파일 경로와 함께, 정렬). 그 소스와 baseline을 lane 입력으로 선언해 캐시가 변경을 놓치지 않게 했다. - 기동한 SecurityFilterChain의 matcher를 reflection으로 읽는 안은 버렸다. matcher가 Spring의 private 필드에 있어 버전마다 깨진다. 문장 글자만 보므로 상수로 만든 matcher의 값은 못 본다. 그 한계를 docs/build.md에 적었다. - 관리 포트 publish 줄과 dev lane JMX를 지웠다. 컨테이너 안에서 읽는 명령 (docker compose exec app wget …, jcmd)을 주석에 적었다. Kubernetes는 MANAGEMENT_SERVER_ADDRESS를 바꾸거나 sidecar로 읽어야 한다고 service-runtime README·Dockerfile·docs/build.md에 적었다. 위험·한계: 파생 서비스가 자기 chain이나 profile 덮어쓰기를 두었다면 merge 뒤 스냅숏이 실패한다. 읽고 승인하면 된다(upgrade 안내 1). dev lane에서 원격 JMX로 보던 사람은 jcmd로 바꾼다(안내 4). 검증(desktop, --no-build-cache): - RED: 기준 a7e38c10에 permitAll chain을 더한 탐침 트리에서 기존 publicPathSnapshotTest가 통과했다(rc=0) — 틈이 있다. - GREEN: spotlessApply 뒤 :app-bootstrap:test --tests '*PublicPathSnapshotTest' (새 렌더링 시험 둘), :app-bootstrap:publicPathSnapshotTest, repositoryContractTest, spotlessCheck, :verifyComposeProfiles(18 lane) — 67건 실패 0, skip 1, rc=0. - 변이: 새 스냅숏을 커밋한 트리에서 callback chain의 securityMatcher를 "/internal/**"로 넓히면 publicPathSnapshotTest가 실패한다. BREAKING CHANGE: 공개 경로 스냅숏이 profile 덮어쓰기와 모든 모듈의 permitAll·securityMatcher 문장을 본다. compose가 관리 포트 9001과 dev lane JMX 9999를 publish하지 않는다. 할 일은 docs/upgrade/2026-11-round9-public-surface.md.
This commit is contained in:
+3
-1
@@ -219,7 +219,9 @@ EXPOSE 8080 9001
|
||||
# connection adds its own indicator when it is selected — the JPA module adds the datasource — so a
|
||||
# container started without that dependency reachable is genuinely not ready.
|
||||
# Kubernetes ignores HEALTHCHECK and uses its own probes against the same path; this exists for
|
||||
# docker and Compose.
|
||||
# docker and Compose. A kubelet probe reaches the pod IP, and the management port binds loopback
|
||||
# by default (MANAGEMENT_SERVER_ADDRESS=127.0.0.1): a Kubernetes deployment sets that address, or
|
||||
# its probes fail (src/bootstrap/service-runtime/README.md 「management/security」).
|
||||
#
|
||||
# wget is present in eclipse-temurin:21-jre-noble, so nothing is installed for it.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
|
||||
|
||||
+5
-4
@@ -85,10 +85,11 @@ services:
|
||||
required: false
|
||||
ports:
|
||||
- "${APP_SERVER_PORT:-8080}:8080"
|
||||
# Management (health, info, prometheus — answered without authentication) on loopback only:
|
||||
# published on every interface it reaches the whole LAN (07-13). The smoke lanes read it from
|
||||
# inside the container, so they need no host port at all.
|
||||
- "127.0.0.1:9001:9001"
|
||||
# Management (health, info, prometheus — answered without authentication) is not published.
|
||||
# It binds the container's loopback (MANAGEMENT_SERVER_ADDRESS, default 127.0.0.1), so a host
|
||||
# port mapped to it would answer nothing, and binding 0.0.0.0 to publish it would open it to
|
||||
# every container on the network as well. The healthcheck and the smoke lanes read it from
|
||||
# inside the container: `docker compose exec app wget -qO- http://localhost:9001/actuator/health`.
|
||||
environment:
|
||||
# Explicit, not inherited. A Compose profile selects services; it says nothing about which
|
||||
# environment the application believes it is in. The dev and prod-smoke lane overlays set
|
||||
|
||||
+19
-22
@@ -147,28 +147,22 @@ Checkstyle은 파싱된 파일에 같은 질문을 하고, leaf 단위로 돈다
|
||||
|
||||
### `verifyPublicPathSnapshot`
|
||||
|
||||
- **하는 일.** deny-by-default public path 표면이 승인 없이 바뀌면 빌드를 실패시킨다.
|
||||
- **배경.** 이 앱은 deny-by-default이다. 즉 `SECURITY_PUBLIC_PATHS` 가 먹이는 명시적 `permitAll()`
|
||||
경로를 **제외한** 모든 요청은 인증을 요구한다
|
||||
(`src/bootstrap/app/src/main/resources/config/security.yml` → `SecuritySettings.publicPaths()` →
|
||||
`SecurityConfig`). 설정 분할 이전에는 이 SSOT 가 `.env` 였고 문서만 그대로 남아 있었다.
|
||||
스냅샷 플러그인이 실제로 읽는 파일은 `config/security.yml`이다
|
||||
(`build-logic/.../publicpath/PublicPathSnapshotPlugin.java`).
|
||||
이 public 표면이 바뀌는 순간이 곧 보호되던 엔드포인트가 조용히 공개로 노출되는 지점이다.
|
||||
그래서 그 표면을 snapshot 으로 떠 두고, 미승인 변경에 빌드를 실패시킨다.
|
||||
- **승인 방법.** `verifyPublicPathSnapshot` 은 항상 읽기 전용이다. reviewer 가 변경을 승인한 뒤
|
||||
`./gradlew updatePublicPathSnapshot -PapprovePublicPathChange` 로 snapshot 을 명시적으로 다시
|
||||
생성한다. 공개 경로 변경은 보안 리뷰 대상으로 보고 재생성된 snapshot 을 함께 커밋한다.
|
||||
- **결정 — 무엇을 snapshot 했나 (프로젝트 선택).** 초기안은 기동 시
|
||||
`SecurityFilterChain.getFilters()` 를 introspection 하는 방식이었다. 하지만 그 reflection
|
||||
은 Spring 버전마다 깨지기 쉽다(`permitAll` matcher 가
|
||||
`RequestMatcherDelegatingAuthorizationManager` 의 private 필드에 숨어 있음). 그래서 `permitAll()`
|
||||
을 실제로 먹이는 결정적 SSOT 인 `SECURITY_PUBLIC_PATHS` 자체를 snapshot 한다. 탐지 목표(공개 경로
|
||||
변경은 무조건 게이트를 실패시킨다)는 같고, 메커니즘은 더 견고하다.
|
||||
- **snapshot 위치.** `docs/security/public-paths-snapshot.txt`. 이 파일은 커밋된 필수 보안
|
||||
baseline이다. CI 는 Gradle 실행 전에 파일이 비어 있지 않고 Git에 추적되는지 검사하므로 fresh
|
||||
checkout 에서 누락되거나 untracked 상태면 즉시 실패한다. 승인된 변경만 update task로 재생성한
|
||||
뒤 보안 리뷰와 함께 커밋한다.
|
||||
- **하는 일.** 인증 없이 들어올 수 있는 표면이 승인 없이 바뀌면 빌드를 실패시킨다. main 단계(`mainCheck`)와
|
||||
`releaseCheck`의 lane `:app-bootstrap:publicPathSnapshotTest`다.
|
||||
- **스냅숏에 드는 셋.** `docs/security/public-paths-snapshot.txt`의 세 절이다.
|
||||
- 기본 공개 경로: `src/bootstrap/app/src/main/resources/config/security.yml`의 `app.security.public-paths` 기본값
|
||||
(`SecuritySettings.publicPaths()` → web `SecurityConfig`의 `permitAll()`).
|
||||
- profile이 덮는 값: `application-<profile>.yml`이 `public-paths`를 리터럴로 덮으면 그 값.
|
||||
- 모듈 chain: 모든 leaf의 운영 코드에서 Spring Security를 쓰는 파일의 `permitAll` 문장과 chain 범위
|
||||
(`securityMatcher`) 문장. 알림 callback chain, actuator chain이 여기에 든다. 문장 글자가 바뀌면(새 matcher,
|
||||
넓어진 pattern) 스냅숏이 바뀐다.
|
||||
- **못 보는 것.** 운영자가 배포 env(`SECURITY_PUBLIC_PATHS`)로 준 값, 그리고 matcher를 상수나 변수로 다른 줄에서
|
||||
만든 경우의 그 값(문장 글자만 본다). 그런 변경은 리뷰가 본다.
|
||||
- **승인 방법.** 리뷰가 변경을 받은 뒤 `./gradlew verifyPublicPathSnapshot -PapprovePublicPathChange`로 스냅숏을 다시
|
||||
쓰고 함께 커밋한다. 플래그 없이 돌리면 비교만 한다.
|
||||
- **결정 — 무엇을 스냅숏하나.** 기동한 `SecurityFilterChain`의 matcher를 reflection으로 읽는 안은 Spring 버전마다
|
||||
깨진다(`permitAll` matcher가 `RequestMatcherDelegatingAuthorizationManager`의 private 필드에 있다). 그래서 설정의
|
||||
기본값과 소스의 `permitAll` 문장을 글자로 고정한다.
|
||||
|
||||
### Trivy suppression과 플래키 격리 — 정책은 유지, 파서는 삭제
|
||||
|
||||
@@ -575,3 +569,6 @@ docker compose up -d --wait db
|
||||
- **결정 — management 포트 분리.** actuator 엔드포인트를 앱 API 와 **같은 소켓에 노출하지 않으려고**
|
||||
별도 management 포트를 둔다.
|
||||
- **`MANAGEMENT_SERVER_PORT`** — 1~65535 정수. **`APP_SERVER_PORT`(8080)와 달라야 한다.**
|
||||
- **`MANAGEMENT_SERVER_ADDRESS`** — 관리 커넥터가 묶이는 주소. 기본 `127.0.0.1`(컨테이너 안 loopback). 그래서
|
||||
컨테이너 밖에서는 닿지 않고, compose도 이 포트를 publish하지 않는다. Kubernetes 프로브와 Prometheus처럼 pod IP로
|
||||
읽는 배포는 이 값을 바꾸거나(`0.0.0.0`과 NetworkPolicy) 같은 pod의 sidecar로 읽는다.
|
||||
|
||||
@@ -4,3 +4,12 @@
|
||||
# overrides it at run time and is outside this snapshot.
|
||||
# Update only after review with: ./gradlew verifyPublicPathSnapshot -PapprovePublicPathChange
|
||||
/v1/healthcheck
|
||||
# Profile overrides of app.security.public-paths
|
||||
profile local: /api/healthcheck
|
||||
# Filter-chain statements that permit requests without authentication
|
||||
src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackMvcSecurityConfiguration.java: .authorizeHttpRequests(requests -> requests.anyRequest().permitAll())
|
||||
src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackMvcSecurityConfiguration.java: return http.securityMatcher("/internal/notification/callbacks/**")
|
||||
src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java: auth.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll();
|
||||
src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java: auth.requestMatchers(publicPaths).permitAll();
|
||||
src/bootstrap/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java: .requestMatchers(EndpointRequest.to("health", "info", "prometheus")) .permitAll()
|
||||
src/bootstrap/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java: http.securityMatcher(EndpointRequest.toAnyEndpoint())
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# 업그레이드 안내 — 2026-11 공개 경로 스냅숏과 관리 포트
|
||||
|
||||
- 범위: 공개 경로 스냅숏(`docs/security/public-paths-snapshot.txt`)이 보는 범위를 넓힌 변경과, compose가 관리 포트·JMX를
|
||||
publish하던 줄을 지운 변경. 앱이 여는 경로와 기본 설정은 바뀌지 않았다.
|
||||
- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 공개 경로·관리 포트 발견
|
||||
|
||||
## 1. 누가 읽나
|
||||
|
||||
이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 자기 모듈에 Spring Security filter
|
||||
chain을 둔 서비스, profile 파일에서 `app.security.public-paths`를 덮은 서비스, Kubernetes에 배포하는 서비스, dev
|
||||
compose lane으로 JVM을 원격 JMX로 보던 사람이다.
|
||||
|
||||
## 2. 할 일
|
||||
|
||||
| # | 할 일 | 안 하면 | 해당 서비스 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | merge 뒤 `./gradlew verifyPublicPathSnapshot`을 돌린다. 실패하면 스냅숏에 새로 든 두 절(profile이 덮는 값, filter chain의 `permitAll`·`securityMatcher` 문장)을 읽고, 의도한 공개면 `./gradlew verifyPublicPathSnapshot -PapprovePublicPathChange`로 다시 쓴 파일을 보안 리뷰와 함께 커밋한다 | `mainCheck`·`releaseCheck`의 `:app-bootstrap:publicPathSnapshotTest`가 실패한다 | 자기 chain이나 profile 덮어쓰기가 있는 서비스 |
|
||||
| 2 | Kubernetes 배포는 `MANAGEMENT_SERVER_ADDRESS`를 pod IP에서 닿는 주소(예: `0.0.0.0`과 NetworkPolicy)로 두거나 같은 pod의 sidecar로 읽는다. 기본값 `127.0.0.1`은 2026-11-12 main 병합(관리 포트 loopback 고정)부터다 | kubelet 프로브가 관리 포트에 닿지 않아 liveness 실패로 재시작하고 readiness가 오지 않는다. Prometheus도 못 읽는다 | Kubernetes 배포 |
|
||||
| 3 | compose에서 관리 포트를 호스트로 읽던 명령(`curl localhost:9001/...`)을 `docker compose exec app wget -qO- http://localhost:9001/actuator/health`로 바꾼다 | 호스트 포트가 없어 연결이 거절된다. 지운 publish 줄도 컨테이너 loopback에 닿지 않아 원래 아무것도 답하지 않았다 | compose로 띄우는 사람 |
|
||||
| 4 | dev lane에서 원격 JMX(9999) 대신 `docker compose exec app jcmd 1 <명령>`(`VM.flags`, `Thread.print`, `JFR.start`)을 쓴다 | 9999 연결이 거절된다 | dev lane으로 JVM을 보던 사람 |
|
||||
|
||||
## 3. 바뀐 것
|
||||
|
||||
- 스냅숏은 세 절이다: 기본 공개 경로(`config/security.yml`), profile이 덮는 값(`application-<profile>.yml`), 모든 leaf
|
||||
운영 코드의 `permitAll`·`securityMatcher` 문장. 알림 callback chain과 actuator chain이 셋째 절에 든다.
|
||||
- 스냅숏이 못 보는 것은 운영자가 배포 env(`SECURITY_PUBLIC_PATHS`)로 준 값과, matcher를 상수나 변수로 다른 줄에서
|
||||
만든 경우의 그 값이다. 그런 변경은 리뷰가 본다(`docs/build.md` 「`verifyPublicPathSnapshot`」).
|
||||
- dev lane의 원격 JMX는 인증·TLS 없이 열려 있었고 `jmxremote.host`가 없어 모든 인터페이스에 묶였다. 그래서 지웠다.
|
||||
@@ -459,6 +459,14 @@ strictTestLanes {
|
||||
systemProperty 'publicpath.snapshot.write', project.hasProperty('approvePublicPathChange') ? 'true' : 'false'
|
||||
}
|
||||
}
|
||||
// The snapshot also lists every filter-chain statement that permits requests, in any leaf, and the
|
||||
// committed baseline it compares with: both are files outside this project's own inputs.
|
||||
tasks.named('publicPathSnapshotTest', Test) {
|
||||
inputs.files(fileTree(rootProject.projectDir) {
|
||||
include 'src/**/src/main/java/**/*.java', 'docs/security/public-paths-snapshot.txt'
|
||||
exclude repositoryContractExcludes
|
||||
}).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('securitySourcesAndBaseline')
|
||||
}
|
||||
|
||||
tasks.register('stageDockerJar', Sync) {
|
||||
dependsOn tasks.named('bootJar')
|
||||
|
||||
@@ -12,7 +12,11 @@
|
||||
# can hot-swap files without image rebuilds.
|
||||
# - Increases memory allowance for dev/debugging workloads.
|
||||
# - Disables restart-unless-stopped so crash loops don't mask startup errors.
|
||||
# - Enables JMX remote port (local only, never in prod).
|
||||
# - No remote JMX. The JVM's JMX connector without authentication runs code for anyone who
|
||||
# reaches it, and a port published to the host's loopback still answers every container on the
|
||||
# Compose network (the reason the management port binds the container's loopback). Inspect the
|
||||
# JVM from inside the container instead: `docker compose exec app jcmd 1 VM.flags`, `Thread.print`,
|
||||
# `JFR.start` (2026-11-12 review).
|
||||
# - Mounts a local source volume for fast iteration (optional; mount when IDE
|
||||
# attaches to the running container).
|
||||
# =============================================================================
|
||||
@@ -51,7 +55,6 @@ services:
|
||||
# Use a shorter drain timeout in dev so restarts are faster.
|
||||
APP_SERVER_SHUTDOWN_TIMEOUT: "5s"
|
||||
APP_SERVER_SHUTDOWN: "graceful"
|
||||
# Remote JMX — bind to localhost only; NEVER expose in production.
|
||||
JAVA_TOOL_OPTIONS: >-
|
||||
-XX:MaxRAMPercentage=75
|
||||
-XX:+UseContainerSupport
|
||||
@@ -59,16 +62,11 @@ services:
|
||||
-XX:+HeapDumpOnOutOfMemoryError
|
||||
-XX:HeapDumpPath=/var/tmp/heap
|
||||
-Dserver.tomcat.basedir=/tmp
|
||||
-Dcom.sun.management.jmxremote
|
||||
-Dcom.sun.management.jmxremote.port=9999
|
||||
-Dcom.sun.management.jmxremote.rmi.port=9999
|
||||
-Dcom.sun.management.jmxremote.authenticate=false
|
||||
-Dcom.sun.management.jmxremote.ssl=false
|
||||
-Djava.rmi.server.hostname=127.0.0.1
|
||||
# The management port is not published: it binds the container's loopback
|
||||
# (MANAGEMENT_SERVER_ADDRESS), so a host port mapped to it answers nothing. Read it from inside
|
||||
# the container: `docker compose exec app wget -qO- http://localhost:9001/actuator/health`.
|
||||
ports:
|
||||
- "8080:8080"
|
||||
- "127.0.0.1:9001:9001" # management — localhost only (07-13)
|
||||
- "127.0.0.1:9999:9999" # JMX — localhost only
|
||||
# No health check constraint in dev; let the app start at its own pace.
|
||||
healthcheck:
|
||||
disable: true
|
||||
|
||||
+150
-1
@@ -11,6 +11,7 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -30,6 +31,10 @@ class PublicPathSnapshotTest {
|
||||
private static final Path SECURITY_CONFIGURATION =
|
||||
Path.of("src/main/resources/config/security.yml");
|
||||
private static final Path SNAPSHOT = Path.of("../../../docs/security/public-paths-snapshot.txt");
|
||||
private static final Path RESOURCES = Path.of("src/main/resources");
|
||||
private static final Path REPOSITORY = Path.of("../../..");
|
||||
private static final Pattern PROFILE_FILE = Pattern.compile("application-([a-z0-9-]+)\\.yml");
|
||||
private static final String SECURITY_IMPORT = "org.springframework.security";
|
||||
private static final Pattern BINDING = Pattern.compile("^\\s*public-paths:\\s*(\\S.*?)\\s*$");
|
||||
private static final Pattern DEFAULTED_PLACEHOLDER =
|
||||
Pattern.compile("\\$\\{[A-Za-z0-9_.]+:([^{}]*)}");
|
||||
@@ -47,7 +52,10 @@ class PublicPathSnapshotTest {
|
||||
@DisplayName("배포되는 public path 기본값이 검토된 기준선과 같다")
|
||||
void theShippedPublicPathDefaultMatchesTheReviewedBaseline() throws IOException {
|
||||
// given
|
||||
String rendered = render(Files.readAllLines(SECURITY_CONFIGURATION, StandardCharsets.UTF_8));
|
||||
String rendered =
|
||||
render(Files.readAllLines(SECURITY_CONFIGURATION, StandardCharsets.UTF_8))
|
||||
+ renderProfiles(profileFiles())
|
||||
+ renderPermitAllSites(REPOSITORY, securitySources());
|
||||
if (Boolean.getBoolean("publicpath.snapshot.write")) {
|
||||
Files.writeString(SNAPSHOT, rendered, StandardCharsets.UTF_8);
|
||||
}
|
||||
@@ -112,6 +120,61 @@ class PublicPathSnapshotTest {
|
||||
.hasMessageContaining("expected exactly one 'public-paths:' binding, found 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("보안 설정의 permitAll 문장과 chain 범위를 파일 경로와 함께 정렬해 적고, 보안 import가 없는 파일은 건너뛴다")
|
||||
void permitAllStatementsAreListedWithTheirChainScope(@org.junit.jupiter.api.io.TempDir Path root)
|
||||
throws IOException {
|
||||
// given
|
||||
Path chain = root.resolve("src/a/src/main/java/ChainConfig.java");
|
||||
Path other = root.resolve("src/b/src/main/java/Policy.java");
|
||||
Files.createDirectories(chain.getParent());
|
||||
Files.createDirectories(other.getParent());
|
||||
Files.writeString(
|
||||
chain,
|
||||
"""
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
class ChainConfig {
|
||||
// .permitAll() in a comment is not a statement
|
||||
void chain(HttpSecurity http) {
|
||||
http.securityMatcher("/hooks/**")
|
||||
.authorizeHttpRequests(a -> a
|
||||
.requestMatchers("/hooks/ping")
|
||||
.permitAll());
|
||||
}
|
||||
}""");
|
||||
Files.writeString(other, "class Policy { static Policy permitAll() { return null; } }");
|
||||
|
||||
// when
|
||||
String rendered = renderPermitAllSites(root, List.of(chain, other));
|
||||
|
||||
// then
|
||||
assertThat(rendered)
|
||||
.isEqualTo(
|
||||
"# Filter-chain statements that permit requests without authentication\n"
|
||||
+ "src/a/src/main/java/ChainConfig.java: .requestMatchers(\"/hooks/ping\")"
|
||||
+ " .permitAll());\n"
|
||||
+ "src/a/src/main/java/ChainConfig.java: http.securityMatcher(\"/hooks/**\")\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("profile 파일이 public-paths를 덮으면 profile 이름과 값을 적는다")
|
||||
void aProfileThatOverridesThePublicPathsIsListed(@org.junit.jupiter.api.io.TempDir Path root)
|
||||
throws IOException {
|
||||
// given
|
||||
Path local = root.resolve("application-local.yml");
|
||||
Path prod = root.resolve("application-prod.yml");
|
||||
Files.writeString(local, "app:\n security:\n public-paths: /api/healthcheck\n");
|
||||
Files.writeString(prod, "app:\n security:\n audience: x\n");
|
||||
|
||||
// when
|
||||
String rendered = renderProfiles(List.of(local, prod));
|
||||
|
||||
// then
|
||||
assertThat(rendered)
|
||||
.isEqualTo(
|
||||
"# Profile overrides of app.security.public-paths\nprofile local: /api/healthcheck\n");
|
||||
}
|
||||
|
||||
private static String render(List<String> configuration) {
|
||||
List<String> bindings = new ArrayList<>();
|
||||
for (String line : configuration) {
|
||||
@@ -150,4 +213,90 @@ class PublicPathSnapshotTest {
|
||||
.toList();
|
||||
return HEADER + (paths.isEmpty() ? "" : String.join("\n", paths) + "\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* A profile file that sets {@code app.security.public-paths} to a literal overrides the default
|
||||
* in that runtime, so the snapshot pins it too. The check used to read security.yml only, and
|
||||
* application-local.yml opened its own path past it (review 2026-11-12).
|
||||
*/
|
||||
static String renderProfiles(List<Path> profiles) throws IOException {
|
||||
List<String> lines = new ArrayList<>();
|
||||
for (Path profile : profiles) {
|
||||
Matcher name = PROFILE_FILE.matcher(profile.getFileName().toString());
|
||||
if (!name.matches()) {
|
||||
continue;
|
||||
}
|
||||
for (String line : Files.readAllLines(profile, StandardCharsets.UTF_8)) {
|
||||
Matcher binding = BINDING.matcher(line);
|
||||
if (binding.matches()) {
|
||||
lines.add("profile " + name.group(1) + ": " + binding.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines.isEmpty()
|
||||
? ""
|
||||
: "# Profile overrides of app.security.public-paths\n"
|
||||
+ String.join("\n", lines.stream().sorted().toList())
|
||||
+ "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Every filter chain that lets a request through unauthenticated, wherever its module is: the
|
||||
* statement that permits and the matcher that scopes its chain. The default list above feeds one
|
||||
* chain; a module's own chain (the notification callback, the actuator) opened paths the old
|
||||
* snapshot never saw. A statement whose text changes — a new matcher, a wider pattern — changes
|
||||
* the snapshot.
|
||||
*/
|
||||
static String renderPermitAllSites(Path root, List<Path> sources) throws IOException {
|
||||
List<String> sites = new ArrayList<>();
|
||||
for (Path source : sources) {
|
||||
List<String> lines = Files.readAllLines(source, StandardCharsets.UTF_8);
|
||||
if (lines.stream().noneMatch(line -> line.contains(SECURITY_IMPORT))) {
|
||||
continue;
|
||||
}
|
||||
String file = root.relativize(source).toString().replace('\\', '/');
|
||||
String previous = "";
|
||||
for (String raw : lines) {
|
||||
String line = raw.trim();
|
||||
if (line.isEmpty()
|
||||
|| line.startsWith("//")
|
||||
|| line.startsWith("*")
|
||||
|| line.startsWith("/*")) {
|
||||
continue;
|
||||
}
|
||||
if (line.contains("securityMatcher(")) {
|
||||
sites.add(file + ": " + line);
|
||||
}
|
||||
if (line.contains(".permitAll(")) {
|
||||
sites.add(file + ": " + (line.startsWith(".permitAll") ? previous + " " + line : line));
|
||||
}
|
||||
previous = line;
|
||||
}
|
||||
}
|
||||
return sites.isEmpty()
|
||||
? ""
|
||||
: "# Filter-chain statements that permit requests without authentication\n"
|
||||
+ String.join("\n", sites.stream().sorted().toList())
|
||||
+ "\n";
|
||||
}
|
||||
|
||||
private static List<Path> profileFiles() throws IOException {
|
||||
try (Stream<Path> files = Files.list(RESOURCES)) {
|
||||
return files
|
||||
.filter(path -> PROFILE_FILE.matcher(path.getFileName().toString()).matches())
|
||||
.sorted()
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Path> securitySources() throws IOException {
|
||||
try (Stream<Path> files = Files.walk(REPOSITORY.resolve("src"))) {
|
||||
return files
|
||||
.filter(path -> path.toString().endsWith(".java"))
|
||||
.filter(path -> path.toString().replace('\\', '/').contains("/src/main/java/"))
|
||||
.filter(path -> !path.toString().replace('\\', '/').contains("/build/"))
|
||||
.sorted()
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,9 +272,12 @@ runtimeOnly project(':composition:service-runtime')
|
||||
앞서 실행된다.** 그래서 액추에이터 엔드포인트에 매칭되는 요청은 앱 체인이 아니라 이 체인이
|
||||
처리한다. 보안 매처는 `EndpointRequest.toAnyEndpoint()`로, 관리 포트의 `/actuator/**` 경로만 이
|
||||
체인 범위에 든다.
|
||||
- **접근 정책.** `health`, `info`, `prometheus`는 permit-all 이다. 자격 증명 없이 Kubernetes 프로브와
|
||||
Prometheus 스크레이프가 접근할 수 있어야 하고, 이 엔드포인트들은 민감 데이터를 노출하지 않기
|
||||
때문이다(health 상세는 `never`). 나머지(`/actuator` 링크 등)는 모두 인증이 필요하다.
|
||||
- **접근 정책.** `health`, `info`, `prometheus`는 permit-all 이다. 자격 증명 없이 프로브와 스크레이프가
|
||||
읽을 수 있어야 하고, 이 엔드포인트들은 민감 데이터를 노출하지 않기 때문이다(health 상세는 `never`).
|
||||
관리 포트는 기본으로 loopback(`MANAGEMENT_SERVER_ADDRESS=127.0.0.1`)에만 묶인다. Kubernetes kubelet
|
||||
프로브와 Prometheus는 pod IP로 붙으므로, 그 배포는 `MANAGEMENT_SERVER_ADDRESS`를 그 주소(예: `0.0.0.0`과
|
||||
NetworkPolicy)로 바꾸거나 같은 pod의 sidecar로 읽는다. 기본값 그대로면 liveness가 실패해 재시작하고
|
||||
readiness가 오지 않는다. 나머지(`/actuator` 링크 등)는 모두 인증이 필요하다.
|
||||
- **`loggers`는 노출하지 않는다.** 이 체인에는 인증 수단(`httpBasic`·`oauth2ResourceServer`)이 없어
|
||||
`authenticated()`에 걸리는 엔드포인트는 어떤 자격 증명으로도 도달할 수 없다. 그래서 `loggers`
|
||||
노출과 `show-details: when-authorized`를 뺐다. 로그 레벨을 런타임에 보거나 바꿔야 하면 인증
|
||||
|
||||
Reference in New Issue
Block a user