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:
@@ -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