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` 안에서 돈다. 실패 메시지가 안쪽 키 이름을 짚는다.