review-followup Wave 3 라운드 3(P22): Redis runtime·SDK 분리, 좁은 semantic 포트, startup rule, lease fencing 계약

- pub/sub 표면 삭제(G-6b·G-4i — 소비자 0, capability 규칙 3): SDK pub/sub·runtime gateway·PUBSUB lane·env 키 2개
- runtime을 `…cache.redis.runtime`으로(split package 해소), runtime은 소비자가 쓰는 8개 명령(`SemanticRedisCommands`)만,
  118개 메서드 gateway는 redis-sdk가 확장. SDK의 blocking·transaction·admin lane은 코드로 조립(env 키 4개 삭제)
- EVALSHA+NOSCRIPT 재로드 헬퍼 하나(메시지에만 NOSCRIPT가 온 경우도 재로드 — `LeaseScriptsTest` FAIL→PASS)
- startup rule 목록 + runner 하나(환경 검사 8개, exit code·문구 유지), Redis secret 요구는 모듈이 기여,
  ratelimit 정책을 cache-redis 밖으로, lease fencing 계약 테스트(fake·어댑터·실제 Redis)
- 통합: redis-sdk 테스트 2개가 옛 split package 경로를 보던 것 수정(ORCH-new-4)

검증: ./gradlew check architectureCheck verifyDependencyLocks :app-bootstrap:verifyEnvKeys configContractCheck
:app-bootstrap:integrationTest :sample-portfolio:integrationTest :sample-portfolio:systemTest --continue 통과(682 task),
Redis 7.4 standalone topology lane: runtime 7 · sdk 14 · cache-redis 19, 실패·skip 0

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-29 13:39:24 +09:00
co-authored by Claude Opus 5.5
parent 486d85a603
commit 4f4bd1fd34
283 changed files with 5499 additions and 5120 deletions
+5
View File
@@ -82,6 +82,11 @@ configurations, Redis as one 376-line class.
error codes, exceptions, `StartupFailures`, `StartupValidationContext`, `StartupOrder`,
`ReadinessGroup`, `RuntimeWarnings`), so capability modules fail the same way without depending on
this leaf. `runtime/startup/` keeps only `StartupFailureExceptionReporter`.
- **An environment-only guard is a `StartupRule` bean** (`support.startup`): it returns violations,
and the one `StartupRuleRunner` raises them. A guard that needs another bean stays a bean. A
capability's production secrets are the capability's: its module contributes a
`RequiredProductionSecrets` bean, and `SecretSourceValidator` checks the names without knowing
which roles exist.
## Decomposition threshold
+11
View File
@@ -144,10 +144,21 @@ README의 "startup" 절에 있다.
`docs/registries/secrets-classification.yaml`의 secret 행과 정확히 일치해야 하며,
`SecretsClassificationRegistryTest`가 1:1 일치를 단언한다. 그래서 레지스트리에 시크릿을 추가/제거하고
이 상수를 갱신하지 않으면 빌드가 깨진다 — drift 를 컴파일·테스트 단계에서 잡는다.
- **capability의 시크릿은 그 모듈이 기여한다.** 선택한 역할에만 필요한 시크릿(Redis 역할별
비밀번호·HMAC 등)은 이 상수에 없다. 소유 모듈이 `RequiredProductionSecrets` 빈으로 "지금 선택된
역할이 요구하는 시크릿"을 알려 주고(Redis는 `cache-redis`의 `RedisProductionSecrets`), 이 가드는
그 이름들이 백엔드에서 풀리는지만 본다. 레지스트리에서는 그 행들이 `required_when`을 가진다.
- **prod 판정은 대소문자 무시다.** `SPRING_PROFILES_ACTIVE=PROD` 같은 배포 오타도 prod 가드를
발동시켜야 하므로 `equalsIgnoreCase`로 비교한다(`Environment#matchesProfiles`는 대소문자를 구분해
"PROD"를 통과시킨다).
환경만 읽는 검사(`RuntimeNumericBoundsValidator`, `ErrorDetailExposureSafetyValidator`와
persistence-jpa의 datasource·Flyway·OSIV·TLS·vendor·Hikari 검사)는 `StartupRule`이다: 위반 목록만
돌려주고, `adapter:outbound:support`의 `StartupRuleRunner` 하나가 모든 싱글톤 생성 후 규칙마다 그
phase의 종료 코드로 실패시킨다. 다른 bean이 필요한 검사(`SecretSourceValidator`의 `SecretSourcePort`,
`StartupSafetyValidator`의 bean factory, persistence-jpa의 datasource 검사)는 계속 bean이고, 부팅 전에
돌아야 하는 profile 규칙(`RuntimeEnvironmentProfileValidator`)은 `EnvironmentPostProcessor`로 남는다.
관계형 설정 가드(`HikariPoolConstraintValidator`, `OpenInViewSafetyValidator`,
`JpaDangerousConfigurationGuard`, `PostgreSqlTransportSecurityValidator`,
`PersistenceVendorProdSafetyValidator`)는 `adapter:outbound:persistence-jpa`로 옮겼다. 풀 크기
@@ -1,13 +1,13 @@
package dev.caskeleton.bootstrap.runtime;
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import dev.caskeleton.adapter.outbound.support.startup.StartupPhase;
import dev.caskeleton.adapter.outbound.support.startup.StartupRule;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.core.env.Environment;
/**
@@ -16,7 +16,7 @@ import org.springframework.core.env.Environment;
* each is an environment override away in {@code application.yml}, so a YAML default alone does not
* hold them off in prod.
*/
public class ErrorDetailExposureSafetyValidator implements SmartInitializingSingleton {
public class ErrorDetailExposureSafetyValidator implements StartupRule {
/** Each key that must stay {@code never}, with the name an operator would have set. */
private static final Map<String, String> MUST_BE_NEVER = new LinkedHashMap<>();
@@ -30,16 +30,21 @@ public class ErrorDetailExposureSafetyValidator implements SmartInitializingSing
private static final String INCLUDE_EXCEPTION = "spring.web.error.include-exception";
private final Environment environment;
public ErrorDetailExposureSafetyValidator(Environment environment) {
this.environment = environment;
@Override
public StartupPhase phase() {
return StartupPhase.PROFILE_CHECK;
}
@Override
public void afterSingletonsInstantiated() {
public String summary() {
return "prod profile requires error details to stay out of responses (include-* = never, "
+ "include-exception = false), but found";
}
@Override
public List<String> violations(Environment environment) {
if (!RuntimeProfileSnapshot.from(environment).isProduction()) {
return;
return List.of();
}
List<String> violations = new ArrayList<>();
MUST_BE_NEVER.forEach(
@@ -53,12 +58,7 @@ public class ErrorDetailExposureSafetyValidator implements SmartInitializingSing
if (includeException != null && "true".equals(normalized(includeException))) {
violations.add(INCLUDE_EXCEPTION + "=true");
}
if (!violations.isEmpty()) {
throw StartupFailures.profileMismatch(
"prod profile requires error details to stay out of responses (include-* = never, "
+ "include-exception = false), but found "
+ String.join(", ", violations));
}
return violations;
}
private static String normalized(String value) {
@@ -1,16 +1,16 @@
package dev.caskeleton.bootstrap.runtime;
import dev.caskeleton.adapter.outbound.support.startup.StartupPhase;
import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext;
import dev.caskeleton.adapter.outbound.support.startup.StartupRule;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.core.env.Environment;
/**
* Fail-fast startup guard for the high-risk numeric runtime knobs (pool/thread sizing). Reads the
* resolved Spring property; an absent key is skipped. See README for the design rationale.
*/
public class RuntimeNumericBoundsValidator implements SmartInitializingSingleton {
public class RuntimeNumericBoundsValidator implements StartupRule {
/** A numeric property bound: resolved Spring key, the {@code APP_*} env key, and minimum. */
record Bound(String springKey, String envKey, int minInclusive) {}
@@ -25,23 +25,27 @@ public class RuntimeNumericBoundsValidator implements SmartInitializingSingleton
new Bound("server.tomcat.threads.min-spare", "APP_SERVER_TOMCAT_MIN_SPARE_THREADS", 0),
new Bound("server.tomcat.accept-count", "APP_SERVER_TOMCAT_ACCEPT_COUNT", 0));
private final Environment environment;
public RuntimeNumericBoundsValidator(Environment environment) {
this.environment = environment;
@Override
public StartupPhase phase() {
return StartupPhase.ENV_VALIDATION;
}
@Override
public void afterSingletonsInstantiated() {
StartupValidationContext violations =
StartupValidationContext.forPhase(StartupPhase.ENV_VALIDATION);
public String summary() {
return "invalid runtime numeric configuration (feature-env-driven-runtime-configuration "
+ "D10 — no lenient default)";
}
@Override
public List<String> violations(Environment environment) {
List<String> violations = new ArrayList<>();
for (Bound bound : BOUNDS) {
Integer value = environment.getProperty(bound.springKey(), Integer.class);
if (value == null) {
continue; // absent → skip (framework default owns it)
}
if (value < bound.minInclusive()) {
violations.reject(
violations.add(
bound.envKey()
+ " ("
+ bound.springKey()
@@ -51,8 +55,6 @@ public class RuntimeNumericBoundsValidator implements SmartInitializingSingleton
+ value);
}
}
violations.failIfViolated(
"invalid runtime numeric configuration (feature-env-driven-runtime-configuration "
+ "D10 — no lenient default)");
return violations;
}
}
@@ -4,7 +4,6 @@ import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
/**
* Wires the runtime-safety startup fail-fast validators into the running application. See README
@@ -21,12 +20,12 @@ public class RuntimeSafetyConfig {
}
@Bean
RuntimeNumericBoundsValidator runtimeNumericBoundsValidator(Environment environment) {
return new RuntimeNumericBoundsValidator(environment);
RuntimeNumericBoundsValidator runtimeNumericBoundsValidator() {
return new RuntimeNumericBoundsValidator();
}
@Bean
ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator(Environment environment) {
return new ErrorDetailExposureSafetyValidator(environment);
ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator() {
return new ErrorDetailExposureSafetyValidator();
}
}
@@ -1,6 +1,8 @@
package dev.caskeleton.bootstrap.runtime;
import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets;
import dev.caskeleton.application.outbound.SecretSourcePort;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -22,7 +24,10 @@ public class SecretSourceConfig {
@Bean
SecretSourceValidator secretSourceValidator(
ConfigurableEnvironment environment, SecretSourcePort secretSource) {
return new SecretSourceValidator(environment, secretSource);
ConfigurableEnvironment environment,
SecretSourcePort secretSource,
ObjectProvider<RequiredProductionSecrets> contributed) {
return new SecretSourceValidator(
environment, secretSource, contributed.orderedStream().toList());
}
}
@@ -1,6 +1,7 @@
package dev.caskeleton.bootstrap.runtime;
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets;
import dev.caskeleton.adapter.outbound.support.startup.StartupPhase;
import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext;
import dev.caskeleton.application.outbound.SecretSourcePort;
@@ -22,31 +23,14 @@ public class SecretSourceValidator implements SmartInitializingSingleton {
static final String LOCAL_DEV_SENTINEL_PREFIX = "__LOCAL_DEV_";
/**
* The one global Redis switch, bound from {@code APP_REDIS_ENABLED}.
*
* <p>There is deliberately no second capability switch. {@code APP_CACHE_REDIS_ENABLED} used to
* read like one, which is how a deployment with no Redis at all still had to supply cache Redis
* credentials to reach a running state.
*/
public static final String REDIS_ENABLED_PROPERTY = "app.redis.enabled";
/**
* Secret keys that must be injected under the {@code prod} profile. {@code
* SecretsClassificationRegistryTest} asserts this list matches the registry 1:1. See README for
* the design rationale.
* Secret keys that must be injected under the {@code prod} profile whatever the deployment
* selected. {@code SecretsClassificationRegistryTest} asserts this list matches the registry 1:1.
* A capability's own secrets are not listed here: the module that owns them contributes them
* ({@link RequiredProductionSecrets}) for the roles the deployment selected, and the registry
* marks them {@code required_when}. See README for the design rationale.
*/
public static final List<String> REQUIRED_PROD_SECRETS =
List.of(
"APP_DATASOURCE_PASSWORD",
"APP_CACHE_REDIS_PASSWORD",
"APP_CACHE_REDIS_KEY_HMAC_SECRET",
"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_PRIVACY_PSEUDONYMIZATION_SALT");
List.of("APP_DATASOURCE_PASSWORD", "APP_PRIVACY_PSEUDONYMIZATION_SALT");
/**
* The relational credential, required only while relational persistence is on. The switch is set
@@ -61,10 +45,15 @@ public class SecretSourceValidator implements SmartInitializingSingleton {
private final ConfigurableEnvironment environment;
private final SecretSourcePort secretSource;
private final List<RequiredProductionSecrets> contributed;
public SecretSourceValidator(ConfigurableEnvironment environment, SecretSourcePort secretSource) {
public SecretSourceValidator(
ConfigurableEnvironment environment,
SecretSourcePort secretSource,
List<RequiredProductionSecrets> contributed) {
this.environment = environment;
this.secretSource = secretSource;
this.contributed = List.copyOf(contributed);
}
@Override
@@ -102,76 +91,23 @@ public class SecretSourceValidator implements SmartInitializingSingleton {
}
private void collectMissingSecretViolations(StartupValidationContext validation) {
Set<String> required = new LinkedHashSet<>();
for (String key : REQUIRED_PROD_SECRETS) {
if (isRedisMaterial(key) && !isRedisRoleSelected(key)) {
continue;
}
if (DATASOURCE_PASSWORD.equals(key) && !isRelationalPersistenceOn()) {
continue;
}
required.add(key);
}
// Each module names the secrets its selected capabilities need. This guard does not know which
// capabilities a module has or how they are selected — it only checks the names resolve.
contributed.forEach(module -> required.addAll(module.requiredSecrets(environment)));
for (String key : required) {
if (secretSource.resolve(key).isEmpty()) {
validation.reject(key + " is missing/blank");
}
}
}
/**
* Reports whether a required secret is Redis material.
*
* <p>The prefix is the role, and every role is spelled {@code APP_<ROLE>_REDIS_...}. Matching on
* the shared infix rather than enumerating roles means a role added later cannot quietly become
* an unconditional production requirement the way the cache role did.
*/
private static boolean isRedisMaterial(String key) {
return key.contains("_REDIS_");
}
/**
* Reports whether the deployment actually selected the Redis role this secret belongs to.
*
* <p>Two conditions, and both must hold. {@code app.redis.enabled} is the single global switch:
* with Redis off nothing Redis-shaped is created, so demanding its credentials would fail a
* deployment over an adapter it never asked for. On top of that the specific role has to be
* bound, because a deployment that runs Redis for its cache owes nothing to the session store.
*/
private boolean isRedisRoleSelected(String key) {
if (!isRedisGloballyEnabled()) {
return false;
}
if (key.startsWith("APP_CACHE_REDIS_")) {
return isRedisCacheBound();
}
if (key.startsWith("APP_RATE_LIMIT_REDIS_")) {
return isSelected("ca-skeleton.capabilities.rate-limit.provider", "disabled", "redis");
}
if (key.startsWith("APP_SESSION_REDIS_")) {
return isSelected("ca-skeleton.security.auth-mode", "jwt", "redis-session");
}
if (key.startsWith("APP_IDEMPOTENCY_REDIS_")) {
return isSelected("ca-skeleton.capabilities.idempotency.provider", "disabled", "redis");
}
if (key.startsWith("APP_LEASE_REDIS_")) {
return isSelected("ca-skeleton.capabilities.lease.provider", "disabled", "redis");
}
// An unrecognised Redis role is required whenever Redis is on: an unknown role must fail
// closed, not silently exempt itself from the production secret contract.
return true;
}
private boolean isRedisGloballyEnabled() {
return Boolean.parseBoolean(environment.getProperty(REDIS_ENABLED_PROPERTY, "false"));
}
private boolean isRedisCacheBound() {
return "redis"
.equalsIgnoreCase(
environment.getProperty("ca-skeleton.capabilities.cache.bindings.default", "disabled"));
}
private boolean isSelected(String property, String fallback, String selecting) {
return selecting.equalsIgnoreCase(environment.getProperty(property, fallback));
}
private boolean isRelationalPersistenceOn() {
return Boolean.parseBoolean(
environment.getProperty(RELATIONAL_PERSISTENCE_PROPERTY, "false").trim());
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfiguration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@@ -15,7 +16,8 @@ import org.springframework.core.env.Environment;
class ErrorDetailExposureSafetyValidatorTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class);
new ApplicationContextRunner()
.withUserConfiguration(StartupRuleAutoConfiguration.class, ValidatorConfig.class);
@ParameterizedTest
@CsvSource({
@@ -67,7 +69,7 @@ class ErrorDetailExposureSafetyValidatorTest {
@Bean
ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator(Environment environment) {
return new ErrorDetailExposureSafetyValidator(environment);
return new ErrorDetailExposureSafetyValidator();
}
}
}
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfiguration;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
@@ -19,7 +20,8 @@ import org.springframework.core.env.Environment;
class RuntimeNumericBoundsValidatorTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class);
new ApplicationContextRunner()
.withUserConfiguration(StartupRuleAutoConfiguration.class, ValidatorConfig.class);
@Test
void nonPositiveMaxThreadsFailsStartupNamingTheAppKey() {
@@ -77,7 +79,7 @@ class RuntimeNumericBoundsValidatorTest {
static class ValidatorConfig {
@Bean
RuntimeNumericBoundsValidator runtimeNumericBoundsValidator(Environment environment) {
return new RuntimeNumericBoundsValidator(environment);
return new RuntimeNumericBoundsValidator();
}
}
}
@@ -2,10 +2,14 @@ package dev.caskeleton.bootstrap.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -26,12 +30,7 @@ class SecretSourceValidatorTest {
/** All required prod secrets set to real (non-sentinel) values. */
private static String[] allRequiredSecretsPresent() {
return new String[] {
"APP_DATASOURCE_PASSWORD=real-db-password",
"APP_CACHE_REDIS_PASSWORD=real-redis-password",
"APP_CACHE_REDIS_KEY_HMAC_SECRET=real-redis-key-hmac-secret",
"APP_RATE_LIMIT_REDIS_PASSWORD=real-rate-limit-redis-password",
"APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET=real-rate-limit-redis-key-hmac-secret",
"APP_PRIVACY_PSEUDONYMIZATION_SALT=real-salt"
"APP_DATASOURCE_PASSWORD=real-db-password", "APP_PRIVACY_PSEUDONYMIZATION_SALT=real-salt"
};
}
@@ -152,71 +151,6 @@ class SecretSourceValidatorTest {
.run(context -> assertThat(context).hasNotFailed());
}
// ---- Redis is optional: no switch, no secret requirement -----------------
@Test
void prodProfileWithoutRedisDoesNotRequireAnyRedisSecret() {
String[] nonRedisSecrets =
Arrays.stream(allRequiredSecretsPresent())
.filter(value -> !value.contains("_REDIS_"))
.toArray(String[]::new);
runner
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod"))
.withPropertyValues(nonRedisSecrets)
.run(context -> assertThat(context).hasNotFailed());
}
@Test
void prodProfileWithRedisExplicitlyDisabledDoesNotRequireAnyRedisSecret() {
String[] nonRedisSecrets =
Arrays.stream(allRequiredSecretsPresent())
.filter(value -> !value.contains("_REDIS_"))
.toArray(String[]::new);
runner
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod"))
.withPropertyValues(nonRedisSecrets)
.withPropertyValues("app.redis.enabled=false")
.run(context -> assertThat(context).hasNotFailed());
}
@Test
void enabledRedisCacheRequiresItsOwnMaterialInProd() {
runner
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod"))
.withPropertyValues(allRequiredSecretsPresent())
.withPropertyValues(
"app.redis.enabled=true",
"ca-skeleton.capabilities.cache.bindings.default=redis",
"APP_CACHE_REDIS_KEY_HMAC_SECRET=")
.run(
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_CACHE_REDIS_KEY_HMAC_SECRET");
});
}
@Test
void redisEnabledWithoutAnyRoleBoundStillRequiresNoRoleSecret() {
String[] nonRedisSecrets =
Arrays.stream(allRequiredSecretsPresent())
.filter(value -> !value.contains("_REDIS_"))
.toArray(String[]::new);
runner
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod"))
.withPropertyValues(nonRedisSecrets)
.withPropertyValues("app.redis.enabled=true")
.run(context -> assertThat(context).hasNotFailed());
}
@Test
void nonProdProfileWithMissingRequiredSecretsIsAllowed() {
runner
@@ -224,130 +158,51 @@ class SecretSourceValidatorTest {
.run(context -> assertThat(context).hasNotFailed());
}
// ---- secrets a module contributes for what the deployment selected -------------------------
@Test
void enabledRateLimitRedisRequiresItsDedicatedSecretsInProd() {
@DisplayName("모듈이 기여한 secret이 prod에서 비어 있으면 기동이 실패한다")
void aSecretAModuleContributedIsRequiredInProd() {
runner
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod"))
.withPropertyValues(allRequiredSecretsPresent())
.withPropertyValues(
"app.redis.enabled=true",
"ca-skeleton.capabilities.rate-limit.provider=redis",
"APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET=")
.withBean(RequiredProductionSecrets.class, () -> environment -> List.of("APP_MODULE_KEY"))
.run(
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET");
});
context ->
assertThat(context.getStartupFailure())
.isInstanceOf(StartupFailureException.class)
.hasMessageContaining("APP_MODULE_KEY is missing/blank"));
}
@Test
void disabledRateLimitRedisDoesNotRequireItsDedicatedSecretsInProd() {
String[] baselineSecrets =
Arrays.stream(allRequiredSecretsPresent())
.filter(value -> !value.startsWith("APP_RATE_LIMIT_REDIS_"))
.toArray(String[]::new);
void aSecretAModuleContributedAndSuppliedStartsCleanly() {
runner
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod"))
.withPropertyValues(baselineSecrets)
.withPropertyValues("ca-skeleton.capabilities.rate-limit.provider=disabled")
.withPropertyValues(allRequiredSecretsPresent())
.withPropertyValues("APP_MODULE_KEY=real-module-key")
.withBean(RequiredProductionSecrets.class, () -> environment -> List.of("APP_MODULE_KEY"))
.run(context -> assertThat(context).hasNotFailed());
}
@Test
void transportEnableAloneDoesNotRequireRedisProviderSecretsInProd() {
String[] baselineSecrets =
Arrays.stream(allRequiredSecretsPresent())
.filter(value -> !value.startsWith("APP_RATE_LIMIT_REDIS_"))
.toArray(String[]::new);
void aSecretAModuleContributedIsNotRequiredOutsideProd() {
runner
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod"))
.withPropertyValues(baselineSecrets)
.withPropertyValues("app.rate-limit.enabled=true")
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("local"))
.withBean(RequiredProductionSecrets.class, () -> environment -> List.of("APP_MODULE_KEY"))
.run(context -> assertThat(context).hasNotFailed());
}
@Test
void selectedRedisIdempotencyRequiresItsHmacMaterialInProd() {
runner
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod"))
.withPropertyValues(allRequiredSecretsPresent())
.withPropertyValues(
"app.redis.enabled=true",
"ca-skeleton.capabilities.idempotency.provider=redis",
"APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET=")
.run(
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET");
});
}
@Test
void selectedRedisEfficiencyLeaseRequiresItsHmacMaterialInProd() {
runner
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod"))
.withPropertyValues(allRequiredSecretsPresent())
.withPropertyValues(
"app.redis.enabled=true",
"ca-skeleton.capabilities.lease.provider=redis",
"APP_LEASE_REDIS_KEY_HMAC_SECRET=")
.run(
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_LEASE_REDIS_KEY_HMAC_SECRET");
});
}
@Test
void redisSessionModeRequiresItsHmacMaterialInProd() {
runner
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod"))
.withPropertyValues(allRequiredSecretsPresent())
.withPropertyValues(
"app.redis.enabled=true",
"ca-skeleton.security.auth-mode=redis-session",
"APP_SESSION_REDIS_PASSWORD=real-session-password",
"APP_SESSION_REDIS_KEY_HMAC_SECRET=")
.run(
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_SESSION_REDIS_KEY_HMAC_SECRET");
});
}
@Configuration
static class ValidatorConfig {
@Bean
SecretSourceValidator secretSourceValidator(ConfigurableEnvironment environment) {
SecretSourceValidator secretSourceValidator(
ConfigurableEnvironment environment,
ObjectProvider<RequiredProductionSecrets> contributed) {
// Default backend (ENVIRONMENT) — the presence check resolves through the port.
return new SecretSourceValidator(
environment, SecretSourceFactory.create(SecretSourceStrategy.ENVIRONMENT, environment));
environment,
SecretSourceFactory.create(SecretSourceStrategy.ENVIRONMENT, environment),
contributed.orderedStream().toList());
}
}
}