From 33af80ab20a80ad6a2fbbf6d6af505c9b019ad54 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 03:41:30 +0900 Subject: [PATCH] =?UTF-8?q?fix(env)!:=20env=20=EA=B3=84=EC=95=BD=20?= =?UTF-8?q?=EA=B2=80=EC=82=AC=EA=B0=80=20=EA=B8=B0=EB=B3=B8=EA=B0=92=20?= =?UTF-8?q?=EC=95=88=EC=97=90=20=EC=A4=91=EC=B2=A9=EB=90=9C=20placeholder?= =?UTF-8?q?=EB=8F=84=20=EC=9D=BD=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit EnvContractVerifier의 placeholder 정규식은 기본값을 첫 '}'까지로 읽는다. 그래서 ${A:${B:x}}에서 기본값이 "${B:x"를 삼키고 다음 찾기는 B 뒤에서 이어져, 안쪽 키 B는 registry 행 요구·기본값 대조·required 판정에서 모두 빠진다. 지금 트리의 중첩 줄은 config/security.yml의 SECURITY_PUBLIC_PATHS 하나이고 안쪽 PRESENTATION_API_BASE_PATH를 runtime.yml이 따로 읽어 드러나지 않았다. 기본값에 "${"가 있으면 다음 찾기를 그 기본값 안의 첫 "${"에서 다시 시작한다. 겹마다 한 번씩 되풀이되어 몇 겹이든 안쪽 키를 바깥 키와 같은 규칙으로 본다: 행이 있어야 하고, 리터럴 기본값은 registry default와 대조하고, 기본값이 없으면 바깥 키가 없을 때 읽히므로 required다. 중첩 없는 줄의 추출은 그대로다. 버린 안: 중괄호 깊이를 세는 파서로 기본값 끝을 다시 찾기. 바깥 키의 기본값은 어차피 비교하지 않으니 끝 위치가 필요 없고, 중첩 없는 기본값의 추출까지 바뀐다. 위험: 안쪽 키를 등록하지 않았거나 기본값이 행과 다른 파생 서비스는 verifyEnvKeys(mainCheck 안)가 새로 실패한다. ${A:${B}}의 B는 바깥 키가 .env.example에 있어도 required로 본다(엄한 쪽). 검증: desktop 깨끗한 worktree(트리 e2b080ad)에서 ./gradlew -p build-logic check javadoc rc=0(시험 172, EnvContractVerifierTest 28), :app-bootstrap:verifyEnvKeys rc=0(env 키 315, required 6). 새 시험을 main 판 검사기에 얹으면 6건 실패(rc=1). 검사기 변이 3개 중 2개(재시작 위치 +1, lastIndexOf)를 시험이 잡고, 1개(기본값 시작에서 재시작)는 등가다: find가 앞으로 찾아 첫 "${"에서 같은 매치를 얻는다. scripts/verify.sh pr --no-cache rc=0(tests=7350), docs rc=0. Refs: REV-BE-0014 BREAKING CHANGE: 배포 설정 기본값 안의 placeholder(${A:${B:x}}의 B)도 registry 행, 기본값 일치, 기본값이 없으면 .env.example 줄이 있어야 verifyEnvKeys를 통과한다. docs/upgrade/2026-11-env-contract-nested-placeholder.md를 본다. --- .../config/EnvContractVerifier.java | 19 ++- .../config/EnvContractVerifierTest.java | 127 ++++++++++++++++++ ...2026-11-env-contract-nested-placeholder.md | 33 +++++ 3 files changed, 174 insertions(+), 5 deletions(-) create mode 100644 docs/upgrade/2026-11-env-contract-nested-placeholder.md diff --git a/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java b/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java index f917534f..c92875df 100644 --- a/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java +++ b/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java @@ -135,21 +135,30 @@ public final class EnvContractVerifier { Set environmentSecretReferences = new TreeSet<>(); // name -> the literal defaults the non-profile shipped files give it ("" for ${KEY:}). A // profile file (application-.yml) overrides on purpose and is not compared; a default - // that nests another placeholder is not a literal and is not compared either. + // that nests another placeholder is not a literal and is not compared either. The nested + // placeholder is read by the same rules as an outer one — it needs a row, its literal default is + // compared, and one without a default is required, because the application falls back to it + // whenever the outer key is unset. The pattern's default stops at the first '}', so in + // ${A:${B:x}} it swallows "${B:x" and the scan would resume past B; it resumes at the first + // "${" inside the default instead, once per nesting level (REV-BE-0014). Map> shippedDefaults = new TreeMap<>(); for (File configurationFile : configurationFiles) { String configuration = read(configurationFile); boolean profileFile = configurationFile.getName().startsWith("application-"); Matcher placeholderMatcher = PLACEHOLDER.matcher(configuration); - while (placeholderMatcher.find()) { + int searchFrom = 0; + while (placeholderMatcher.find(searchFrom)) { + String fallback = placeholderMatcher.group(2); allPlaceholders.add(placeholderMatcher.group(1)); - if (placeholderMatcher.group(2) == null) { + if (fallback == null) { requiredPlaceholders.add(placeholderMatcher.group(1)); - } else if (!profileFile && !placeholderMatcher.group(2).contains("${")) { + } else if (!profileFile && !fallback.contains("${")) { shippedDefaults .computeIfAbsent(placeholderMatcher.group(1), name -> new TreeSet<>()) - .add(normalizedValue(placeholderMatcher.group(2).substring(1))); + .add(normalizedValue(fallback.substring(1))); } + int nested = fallback == null ? -1 : fallback.indexOf("${"); + searchFrom = nested < 0 ? placeholderMatcher.end() : placeholderMatcher.start(2) + nested; } Matcher secretMatcher = SECRET_REFERENCE.matcher(configuration); while (secretMatcher.find()) { diff --git a/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java b/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java index 4cb1250d..f598a21f 100644 --- a/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java +++ b/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java @@ -1,5 +1,7 @@ package dev.caskeleton.buildlogic.config; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -12,6 +14,8 @@ import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; class EnvContractVerifierTest { @@ -547,6 +551,129 @@ class EnvContractVerifierTest { assertTrue(!failure.getMessage().contains("127.0.0.1"), failure.getMessage()); } + @ParameterizedTest + @CsvSource( + delimiter = '|', + value = { + "${APP_NEW_SWITCH:${APP_NEW_BASE:/x}} | [APP_NEW_BASE]", + "${APP_NEW_SWITCH:${APP_NEW_BASE:/x}/healthcheck} | [APP_NEW_BASE]", + "${APP_NEW_SWITCH:${APP_NEW_MIDDLE:${APP_NEW_BASE:/x}}} | [APP_NEW_BASE, APP_NEW_MIDDLE]" + }) + @DisplayName("기본값 안에 중첩된 placeholder(${A:${B:x}})의 안쪽 키도 깊이마다 레지스트리에 없으면 실패한다") + void aPlaceholderNestedInADefaultMustBeRegistered( + String value, String unregistered, @TempDir Path temp) throws Exception { + // given + Fixture fixture = withNewSwitch(fixture(temp)); + Path security = securityYaml(fixture, value); + + // when + Throwable failure = catchThrowable(() -> verify(fixture, security)); + + // then + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "shipped configuration references env keys absent from docs/registries/env-keys.yaml" + + " (any prefix; optional defaults and environment secret references are" + + " included): " + + unregistered); + } + + @Test + void aNestedPlaceholderDefaultThatIsNotTheRegistryDefaultFails(@TempDir Path temp) + throws Exception { + // given + Fixture fixture = withNewBase(withNewSwitch(fixture(temp)), "/y"); + Path security = securityYaml(fixture, "${APP_NEW_SWITCH:${APP_NEW_BASE:/x}/healthcheck}"); + + // when + Throwable failure = catchThrowable(() -> verify(fixture, security)); + + // then + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "APP_NEW_BASE: the shipped configuration defaults to '/x', the registry default is" + + " '/y'"); + } + + @Test + @DisplayName("기본값 없는 중첩 placeholder(${A:${B}})는 바깥 키가 없을 때 읽히므로 .env.example에 있어야 한다") + void aNestedPlaceholderWithoutADefaultIsRequired(@TempDir Path temp) throws Exception { + // given + Fixture fixture = withNewSwitch(fixture(temp)); + Path security = securityYaml(fixture, "${APP_NEW_SWITCH:${APP_NEW_BASE}}"); + + // when + Throwable failure = catchThrowable(() -> verify(fixture, security)); + + // then + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "shipped configuration references required env absent from .env.example:" + + " [APP_NEW_BASE]"); + } + + @Test + void aRegisteredNestedPlaceholderPassesAndCountsAsARead(@TempDir Path temp) throws Exception { + // given + Fixture fixture = withNewBase(withNewSwitch(fixture(temp)), "/x"); + Path security = securityYaml(fixture, "${APP_NEW_SWITCH:${APP_NEW_BASE:/x}/healthcheck}"); + + // when + EnvContractResult result = verify(fixture, security); + + // then + assertThat(result.applicationReferenceCount()).isEqualTo(4); + } + + /** Registers and sets {@code APP_NEW_SWITCH}, the outer key of every nested-placeholder case. */ + private static Fixture withNewSwitch(Fixture fixture) throws Exception { + Files.writeString( + fixture.envFile(), Files.readString(fixture.envFile()) + "APP_NEW_SWITCH=/x/switch\n"); + Files.writeString( + fixture.registry(), + Files.readString(fixture.registry()) + + "- name: APP_NEW_SWITCH\n type: string\n default: /x/switch\n"); + return fixture; + } + + /** Registers and sets {@code APP_NEW_BASE}, an inner key, with {@code registryDefault}. */ + private static Fixture withNewBase(Fixture fixture, String registryDefault) throws Exception { + Files.writeString( + fixture.envFile(), + Files.readString(fixture.envFile()) + "APP_NEW_BASE=" + registryDefault + "\n"); + Files.writeString( + fixture.registry(), + Files.readString(fixture.registry()) + + "- name: APP_NEW_BASE\n type: string\n default: " + + registryDefault + + "\n"); + return fixture; + } + + /** A shipped {@code config/security.yml} whose one property is {@code value}. */ + private static Path securityYaml(Fixture fixture, String value) throws Exception { + Path security = + fixture.repositoryRoot().resolve("app-bootstrap/src/main/resources/config/security.yml"); + Files.createDirectories(security.getParent()); + Files.writeString(security, "public-paths: " + value + "\n"); + return security; + } + + private static EnvContractResult verify(Fixture fixture, Path secondaryConfiguration) { + return EnvContractVerifier.verify( + fixture.envFile().toFile(), + List.of(fixture.applicationYaml().toFile(), secondaryConfiguration.toFile()), + fixture.registry().toFile(), + List.of(), + fixture.metadataClasspath(), + List.of("app.redis."), + List.of("APP_REDIS_"), + List.of()); + } + private static EnvContractResult verify(Fixture fixture) { return EnvContractVerifier.verify( fixture.envFile().toFile(), diff --git a/docs/upgrade/2026-11-env-contract-nested-placeholder.md b/docs/upgrade/2026-11-env-contract-nested-placeholder.md new file mode 100644 index 00000000..e0a3b386 --- /dev/null +++ b/docs/upgrade/2026-11-env-contract-nested-placeholder.md @@ -0,0 +1,33 @@ +# 업그레이드 안내 — 2026-11 env 계약 검사가 중첩 placeholder를 읽는다 + +- 범위: `:app-bootstrap:verifyEnvKeys`(구현 `build-logic`의 `EnvContractVerifier`)가 배포 설정의 placeholder를 찾는 방식. + 앱이 읽는 키와 기본값, registry 칸, 검사 규칙 자체는 그대로다. 규칙을 지키는 범위가 기본값 안의 placeholder까지 넓어졌다. +- 근거: `docs/upgrade/2026-11-round9-env-keys.md` 2절 5번(배포 설정의 placeholder는 접두어와 상관없이 registry에 행이 있고 + 행의 `default`가 placeholder 기본값과 같다) + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스 가운데, `verifyEnvKeys`가 읽는 설정 파일(profile 파일 +`application-.yml`을 포함한 `application*.yml`, `config/*.yml`, 모듈 `config/module-defaults/*.yml`)에 기본값 안에 +placeholder를 넣은 줄(`${A:${B:x}}`)을 둔 서비스가 읽는다. 템플릿 자신의 중첩 줄은 `config/security.yml`의 +`SECURITY_PUBLIC_PATHS` 하나이고 안쪽 키가 이미 등록돼 있다. + +## 2. 새로 실패하는 꼴과 할 일 + +전에는 바깥 키(`A`)만 읽고 안쪽 키(`B`)는 건너뛰었다. 이제 안쪽 키도 바깥 키와 같은 규칙으로 본다. 중첩이 몇 겹이어도 같다. + +| # | 꼴 | 할 일 | 안 하면 | +| --- | --- | --- | --- | +| 1 | 안쪽 키 `B`에 registry 행이 없다 | `docs/registries/env-keys.yaml`에 `B` 행을 더한다 | `verifyEnvKeys`가 「shipped configuration references env keys absent from docs/registries/env-keys.yaml」로 실패한다 | +| 2 | 안쪽 키의 리터럴 기본값(`${A:${B:x}}`의 `x`)이 `B` 행의 `default`와 다르다. profile 파일은 일부러 덮어쓰는 곳이라 전처럼 비교하지 않는다 | 행의 `default`나 설정의 기본값을 하나로 맞춘다 | 「env values disagree with docs/registries/env-keys.yaml」로 실패한다 | +| 3 | 안쪽 키에 기본값이 없다(`${A:${B}}`). 바깥 키가 없으면 앱이 `B`를 읽는다 | `.env.example`에 `B` 줄을 더하거나, 안쪽에 기본값을 준다 | 「shipped configuration references required env absent from .env.example」로 실패한다 | + +바깥 키의 기본값(`${B:x}` 전체)은 리터럴이 아니어서 전처럼 registry `default`와 비교하지 않는다. + +## 3. 확인하는 법 + +```bash +./gradlew :app-bootstrap:verifyEnvKeys +``` + +이 태스크는 `mainCheck` 안에서 돈다. 실패 메시지가 안쪽 키 이름을 짚는다. -- 2.54.0