From bd17bf1f0087529431e31b128108c9df48a2a655 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 01:48:48 +0900 Subject: [PATCH 1/2] =?UTF-8?q?fix(env)!:=20env=20=EA=B3=84=EC=95=BD?= =?UTF-8?q?=EC=9D=84=20=EB=B0=B0=ED=8F=AC=20=EC=84=A4=EC=A0=95=20=EB=8F=99?= =?UTF-8?q?=EC=9E=91=EC=97=90=20=EB=A7=9E=EC=B6=94=EA=B3=A0=20verifyEnvKey?= =?UTF-8?q?s=EA=B0=80=20=EA=B7=B8=20=EC=B0=A8=EC=9D=B4=EB=A5=BC=20?= =?UTF-8?q?=EC=9E=A1=EA=B2=8C=20=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: docs/registries/env-keys.yaml·.env.example·배포 설정(profile 밖의 application.yml, config/*.yml, 모듈 module-defaults)이 서로 갈렸고 verifyEnvKeys는 그 차이를 보지 못했다. - .env.example을 복사하면 기동이 실패하는 값이 있었다: APP_DATASOURCE_CONNECTION_TIMEOUT=5s(Hikari long ms, registry 주석이 "기동 실패"라고 적은 그 값), APP_SECURITY_CORS_MAX_AGE=600s(long 초). - 기본값과 다른 예시 값: cache·rate-limit Redis command timeout(2s·1s vs 200ms), APP_LOG_LEVEL_SQL(WARN vs INFO), FORWARD_HEADERS_STRATEGY(native vs none — 프록시 없는 배포에서 forwarded 헤더를 믿게 된다), POSITIVE_SOFT_TTL(빈 줄 — 빈 문자열이 기본값을 덮는다). - registry가 폐기(deprecated_orphaned)로 적은 키 셋을 cache-redis 모듈 설정이 읽는다(COMMAND_TIMEOUT, SEMANTIC_REGION, KEY_HMAC_SECRET 참조). - 폐기 키 45개가 .env.example에 값과 함께 남아, 복사하면 아무 일도 하지 않는 값을 켠 것으로 믿는다. 검사가 오히려 registry의 모든 APP_ 행을 예시에 요구해 폐기 행도 넣게 했다. - 배포 설정이 읽는 APP_ 밖 placeholder 11개(SECURITY_PUBLIC_PATHS, PRESENTATION_API_BASE_PATH, SPRING_JACKSON_DESER_* 등)에 registry 행이 없었다. 검사가 APP_ 이름만 보고, registry 파서도 APP_ 행만 읽어 MANAGEMENT_SERVER_ADDRESS 같은 행이 보이지 않았다. - .env.example 머리말은 "빈 키는 기본값을 쓴다", "Seven values"라고 적었다. 고른 방법: 런타임 동작은 바꾸지 않고 registry와 예시를 배포 설정에 맞춘다. 그리고 verifyEnvKeys가 다섯을 더 본다. 1. registry 행은 접두어와 상관없이 읽는다. 2. 배포 설정의 placeholder는 접두어와 상관없이 행이 있어야 한다. 3. deprecated_orphaned 행은 배포 설정이 읽지 않고 .env.example에 없다. 4. .env.example 값은 registry default(행에 example이 있으면 그 값)와 같다. 빈 줄은 빈 문자열로 본다. 5. profile 밖 배포 설정의 placeholder 기본값은 registry default와 같다. registry에 example 칸을 두었다(SMTP 587·timeout처럼 기본값이 아닌 권장값). APP_ 밖 이름 11개는 지금 이름 그대로 등록했다. 바꾸면 파생 서비스의 배포 env가 소리 없이 무시된다. 이름 변경은 소유자 결정이다. registry 머리말을 실제 규칙(SPRING_·MANAGEMENT_·SERVER_·OTEL_ 이름공간과 옛 이름 둘)으로 고쳤다. gRPC를 켜려면 꼭 두는 APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL과 .env.example의 MANAGEMENT_SERVER_ADDRESS를 더했다. 버린 대안: SECURITY_PUBLIC_PATHS·PRESENTATION_API_BASE_PATH를 APP_로 바꾸고 옛 이름을 fallback으로 두기 — 공개 경로 기본값이 4중 placeholder가 되고 공개 경로 스냅숏 파서까지 바꿔야 한다. 이름 정리는 따로 정한다. 위험·한계: 파생 서비스가 자기 placeholder를 등록하지 않았거나 예시 값이 기본값과 다르면 이제 verifyEnvKeys(mainCheck)가 실패한다(upgrade 안내 5·6). 예시 값이 바뀌어 옛 예시를 복사한 .env는 그대로 둔다 — 안내 1~4가 고칠 값을 적는다. 검증(desktop, --no-build-cache): - RED: 기준 a7e38c10 + 시험만으로 EnvContractVerifierTest 22건 중 7건 실패 (새 검사 6건 + 메시지를 바꾼 기존 1건). 새 지킴 시험(example 행 통과)은 기준에서도 통과. - GREEN: -p build-logic test, :app-bootstrap:verifyEnvKeys(314 env keys, 6 required placeholders, 370 rows), :app-bootstrap:test·repositoryContractTest· documentContractTest, registry·예시를 읽는 leaf 시험(httpclient env manifest, notification mode, redis-runtime required_when, support, fileserver·notification platform, graphql registry parity, web CORS) 682건 실패 0, skip 5. rc=0. BREAKING CHANGE: verifyEnvKeys가 접두어 밖 placeholder, 폐기 행의 사용, 예시·기본값 차이를 실패로 본다. .env.example에서 폐기 키가 빠지고 값 여덟이 기본값으로 바뀌었다. 할 일은 docs/upgrade/2026-11-round9-env-keys.md. --- .env.example | 77 ++---- .../config/EnvContractVerifier.java | 133 ++++++++-- .../buildlogic/config/EnvRegistryRow.java | 25 +- .../config/EnvContractVerifierTest.java | 171 ++++++++++++- docs/registries/env-keys.yaml | 230 ++++++++++++++++-- docs/upgrade/2026-11-round9-env-keys.md | 45 ++++ 6 files changed, 581 insertions(+), 100 deletions(-) create mode 100644 docs/upgrade/2026-11-round9-env-keys.md diff --git a/.env.example b/.env.example index 91afa010..1c68b40e 100644 --- a/.env.example +++ b/.env.example @@ -9,10 +9,13 @@ # is a credential in the repository, and the fact that it is 'only an example' is not something a # scanner, a fork, or a hurried operator can tell. # -# A key left blank here uses the inline default in application.yml. Seven values have no default -# at all — the datasource URL, username and password, the application name, and the JWT issuer and -# audience — because a default for any of them is a deployment running against something nobody -# chose. +# Every value here is the registry default (or the row's `example:`, a recommended production +# value such as the SMTP submission port). A blank line is not "use the default": Compose env_file +# and bootRun both set the variable to an empty string, which replaces the default. So a key is left +# blank only when it has no default — secrets, and the values a deployment must choose itself (the +# profile, the application name, the datasource URL and username, the JWT issuer and audience), +# because a default for any of them is a deployment running against something nobody chose. +# Keys the registry marks deprecated_orphaned are not listed: nothing reads them. # ============================================================================= # ---- Configuration ----------------------------------------------------------- @@ -20,9 +23,13 @@ SPRING_PROFILES_ACTIVE= APP_NAME= APP_SERVER_PORT=8080 MANAGEMENT_SERVER_PORT=9001 +# Loopback by default, so the actuator is reachable only from inside the container. Kubernetes +# probes and a Prometheus scrape reach the pod IP: set the address they use (for example 0.0.0.0 +# behind a NetworkPolicy) or run them as a sidecar. +MANAGEMENT_SERVER_ADDRESS=127.0.0.1 APP_SERVER_SHUTDOWN=graceful APP_SERVER_SHUTDOWN_TIMEOUT=30s -APP_SERVER_FORWARD_HEADERS_STRATEGY=native +APP_SERVER_FORWARD_HEADERS_STRATEGY=none APP_SERVER_TOMCAT_MAX_THREADS=200 APP_SERVER_TOMCAT_MIN_SPARE_THREADS=10 APP_SERVER_TOMCAT_ACCEPT_COUNT=100 @@ -42,7 +49,7 @@ APP_DATASOURCE_URL= APP_DATASOURCE_USERNAME= APP_DATASOURCE_POOL_MAX_SIZE=10 APP_DATASOURCE_POOL_MIN_IDLE=2 -APP_DATASOURCE_CONNECTION_TIMEOUT=5s +APP_DATASOURCE_CONNECTION_TIMEOUT=5000 APP_DATASOURCE_DRIVER=org.postgresql.Driver APP_DATASOURCE_DDL_AUTO=validate APP_DATASOURCE_SHOW_SQL=false @@ -57,7 +64,7 @@ APP_LOG_LEVEL_ROOT=INFO APP_LOG_LEVEL_APP=INFO APP_LOG_LEVEL_SPRING=INFO APP_LOG_LEVEL_WEB=INFO -APP_LOG_LEVEL_SQL=WARN +APP_LOG_LEVEL_SQL=INFO APP_LOG_FILE_ENABLED=false APP_LOG_FILE_PATH=logs/ca-skeleton.json APP_LOG_FILE_MAX_SIZE=100MB @@ -76,7 +83,7 @@ APP_SECURITY_CORS_ENABLED=false APP_SECURITY_CORS_ALLOWED_METHODS= APP_SECURITY_CORS_ALLOWED_HEADERS=* APP_SECURITY_CORS_ALLOW_CREDENTIALS=false -APP_SECURITY_CORS_MAX_AGE=600s +APP_SECURITY_CORS_MAX_AGE=600 APP_SECURITY_AUTH_MODE=jwt APP_SESSION_COOKIE_NAME=CA_SESSION APP_SESSION_COOKIE_SECURE=true @@ -85,33 +92,16 @@ APP_SESSION_COOKIE_SAME_SITE=Lax APP_SESSION_COOKIE_PATH=/ APP_SESSION_CSRF_COOKIE_NAME=XSRF-TOKEN APP_SESSION_CSRF_HEADER_NAME=X-XSRF-TOKEN -APP_SESSION_REDIS_NAMESPACE_ENVIRONMENT=local -APP_SESSION_IDLE_TIMEOUT=30m -APP_SESSION_ABSOLUTE_LIFETIME=8h -APP_SESSION_TOUCH_INTERVAL=1m -APP_SESSION_TOMBSTONE_TTL=5m -APP_SESSION_MAXIMUM_ENVELOPE_BYTES=32768 -APP_SESSION_MAXIMUM_ATTRIBUTES=64 -APP_SESSION_MAXIMUM_SCALAR_BYTES=8192 APP_SECURITY_JWT_ISSUER= APP_SECURITY_JWT_AUDIENCE= APP_RATE_LIMIT_ENABLED=false -APP_RATE_LIMIT_REDIS_ENABLED=false APP_RATE_LIMIT_PROVIDER=disabled APP_RATE_LIMIT_FAILURE_POLICY=fail-closed APP_RATE_LIMIT_DEFAULT_POLICY_ID=api-default APP_RATE_LIMIT_FAILURE_RETRY_AFTER=100ms APP_RATE_LIMIT_HASH_KEY_VERSION=1 APP_RATE_LIMIT_KEY_VERSION=1 -APP_RATE_LIMIT_REDIS_HOST= -APP_RATE_LIMIT_REDIS_PORT=6379 -APP_RATE_LIMIT_REDIS_TRUST_PEM= -APP_SESSION_REDIS_TRUST_PEM= -APP_RATE_LIMIT_REDIS_COMMAND_TIMEOUT=1s -APP_RATE_LIMIT_REDIS_MAXIMUM_COMMAND_BYTES=16384 -APP_RATE_LIMIT_REDIS_MAXIMUM_QUEUED_COMMANDS=32 -APP_RATE_LIMIT_REDIS_MAXIMUM_IN_FLIGHT_BYTES=1048576 -APP_RATE_LIMIT_REDIS_NAMESPACE_ENVIRONMENT=local +APP_RATE_LIMIT_REDIS_COMMAND_TIMEOUT=200ms APP_RATE_LIMIT_POLICY_REVISION=v1 APP_RATE_LIMIT_ALGORITHM=sliding-counter APP_RATE_LIMIT_LIMIT=100 @@ -127,12 +117,10 @@ APP_IDEMPOTENCY_TTL=24h # disabled | redis | postgresql. postgresql refuses a non-PostgreSQL data source, so bootRunH2 # runs with disabled or redis. APP_IDEMPOTENCY_PROVIDER=disabled -APP_IDEMPOTENCY_REDIS_NAMESPACE_ENVIRONMENT=local APP_IDEMPOTENCY_PROCESSING_LEASE=30s # Failure retention: at most 30d and not shorter than APP_IDEMPOTENCY_TTL (startup fails). APP_IDEMPOTENCY_FAILURE_RETENTION=24h APP_LEASE_PROVIDER=disabled -APP_LEASE_REDIS_NAMESPACE_ENVIRONMENT=local APP_LEASE_REDIS_DRIFT_BUDGET=10ms APP_CACHE_CANONICAL_DEFAULT_PROVIDER=disabled APP_REDIS_ENABLED=true @@ -179,32 +167,10 @@ APP_REDIS_TLS_CLIENT_KEY_REFERENCE= APP_REDIS_TLS_ENABLED=false APP_REDIS_TLS_HOSTNAME_VERIFICATION=true APP_REDIS_TLS_TRUST_MATERIAL_RESOURCE= -APP_CACHE_REDIS_ENABLED=false -APP_CACHE_REDIS_CLIENT_MODE=managed -APP_CACHE_REDIS_HOST= -APP_CACHE_REDIS_PORT=6379 -APP_CACHE_REDIS_TRUST_PEM= -APP_REDIS_SEMANTIC_PROBE_MINIMUM_INTERVAL=5s -APP_REDIS_SENTINEL_DISCOVERY_REFRESH_PERIOD=30s -APP_REDIS_SEMANTIC_PROBE_MAXIMUM_STALENESS=15s -APP_CACHE_REDIS_COMMAND_TIMEOUT=2s -APP_CACHE_REDIS_MAXIMUM_QUEUED_COMMANDS=8 -APP_CACHE_REDIS_MAXIMUM_IN_FLIGHT_BYTES=16777216 -APP_CACHE_REDIS_POSITIVE_SOFT_TTL= -APP_CACHE_REDIS_TTL_JITTER=0.10 +APP_CACHE_REDIS_COMMAND_TIMEOUT=200ms +APP_CACHE_REDIS_POSITIVE_SOFT_TTL=30s APP_CACHE_REDIS_MINIMUM_HARD_TTL=1s -APP_CACHE_REDIS_NAMESPACE_ENVIRONMENT=local APP_CACHE_REDIS_SEMANTIC_REGION=default -APP_CACHE_REDIS_MAXIMUM_VALUE_BYTES=1048576 -APP_CACHE_REDIS_L1_ENABLED=false -APP_CACHE_REDIS_L1_MAXIMUM_ENTRIES=10000 -APP_CACHE_REDIS_L1_MAXIMUM_WEIGHT_BYTES=67108864 -APP_CACHE_REDIS_L1_MAXIMUM_ENTRY_WEIGHT_BYTES=1048576 -APP_CACHE_REDIS_L1_TTL=30s -APP_CACHE_REDIS_L1_GENERATION_RECHECK_INTERVAL=5s -APP_CACHE_REDIS_L1_INVALIDATION_QUEUE_CAPACITY=1024 -APP_CACHE_DEFAULT_TTL=300s -APP_CACHE_NEGATIVE_TTL=60s APP_MESSAGING_BROKER=kafka APP_MESSAGING_PRODUCER_ID= APP_MESSAGING_KAFKA_BROKERS= @@ -301,6 +267,9 @@ APP_WEBSOCKET_ENABLED=true # `false` is the explicit off the Compose lanes set. APP_OBJECTSTORAGE_ENABLED=true APP_GRPC_SERVER_ENABLED=true +# The listener is loopback plaintext only; a deployment that selects the gRPC module sets this to +# true or startup refuses. +APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL=false APP_WEBSOCKET_ENDPOINT=/ws APP_WEBSOCKET_ALLOWED_ORIGINS=http://localhost:3000 APP_WEBSOCKET_BROADCAST_DESTINATION=/topic/events @@ -384,10 +353,6 @@ APP_PRIVACY_PSEUDONYMIZATION_SALT= APP_RATE_LIMIT_REDIS_PASSWORD= APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET= APP_SESSION_REDIS_PASSWORD= -APP_SESSION_REDIS_KEY_HMAC_SECRET= -APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET= -APP_LEASE_REDIS_KEY_HMAC_SECRET= -APP_CACHE_REDIS_PASSWORD= APP_CACHE_REDIS_KEY_HMAC_SECRET= APP_FILESERVER_PLATFORM_OBSERVABILITY_FINGERPRINT_KEY= # The notification platform's seven key purposes. Each is base64 of at least 32 bytes and must 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 c1f1892e..f917534f 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 @@ -9,21 +9,28 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Repository policy for the operator-facing environment contract. No Gradle API. */ public final class EnvContractVerifier { - private static final Pattern ENV_LINE = Pattern.compile("^([A-Z][A-Z0-9_]*)=.*"); + private static final Pattern ENV_LINE = Pattern.compile("^([A-Z][A-Z0-9_]*)=(.*)$"); private static final Pattern PLACEHOLDER = Pattern.compile("\\$\\{([A-Z][A-Z0-9_]*)(:[^}]*)?}"); private static final Pattern SECRET_REFERENCE = Pattern.compile("secret://environment/(APP_[A-Z][A-Z0-9_]*)"); + /** + * A registry row of any name. It used to match {@code APP_} rows only, so the framework-named + * rows ({@code MANAGEMENT_SERVER_ADDRESS}, {@code SPRING_MAIL_*}) were invisible to every rule + * below and a placeholder outside {@code APP_} needed no row at all. + */ private static final Pattern REGISTRY_NAME = - Pattern.compile("^\\s*- name: (APP_[A-Z0-9_]+)"); + Pattern.compile("^\\s*- name: ([A-Z][A-Z0-9_]*)\\s*$"); private static final Pattern REGISTRY_FIELD = Pattern.compile("^\\s*([a-z_]+):\\s*(\\S.*)?$"); private static final Pattern APP_KEY = Pattern.compile("APP_[A-Z][A-Z0-9_]*"); @@ -114,23 +121,34 @@ public final class EnvContractVerifier { requireFile(registryFile, "missing " + registryFile); Set envKeys = new TreeSet<>(); + Map envValues = new TreeMap<>(); for (String line : readLines(envFile)) { Matcher matcher = ENV_LINE.matcher(line); if (matcher.matches()) { envKeys.add(matcher.group(1)); + envValues.put(matcher.group(1), matcher.group(2).trim()); } } Set requiredPlaceholders = new TreeSet<>(); Set allPlaceholders = new TreeSet<>(); 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. + 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()) { allPlaceholders.add(placeholderMatcher.group(1)); if (placeholderMatcher.group(2) == null) { requiredPlaceholders.add(placeholderMatcher.group(1)); + } else if (!profileFile && !placeholderMatcher.group(2).contains("${")) { + shippedDefaults + .computeIfAbsent(placeholderMatcher.group(1), name -> new TreeSet<>()) + .add(normalizedValue(placeholderMatcher.group(2).substring(1))); } } Matcher secretMatcher = SECRET_REFERENCE.matcher(configuration); @@ -139,10 +157,9 @@ public final class EnvContractVerifier { } } - Set applicationAppReferences = new TreeSet<>(); - allPlaceholders.stream() - .filter(name -> name.startsWith("APP_")) - .forEach(applicationAppReferences::add); + // Every name the shipped configuration reads, whatever its prefix: a placeholder outside APP_ + // (SECURITY_PUBLIC_PATHS opens paths to anonymous callers) needs a row as much as an APP_ one. + Set applicationAppReferences = new TreeSet<>(allPlaceholders); applicationAppReferences.addAll(environmentSecretReferences); failUnlessEmpty( @@ -152,26 +169,80 @@ public final class EnvContractVerifier { List registryRows = parseRegistryRows(registryFile); Set registryAppKeys = new TreeSet<>(); Set registryProperties = new TreeSet<>(); + Set liveAppRows = new TreeSet<>(); + Set deprecatedRows = new TreeSet<>(); for (EnvRegistryRow row : registryRows) { registryAppKeys.add(row.name()); row.property().ifPresent(registryProperties::add); + if (row.deprecatedOrphaned()) { + deprecatedRows.add(row.name()); + } else if (row.name().startsWith("APP_")) { + liveAppRows.add(row.name()); + } } failUnlessEmpty( - difference(registryAppKeys, envKeys), + difference(liveAppRows, envKeys), "docs/registries/env-keys.yaml registers APP_ keys absent from .env.example, so an " + "adopter copying the example never sees them: "); - - Set envAppKeys = new TreeSet<>(); - envKeys.stream().filter(name -> name.startsWith("APP_")).forEach(envAppKeys::add); failUnlessEmpty( - difference(envAppKeys, registryAppKeys), - ".env.example declares APP_ keys absent from docs/registries/env-keys.yaml " - + "(registry is the SSOT for APP_ keys): "); + intersection(deprecatedRows, envKeys), + ".env.example sets keys the registry marks deprecated_orphaned — an adopter who copies it" + + " sets a variable nothing reads and believes it is in force: ", + " — take the line out; the registry row stays to tell a deployment that still sets it."); + failUnlessEmpty( + intersection(deprecatedRows, applicationAppReferences), + "docs/registries/env-keys.yaml marks keys deprecated_orphaned that the shipped" + + " configuration still reads: ", + " — the row says nothing reads them and tells deployments to stop setting them; restore" + + " the row (and its default) or remove the placeholder."); + + failUnlessEmpty( + difference(envKeys, registryAppKeys), + ".env.example declares keys absent from docs/registries/env-keys.yaml " + + "(registry is the SSOT): "); failUnlessEmpty( difference(applicationAppReferences, registryAppKeys), - "shipped configuration references APP_ keys absent from docs/registries/env-keys.yaml " - + "(optional defaults and environment secret references are included): "); + "shipped configuration references env keys absent from docs/registries/env-keys.yaml " + + "(any prefix; optional defaults and environment secret references are included): "); + + List valueMismatches = new ArrayList<>(); + for (EnvRegistryRow row : registryRows) { + String expected = row.exampleValue(); + String written = envValues.get(row.name()); + if (written != null && !normalizedValue(written).equals(expected)) { + valueMismatches.add( + row.name() + + ": .env.example writes '" + + written + + "', the registry " + + (row.example().isPresent() ? "example" : "default") + + " is '" + + expected + + "'" + + (written.isEmpty() + ? " (a blank line sets an empty string, which replaces the default)" + : "")); + } + Set defaults = shippedDefaults.getOrDefault(row.name(), Set.of()); + String registered = row.defaultValue().orElse(""); + for (String shipped : defaults) { + if (!shipped.equals(registered)) { + valueMismatches.add( + row.name() + + ": the shipped configuration defaults to '" + + shipped + + "', the registry default is '" + + registered + + "'"); + } + } + } + failUnlessEmpty( + valueMismatches, + "env values disagree with docs/registries/env-keys.yaml: ", + " — the registry default is what the shipped configuration falls back to, and" + + " .env.example writes that default (or the row's example:)."); Set declared = ConfigurationMetadataClasspath.propertiesUnder(metadataClasspath, ""); Set typedProperties = new TreeSet<>(); @@ -351,6 +422,10 @@ public final class EnvContractVerifier { current.property = value; } else if (key.equals("deprecated_orphaned")) { current.deprecatedOrphaned = Boolean.parseBoolean(value); + } else if (key.equals("default")) { + current.defaultValue = normalizedValue(value); + } else if (key.equals("example")) { + current.example = normalizedValue(value); } } if (current != null) { @@ -391,6 +466,25 @@ public final class EnvContractVerifier { } } + private static Set intersection(Collection left, Collection right) { + Set result = new TreeSet<>(left); + result.retainAll(new HashSet<>(right)); + return result; + } + + /** A registry or env value without YAML quotes; {@code null}, {@code ~} and blank are "". */ + private static String normalizedValue(String raw) { + String value = raw.trim(); + if (value.length() >= 2 + && (value.startsWith("\"") && value.endsWith("\"") + || value.startsWith("'") && value.endsWith("'"))) { + value = value.substring(1, value.length() - 1); + } else if (value.equals("null") || value.equals("~")) { + value = ""; + } + return value; + } + private static Set difference(Collection left, Collection right) { Set result = new TreeSet<>(left); result.removeAll(new HashSet<>(right)); @@ -417,13 +511,20 @@ public final class EnvContractVerifier { private final String name; private String property; private boolean deprecatedOrphaned; + private String defaultValue; + private String example; private RowBuilder(String name) { this.name = name; } private EnvRegistryRow build() { - return new EnvRegistryRow(name, Optional.ofNullable(property), deprecatedOrphaned); + return new EnvRegistryRow( + name, + Optional.ofNullable(property), + deprecatedOrphaned, + Optional.ofNullable(defaultValue).filter(value -> !value.isEmpty()), + Optional.ofNullable(example)); } } } diff --git a/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvRegistryRow.java b/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvRegistryRow.java index 77ffd3fc..8b1f6810 100644 --- a/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvRegistryRow.java +++ b/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvRegistryRow.java @@ -3,10 +3,33 @@ package dev.caskeleton.buildlogic.config; import java.util.Objects; import java.util.Optional; +/** + * One {@code env-keys.yaml} row as the environment contract reads it. + * + * @param defaultValue the row's {@code default:}, empty when it is {@code null} or blank — the + * value the shipped configuration falls back to and {@code .env.example} writes + * @param example the row's {@code example:}, the value {@code .env.example} writes instead of the + * default (a recommended production value such as the SMTP submission port) + */ public record EnvRegistryRow( - String name, Optional property, boolean deprecatedOrphaned) { + String name, + Optional property, + boolean deprecatedOrphaned, + Optional defaultValue, + Optional example) { public EnvRegistryRow { Objects.requireNonNull(name, "name"); property = property == null ? Optional.empty() : property; + defaultValue = defaultValue == null ? Optional.empty() : defaultValue; + example = example == null ? Optional.empty() : example; + } + + public EnvRegistryRow(String name, Optional property, boolean deprecatedOrphaned) { + this(name, property, deprecatedOrphaned, Optional.empty(), Optional.empty()); + } + + /** What {@code .env.example} must write for this row: the example, else the default. */ + public String exampleValue() { + return example.or(() -> defaultValue).orElse(""); } } 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 f3c4f9d1..4cb1250d 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 @@ -102,7 +102,7 @@ class EnvContractVerifierTest { Files.readString(fixture.registry()) + "- name: APP_REDIS_UNUSED\n" + " type: string\n" - + " default: null\n"); + + " default: present-but-unread\n"); IllegalStateException failure = assertThrows( @@ -142,7 +142,7 @@ class EnvContractVerifierTest { List.of("APP_REDIS_"), List.of())); - assertTrue(failure.getMessage().contains("shipped configuration references APP_ keys")); + assertTrue(failure.getMessage().contains("shipped configuration references env keys")); assertTrue(failure.getMessage().contains("APP_SECONDARY_ONLY")); } @@ -356,7 +356,7 @@ class EnvContractVerifierTest { Files.writeString( fixture.registry(), Files.readString(fixture.registry()) - + "- name: APP_GHOST_ENABLED\n property: app.ghost.enabled\n type: boolean\n"); + + "- name: APP_GHOST_ENABLED\n property: app.ghost.enabled\n type: boolean\n default: true\n"); Path compose = fixture.repositoryRoot().resolve("compose.yaml"); Files.writeString( compose, "services:\n app:\n environment:\n APP_GHOST_ENABLED: \"true\"\n"); @@ -381,7 +381,7 @@ class EnvContractVerifierTest { Files.writeString( fixture.registry(), Files.readString(fixture.registry()) - + "- name: APP_GHOST_ENABLED\n property: app.ghost.enabled\n type: boolean\n"); + + "- name: APP_GHOST_ENABLED\n property: app.ghost.enabled\n type: boolean\n default: true\n"); Path ghostClasses = fixture.repositoryRoot().resolve("adapter/ghost/build/classes/java/main"); Files.createDirectories(ghostClasses.resolve("META-INF")); Files.writeString( @@ -398,6 +398,167 @@ class EnvContractVerifierTest { assertEquals(3, result.envKeyCount()); } + @Test + @DisplayName("APP_ 밖 이름의 placeholder도 레지스트리에 없으면 실패한다") + void aPlaceholderOutsideTheAppPrefixMustBeRegistered(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString( + fixture.applicationYaml(), + Files.readString(fixture.applicationYaml()) + "paths: ${SECURITY_PUBLIC_PATHS:/v1/health}\n"); + + // when + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> verify(fixture)); + + // then + assertTrue(failure.getMessage().contains("shipped configuration references env keys absent")); + assertTrue(failure.getMessage().contains("SECURITY_PUBLIC_PATHS")); + } + + @Test + @DisplayName("APP_ 밖 이름의 레지스트리 행도 placeholder를 등록한 것으로 친다") + void aFrameworkNamedRegistryRowRegistersItsPlaceholder(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString( + fixture.applicationYaml(), + Files.readString(fixture.applicationYaml()) + + "address: ${MANAGEMENT_SERVER_ADDRESS:127.0.0.1}\n"); + Files.writeString( + fixture.registry(), + Files.readString(fixture.registry()) + + "- name: MANAGEMENT_SERVER_ADDRESS\n type: string\n default: 127.0.0.1\n"); + + // when + EnvContractResult result = verify(fixture); + + // then + assertEquals(3, result.applicationReferenceCount()); + } + + @Test + @DisplayName("deprecated_orphaned 행의 키를 .env.example이 아직 쓰면 실패한다") + void aDeprecatedKeyTheExampleStillSetsFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString( + fixture.envFile(), Files.readString(fixture.envFile()) + "APP_REDIS_OLD=2s\n"); + Files.writeString( + fixture.registry(), + Files.readString(fixture.registry()) + + "- name: APP_REDIS_OLD\n deprecated_orphaned: true\n type: duration\n default: 2s\n"); + + // when + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> verify(fixture)); + + // then + assertTrue(failure.getMessage().contains("marks deprecated_orphaned")); + assertTrue(failure.getMessage().contains("APP_REDIS_OLD")); + } + + @Test + @DisplayName("deprecated_orphaned 행의 키를 배포 설정이 아직 읽으면 실패한다") + void aDeprecatedKeyTheConfigurationStillReadsFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString( + fixture.applicationYaml(), + Files.readString(fixture.applicationYaml()) + "timeout: ${APP_REDIS_OLD:200ms}\n"); + Files.writeString( + fixture.registry(), + Files.readString(fixture.registry()) + + "- name: APP_REDIS_OLD\n deprecated_orphaned: true\n type: duration\n default: 200ms\n"); + + // when + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> verify(fixture)); + + // then + assertTrue(failure.getMessage().contains("that the shipped configuration still reads")); + assertTrue(failure.getMessage().contains("APP_REDIS_OLD")); + } + + @Test + @DisplayName(".env.example 값이 레지스트리 기본값과 다르면 실패하고, 빈 줄은 빈 문자열로 친다") + void anExampleValueThatIsNotTheRegistryDefaultFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString(fixture.envFile(), "APP_REQUIRED=required\nAPP_REDIS_HOST=\n"); + + // when + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> verify(fixture)); + + // then + assertTrue(failure.getMessage().contains("APP_REDIS_HOST: .env.example writes ''")); + assertTrue(failure.getMessage().contains("a blank line sets an empty string")); + } + + @Test + @DisplayName("행의 example 값을 .env.example이 쓰면 기본값과 달라도 통과한다") + void anExampleValueTheRowNamesPasses(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString( + fixture.envFile(), Files.readString(fixture.envFile()) + "SPRING_MAIL_PORT=587\n"); + Files.writeString( + fixture.registry(), + Files.readString(fixture.registry()) + + "- name: SPRING_MAIL_PORT\n type: integer\n default: null\n example: 587\n"); + + // when + EnvContractResult result = verify(fixture); + + // then + assertEquals(3, result.envKeyCount()); + } + + @Test + @DisplayName("배포 설정의 기본값이 레지스트리 기본값과 다르면 실패하고, profile 파일은 비교하지 않는다") + void aShippedDefaultThatIsNotTheRegistryDefaultFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Path profile = fixture.applicationYaml().resolveSibling("application-local.yml"); + Files.writeString(profile, "redis: ${APP_REDIS_HOST:127.0.0.1}\n"); + Files.writeString( + fixture.applicationYaml(), + "required: ${APP_REQUIRED}\nredis: ${APP_REDIS_HOST:redis.internal}\n"); + + // when + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> + EnvContractVerifier.verify( + fixture.envFile().toFile(), + List.of(fixture.applicationYaml().toFile(), profile.toFile()), + fixture.registry().toFile(), + List.of(), + fixture.metadataClasspath(), + List.of("app.redis."), + List.of("APP_REDIS_"), + List.of())); + + // then + assertTrue( + failure + .getMessage() + .contains( + "APP_REDIS_HOST: the shipped configuration defaults to 'redis.internal', the" + + " registry default is 'localhost'")); + assertTrue(!failure.getMessage().contains("127.0.0.1"), failure.getMessage()); + } + + private static EnvContractResult verify(Fixture fixture) { + return EnvContractVerifier.verify( + fixture.envFile().toFile(), + List.of(fixture.applicationYaml().toFile()), + fixture.registry().toFile(), + List.of(), + fixture.metadataClasspath(), + List.of("app.redis."), + List.of("APP_REDIS_"), + List.of()); + } + private static EnvContractResult verifyWithOperatorFiles( Fixture fixture, Path operatorFile, Path... otherModuleClasses) { List classpath = new ArrayList<>(fixture.metadataClasspath()); @@ -435,7 +596,7 @@ class EnvContractVerifierTest { applicationYaml, "required: ${APP_REQUIRED}\nredis: ${APP_REDIS_HOST:localhost}\n"); Files.writeString( registry, - "- name: APP_REQUIRED\n type: string\n default: none\n" + "- name: APP_REQUIRED\n type: string\n default: required\n" + "- name: APP_REDIS_HOST\n property: app.redis.host\n type: string\n default: localhost\n"); Files.writeString(metadata, "{\"properties\":[{\"name\":\"app.redis.host\"}]}"); return new Fixture(repositoryRoot, envFile, applicationYaml, registry, redisClasses, metadata); diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 8d362b5a..3df26fc2 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -1,13 +1,18 @@ # Registry: Env Keys # Schema owner: feature-contract-registry-governance # Owner branch: feature-env-driven-runtime-configuration -# Last updated: 2026-09-25 +# Last updated: 2026-11-12 # # 표기 규칙 # - 애플리케이션이 가진 env는 모두 `APP_` 접두어를 쓴다(D2, 2026-06-05). Spring 속성으로 이어지는 # datasource·server 등의 키도 APP_*로 바꿨다(예: SERVER_PORT -> APP_SERVER_PORT). -# - Spring 런타임이 직접 읽는 env만 원래 이름으로 둔다: SPRING_*와 SPRING_PROFILES_ACTIVE -# (D6 — profile 선택자는 APP_가 아니라 Spring 자체 이름이다). +# - 원래 이름으로 두는 것: Spring Boot 이름공간(SPRING_*·MANAGEMENT_*·SERVER_*, profile 선택자 SPRING_PROFILES_ACTIVE +# 포함 — D6), OpenTelemetry 규격 이름(OTEL_*), 그리고 APP_ 통일 전에 퍼진 두 이름(SECURITY_PUBLIC_PATHS, +# PRESENTATION_API_BASE_PATH, 맨 아래 절). 새 키는 APP_를 쓴다. +# - 배포 설정의 placeholder는 접두어와 상관없이 모두 행이 있어야 한다(verifyEnvKeys, 2026-11-12부터). +# - `default`는 배포 설정의 placeholder 기본값과 같고, .env.example은 그 값을 쓴다. 기본값이 아닌 권장값을 쓰는 +# 행은 `example`에 그 값을 둔다. 빈 줄은 빈 문자열로 들어가 기본값을 덮으므로, 빈 칸은 기본값이 없는 키뿐이다. +# - `deprecated_orphaned: true` 행은 배포 설정이 읽지 않고 .env.example에도 없다(둘 다 verifyEnvKeys가 본다). # - `classification: secret` 행은 secrets-classification.yaml을 가리키기만 한다. 행 전체는 그 파일이 가진다. # - reload_policy 기본값 = `restart-only` (env-driven branch "config reload: no runtime reload" — 실행 중 # 다시 읽지 않는다). @@ -666,7 +671,7 @@ env_keys: - name: APP_LOG_LEVEL_SQL # source: feature-log-management-contract — JPA/JDBC SQL 패키지 레벨 (DEBUG면 SQL을 찍는다) type: enum - default: WARN + default: INFO allowed_values: [TRACE, DEBUG, INFO, WARN, ERROR, OFF] classification: public-config required: false @@ -938,14 +943,16 @@ env_keys: - name: APP_SECURITY_CORS_MAX_AGE # source: feature-security-operational-baseline 2026-05-22 # "preflight max-age 600s default" - type: duration - default: 600s + # 단위: 초. 이 값은 app.cors.max-age-seconds(CorsSettings의 long)로 간다 — "600s"는 바인딩되지 않아 + # dev·prod 기동이 실패한다. 이 행이 duration / 600s라 했고 .env.example이 그 값을 복사했다(2026-11-12 리뷰). + type: integer + default: 600 allowed_values: null classification: public-config required: false reload_policy: restart-only owner_branch: feature-security-operational-baseline - validation: spring_duration_shorthand + validation: non_negative_integer_seconds compatibility_impact: behavior-change required_test: security-contract:cors-preflight-max-age @@ -1425,7 +1432,7 @@ env_keys: - name: APP_RATE_LIMIT_REDIS_COMMAND_TIMEOUT type: duration - default: 1s + default: 200ms allowed_values: null classification: public-config required: false @@ -2545,10 +2552,9 @@ env_keys: required_test: redis-contract:semantic-probe-staleness-bounded - name: APP_CACHE_REDIS_KEY_HMAC_SECRET - # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 - # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. - deprecated_orphaned: true - removal_deadline: 2026-11-30 + # 2026-09-25 capability 포장 때 cache-redis 모듈 기본 설정(config/module-defaults/cache-redis.yml)이 + # app.capabilities.cache.*에 이 키를 다시 묶었다. 2026-08-10 폐기 표시가 그 뒤로 틀린 채 남아 있었다 + # (2026-11-12 리뷰, verifyEnvKeys가 이제 폐기 행을 읽는 placeholder를 잡는다). type: string default: null allowed_values: null @@ -2561,12 +2567,11 @@ env_keys: required_test: cache-contract:redis-hmac-secret-bounded - name: APP_CACHE_REDIS_COMMAND_TIMEOUT - # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 - # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. - deprecated_orphaned: true - removal_deadline: 2026-11-30 + # 2026-09-25 capability 포장 때 cache-redis 모듈 기본 설정(config/module-defaults/cache-redis.yml)이 + # app.capabilities.cache.*에 이 키를 다시 묶었다. 2026-08-10 폐기 표시가 그 뒤로 틀린 채 남아 있었다 + # (2026-11-12 리뷰, verifyEnvKeys가 이제 폐기 행을 읽는 placeholder를 잡는다). type: duration - default: 2s + default: 200ms allowed_values: null classification: public-config required: false @@ -2610,7 +2615,7 @@ env_keys: - name: APP_CACHE_REDIS_POSITIVE_SOFT_TTL type: duration - default: null + default: 30s allowed_values: null classification: public-config required: false @@ -2668,10 +2673,9 @@ env_keys: required_test: cache-contract:redis-namespace-environment-bound - name: APP_CACHE_REDIS_SEMANTIC_REGION - # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 - # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. - deprecated_orphaned: true - removal_deadline: 2026-11-30 + # 2026-09-25 capability 포장 때 cache-redis 모듈 기본 설정(config/module-defaults/cache-redis.yml)이 + # app.capabilities.cache.*에 이 키를 다시 묶었다. 2026-08-10 폐기 표시가 그 뒤로 틀린 채 남아 있었다 + # (2026-11-12 리뷰, verifyEnvKeys가 이제 폐기 행을 읽는 placeholder를 잡는다). type: string default: default allowed_values: null @@ -3860,6 +3864,8 @@ env_keys: # source: persistence-mongo techlead review C1. Spring Boot 4는 이 자체 키를 spring.mongodb.uri로 쓴다. # 유효한 연결 출처 둘 중 하나다. 다른 하나는 고른 typed profile의 uri-secret을 MongoCredentialResolver로 푼 # 값이다. + property: spring.mongodb.uri + owner_module: adapter-outbound-persistence-mongo type: string default: null allowed_values: null @@ -4072,6 +4078,22 @@ env_keys: validation: boolean compatibility_impact: none required_test: off-state-zero-side-effects-and-env-round-trip + - name: APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL + # 2026-11-12 등록: 지금 구현이 여는 listener는 loopback plaintext뿐이라, 모듈을 켠 배포는 이 값을 true로 + # 명시해야 기동한다(GrpcServerSettings, grpc README 「켜기와 끄기」). registry에 없어 운영자가 찾을 곳이 없었다. + property: app.grpc.server.allow-insecure-local + owner_module: adapter-inbound-grpc + type: boolean + default: false + allowed_values: [true, false] + classification: security-relevant + required: false + required_when: gRPC 모듈이 런타임에 있고 app.grpc.server.enabled가 true일 때 + reload_policy: restart-only + owner_branch: refactor/maturity-review-2026-11 + validation: boolean + compatibility_impact: none + required_test: adapter-contract:grpc-plaintext-requires-explicit-opt-in - name: APP_GRAPHQL_ENABLED # 2026-09-25 capability 포장: 모듈은 있으면 켜진다(모듈 자신의 설정 yml이 이 키를 기본 true로 잇는다). # false가 명시적으로 끄는 값이다. 빌드에 모듈이 없는 것이 보통의 꺼진 상태다. @@ -4846,6 +4868,7 @@ env_keys: owner_module: adapter-outbound-notification type: integer default: null + example: 587 allowed_values: null classification: public-config required: false @@ -4897,6 +4920,7 @@ env_keys: owner_module: adapter-outbound-notification type: boolean default: null + example: true allowed_values: null classification: public-config required: false @@ -4914,6 +4938,7 @@ env_keys: owner_module: adapter-outbound-notification type: boolean default: null + example: true allowed_values: null classification: public-config required: false @@ -4931,6 +4956,7 @@ env_keys: owner_module: adapter-outbound-notification type: integer default: null + example: 5000 allowed_values: null classification: public-config required: false @@ -4948,6 +4974,7 @@ env_keys: owner_module: adapter-outbound-notification type: integer default: null + example: 10000 allowed_values: null classification: public-config required: false @@ -4965,6 +4992,7 @@ env_keys: owner_module: adapter-outbound-notification type: integer default: null + example: 10000 allowed_values: null classification: public-config required: false @@ -5270,3 +5298,161 @@ env_keys: validation: positive_duration compatibility_impact: behavior-change required_test: adapter-contract:notification-callback-replay + + # === 원래 이름으로 읽는 placeholder (2026-11-12 등록) === + # 배포 설정이 읽는데 행이 없던 이름이다. verifyEnvKeys가 APP_ 밖 placeholder를 보지 않아 빠졌다. 이름을 APP_로 + # 바꾸면 파생 서비스의 배포 env가 소리 없이 무시되므로 지금 이름 그대로 등록한다(바꾸는 것은 소유자 결정). + # SPRING_JACKSON_DESER_*·SPRING_JACKSON_SER_*·SPRING_BANNER_MODE는 Spring relaxed 이름이 아니라 application.yml + # placeholder가 만든 이름이다. relaxed 이름(예: SPRING_JACKSON_DESERIALIZATION_FAIL_ON_UNKNOWN_PROPERTIES, + # SPRING_MAIN_BANNER_MODE)도 같은 속성을 덮고, 둘 다 있으면 relaxed 이름이 이긴다(환경 변수 소스가 yml보다 앞선다). + + - name: SECURITY_PUBLIC_PATHS + # 인증을 건너뛰는 경로 CSV(app.security.public-paths). 기본값은 API base path 뒤의 healthcheck 하나이고 + # docs/security/public-paths-snapshot.txt가 그 기본값을 고정한다. 운영자 값은 스냅숏 밖이다. + property: app.security.public-paths + type: csv + default: /v1/healthcheck + allowed_values: null + classification: security-relevant + required: false + reload_policy: restart-only + owner_branch: feature-security-operational-baseline + validation: csv_of_absolute_paths + compatibility_impact: behavior-change + required_test: security-contract:public-path-snapshot + + - name: PRESENTATION_API_BASE_PATH + # 모든 controller 앞에 붙는 경로(presentation.api-base-path). 빈 값이면 접두어 없음. SECURITY_PUBLIC_PATHS의 + # 기본값도 이 값에서 나온다. + type: string + default: /v1 + allowed_values: null + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-api-contract-baseline + validation: leading_slash_path_or_empty + compatibility_impact: behavior-change + required_test: web-contract:api-base-path-prefix + + - name: SPRING_BANNER_MODE + property: spring.main.banner-mode + type: enum + default: console + allowed_values: [off, console, log] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: enum_in_allowed_values + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_MAIN_LAZY_INITIALIZATION + property: spring.main.lazy-initialization + type: boolean + default: false + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_MAIN_LOG_STARTUP_INFO + property: spring.main.log-startup-info + type: boolean + default: true + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_THREADS_VIRTUAL_ENABLED + property: spring.threads.virtual.enabled + type: boolean + default: true + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_JACKSON_DESER_FAIL_ON_UNKNOWN_PROPERTIES + # 요청 경계 Jackson 정책(web AGENTS B1). 끄면 잘못된 본문을 조용히 받아들인다. + property: spring.jackson.deserialization.fail-on-unknown-properties + type: boolean + default: true + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_JACKSON_DESER_FAIL_ON_NULL_FOR_PRIMITIVES + # 요청 경계 Jackson 정책(web AGENTS B1). 끄면 잘못된 본문을 조용히 받아들인다. + property: spring.jackson.deserialization.fail-on-null-for-primitives + type: boolean + default: true + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_JACKSON_DESER_FAIL_ON_IGNORED_PROPERTIES + # 요청 경계 Jackson 정책(web AGENTS B1). 끄면 잘못된 본문을 조용히 받아들인다. + property: spring.jackson.deserialization.fail-on-ignored-properties + type: boolean + default: true + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_JACKSON_DESER_READ_UNKNOWN_ENUM_VALUES_AS_NULL + # 요청 경계 Jackson 정책(web AGENTS B1). 끄면 잘못된 본문을 조용히 받아들인다. + property: spring.jackson.datatype.enum.read-unknown-enum-values-as-null + type: boolean + default: false + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder + + - name: SPRING_JACKSON_SER_WRITE_DATES_AS_TIMESTAMPS + # 요청 경계 Jackson 정책(web AGENTS B1). 끄면 잘못된 본문을 조용히 받아들인다. + property: spring.jackson.datatype.datetime.write-dates-as-timestamps + type: boolean + default: false + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: feature-env-driven-runtime-configuration + validation: boolean + compatibility_impact: behavior-change + required_test: env-contract:spring-runtime-placeholder diff --git a/docs/upgrade/2026-11-round9-env-keys.md b/docs/upgrade/2026-11-round9-env-keys.md new file mode 100644 index 00000000..02ead116 --- /dev/null +++ b/docs/upgrade/2026-11-round9-env-keys.md @@ -0,0 +1,45 @@ +# 업그레이드 안내 — 2026-11 env 키 계약 정리 + +- 범위: `docs/registries/env-keys.yaml`·`.env.example`·`verifyEnvKeys`를 배포 설정의 실제 동작에 맞춘 변경. 앱이 읽는 키와 + 그 기본값은 바뀌지 않았다. 바뀐 것은 예시 파일의 값, registry 행, 그리고 검사가 실패로 보는 범위다. +- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 env 계약 발견 + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 예전 `.env.example`을 복사해 `.env`나 +배포 env를 만든 서비스, 자기 배포 설정에 placeholder를 더한 서비스다. + +## 2. 할 일 + +| # | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | +| 1 | 옛 `.env.example`에서 복사한 `APP_DATASOURCE_CONNECTION_TIMEOUT=5s`를 `5000`(밀리초)으로 바꾼다 | JPA를 켠 배포가 Hikari 바인딩 실패로 기동하지 않는다 | persistence-jpa 선택 | +| 2 | 옛 예시의 `APP_SECURITY_CORS_MAX_AGE=600s`를 `600`(초)으로 바꾼다 | dev·prod 기동이 `app.cors.max-age-seconds` 바인딩 실패로 멈춘다(local은 profile 리터럴이 덮어 안 보인다) | 예시를 복사한 서비스 | +| 3 | 옛 예시에서 복사한 값 다섯을 확인한다: `APP_CACHE_REDIS_COMMAND_TIMEOUT=2s`, `APP_RATE_LIMIT_REDIS_COMMAND_TIMEOUT=1s`, `APP_LOG_LEVEL_SQL=WARN`, `APP_SERVER_FORWARD_HEADERS_STRATEGY=native`, `APP_CACHE_REDIS_POSITIVE_SOFT_TTL=`(빈 값). 새 예시는 기본값(`200ms`, `200ms`, `INFO`, `none`, `30s`)을 쓴다 | 그 값들이 env가 없을 때와 다르게 동작한다. 특히 `native`는 프록시를 거치지 않는 배포에서 호출자가 보낸 forwarded 헤더를 믿는다 | 예시를 복사한 서비스 | +| 4 | `.env`·배포 env에 남은 `deprecated_orphaned` 키(예: `APP_CACHE_REDIS_TTL_JITTER`, `APP_SESSION_IDLE_TIMEOUT`, `APP_CACHE_REDIS_L1_*`)를 지운다. 무엇이 대신하는지는 registry 행 주석에 있다 | 아무 일도 하지 않는 값을 켠 것으로 믿는다 | 예시를 복사한 서비스 | +| 5 | 서비스가 배포 설정(profile 파일 밖의 `application.yml`, `config/*.yml`, 모듈 `config/module-defaults/*.yml`)에 더한 placeholder는 접두어와 상관없이 registry에 행을 더하고, 행의 `default`를 placeholder 기본값과 같게 둔다 | `:app-bootstrap:verifyEnvKeys`(`mainCheck` 안)가 실패한다 | 자기 placeholder를 더한 서비스 | +| 6 | `.env.example`의 값을 registry `default`(또는 행의 `example`)와 같게 둔다. 기본값이 있는 키를 빈 줄로 두지 않는다 | 같은 검사가 실패한다 | 자기 키를 예시에 더한 서비스 | + +## 3. 다시 살린 registry 행 + +아래 셋은 2026-08-10 폐기로 적혀 있었지만, 2026-09-25 capability 포장 뒤로 cache-redis 모듈 설정이 다시 읽는다. +`deprecated_orphaned`를 지우고 기본값을 모듈 설정에 맞췄다. + +| 키 | 읽는 곳 | 기본값 | +| --- | --- | --- | +| `APP_CACHE_REDIS_COMMAND_TIMEOUT` | `app.capabilities.cache.command-timeout` | `200ms`(registry가 `2s`라고 적었다) | +| `APP_CACHE_REDIS_SEMANTIC_REGION` | `app.capabilities.cache.semantic-region` | `default` | +| `APP_CACHE_REDIS_KEY_HMAC_SECRET` | `secret://environment/APP_CACHE_REDIS_KEY_HMAC_SECRET` 참조 | 없음(비밀) | + +## 4. 새로 등록한 이름 + +배포 설정이 읽는데 registry에 없던 이름이다. 이름은 그대로이고 동작도 같다. + +- `SECURITY_PUBLIC_PATHS`, `PRESENTATION_API_BASE_PATH` — APP_ 통일 전에 퍼진 이름이다. 바꾸면 파생 서비스의 배포 env가 + 소리 없이 무시되어 그대로 둔다. +- `SPRING_BANNER_MODE`, `SPRING_JACKSON_DESER_*` 넷, `SPRING_JACKSON_SER_WRITE_DATES_AS_TIMESTAMPS`, + `SPRING_MAIN_LAZY_INITIALIZATION`, `SPRING_MAIN_LOG_STARTUP_INFO`, `SPRING_THREADS_VIRTUAL_ENABLED` — `application.yml` + placeholder 이름이다. Spring relaxed 이름도 같은 속성을 덮고, 둘 다 있으면 relaxed 이름이 이긴다. +- `APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL` — gRPC 모듈을 켠 배포가 기동하려면 `true`로 명시하는 값이다. +- `.env.example`에 `MANAGEMENT_SERVER_ADDRESS=127.0.0.1`을 더했다. Kubernetes 프로브와 Prometheus는 pod IP로 붙으므로 + 원격에서 읽으려면 이 값을 바꾼다. From ebbfafe4549e6448c531b54813200202f642cefa Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 01:48:48 +0900 Subject: [PATCH 2/2] =?UTF-8?q?docs(adapter):=20grpc=C2=B7cache-redis=20RE?= =?UTF-8?q?ADME=EC=9D=98=20env=20=ED=82=A4=20=EC=95=88=EB=82=B4=EB=A5=BC?= =?UTF-8?q?=20registry=EC=97=90=20=EB=A7=9E=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit grpc README는 "전용 APP_* 키는 registry에 없다"고 했지만 끄는 값 APP_GRPC_SERVER_ENABLED가 있고, 기동에 꼭 두라는 APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL은 registry에 없었다(앞 커밋이 등록). cache-redis README는 운영 비밀로 읽는 곳 없는 폐기 키 셋 (APP_CACHE_REDIS_PASSWORD, APP_IDEMPOTENCY_/LEASE_REDIS_KEY_HMAC_SECRET)을 넣으라고 했다. 자격 증명은 APP_REDIS_AUTHENTICATION_*의 secret 참조다. 검증: python3 scripts/check-docs.py rc=0. --- src/adapter/inbound/grpc/README.md | 7 ++++--- src/adapter/outbound/cache-redis/README.md | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/adapter/inbound/grpc/README.md b/src/adapter/inbound/grpc/README.md index e713d0cf..81ecdc3e 100644 --- a/src/adapter/inbound/grpc/README.md +++ b/src/adapter/inbound/grpc/README.md @@ -23,9 +23,10 @@ 이 줄을 지우면 서버, 포트, 설정 바인딩이 모두 함께 빠진다. - 켜기와 끄기: 모듈이 있으면 켜진다. `app.grpc.server.enabled=false`로만 끈다. -- 필요한 설정: 전용 `APP_*` env 키는 registry에 없다. 켜진 상태에서 지금 구현이 받는 listener는 - loopback plaintext뿐이라 `app.grpc.server.allow-insecure-local=true`(env - `APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL=true`)를 명시해야 기동한다. 선택: `app.grpc.server.port` +- 필요한 설정: registry 행은 끄는 값 `APP_GRPC_SERVER_ENABLED`와 `APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL` 둘이다. + 켜진 상태에서 지금 구현이 받는 listener는 loopback plaintext뿐이라 + `APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL=true`(`app.grpc.server.allow-insecure-local`)를 명시해야 기동한다. 나머지 + `app.grpc.server.*`는 registry 행 없이 Spring relaxed 이름(`APP_GRPC_SERVER_PORT` 등)으로 받는다. 선택: `app.grpc.server.port` (기본 9090), `.bind-address`(기본 127.0.0.1), `.reflection-enabled`, `.shutdown-grace-seconds`, `.shutdown-drain-seconds`, 그리고 아래 「서버 한도」 절의 전송 한도 키. diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 51cb4fab..265934b3 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -47,7 +47,7 @@ runtimeOnly project(':adapter:outbound:cache-redis') // brings :adapter:outbou | namespace | `APP_REDIS_NAMESPACE_ENVIRONMENT`, `APP_REDIS_NAMESPACE_SERVICE`, `APP_REDIS_NAMESPACE_DOMAIN` | | role | `APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis` | | role 조정 | `APP_CACHE_REDIS_*`, `APP_RATE_LIMIT_*`, `APP_LEASE_REDIS_*`, `APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT` | -| 운영 비밀 값(고른 role마다) | `APP_CACHE_REDIS_PASSWORD`, `APP_CACHE_REDIS_KEY_HMAC_SECRET`, `APP_RATE_LIMIT_REDIS_PASSWORD`, `APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET`, `APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET`, `APP_LEASE_REDIS_KEY_HMAC_SECRET` | +| 운영 비밀 값(고른 role마다) | Redis 접속 자격 증명은 `APP_REDIS_AUTHENTICATION_*`가 가리키는 `secret://` 참조다. 캐시 key HMAC은 `APP_CACHE_REDIS_KEY_HMAC_SECRET`, rate limit은 `APP_RATE_LIMIT_REDIS_PASSWORD`·`APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET`. 멱등·lease는 호출자가 준 digest를 써서 비밀이 없다. role마다 따로 두던 `APP_CACHE_REDIS_PASSWORD`, `APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET`, `APP_LEASE_REDIS_KEY_HMAC_SECRET`는 읽는 곳이 없다(registry `deprecated_orphaned`) | ## 켜기와 조립