review-followup Wave 3 라운드 3(P19): 3-D 공통 유틸 — Sha256·HmacSha256·Backoff·MdcKeys·TenantId, caller 트랜잭션 guard 하나
- shared-contract `Sha256`(약 65벌 흡수, notification `MessageDigestPort` 삭제), `HmacSha256`(서명 헬퍼), `Backoff`("full jitter" 뜻 하나),
`MdcKeys`(gRPC·STOMP에도 상관관계), registry edge application-notification → shared-contract
- application-core `TenantId` 하나로 web·GraphQL tenant 문법 통일, web operation 경로에 tenant 해석(JWT `tenant_id`)
- persistence-jpa `CallerTransaction` 하나(복사본 4벌 + `JpaStreamScope` 흡수), 범위 없는 멱등성·outbox 리포지토리 메서드 제거(E-6b)
- 주입된 `Clock` 우회 제거(objectstorage·websocket·mongo·web stream), GraphQL 오류가 HTTP request id 사용, notification UUIDv7은 uuid-creator
- 호출처 없는 `WebRequestContext`·argument resolver 삭제
- 결함 수정: `WebStreamRegistry` 상한 경합(ORCH-new-3 — bin 하나만 잠그는 lock 안에서 크기 확인, 원자 카운터로 슬롯 예약)
- 현황표: 소유자 결정 33(persistence-notification·fileserver → persistence-jpa edge), 34(id 포트 domain 전환 보류), 35(X2-P2-6b 나머지 보류)
검증: ./gradlew check architectureCheck verifyDependencyLocks verifyPublicPathSnapshot :app-bootstrap:verifyEnvKeys configContractCheck
:app-bootstrap:integrationTest :sample-portfolio:integrationTest :sample-portfolio:systemTest graphql·websocket systemTest
persistence-jpa jpaPlatformContractTest·postgresql{Idempotency,Outbox*}IntegrationTest --continue 통과(695 task)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
4f4bd1fd34
commit
09e2dd63d6
+2
-12
@@ -1,8 +1,6 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.context;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import dev.caskeleton.shared.digest.Sha256;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/**
|
||||
@@ -66,14 +64,6 @@ public record ActorRef(String value, boolean authenticated) {
|
||||
}
|
||||
|
||||
static String sha256Prefix(String source) {
|
||||
try {
|
||||
byte[] digest =
|
||||
MessageDigest.getInstance("SHA-256").digest(source.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] prefix = new byte[FINGERPRINT_BYTES];
|
||||
System.arraycopy(digest, 0, prefix, 0, FINGERPRINT_BYTES);
|
||||
return HexFormat.of().formatHex(prefix);
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
throw new IllegalStateException("SHA-256 is required for actor fingerprints", ex);
|
||||
}
|
||||
return HexFormat.of().formatHex(Sha256.ofUtf8(source).bytes(), 0, FINGERPRINT_BYTES);
|
||||
}
|
||||
}
|
||||
|
||||
+9
-22
@@ -1,14 +1,10 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.context;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import dev.caskeleton.shared.digest.HmacSha256;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/**
|
||||
* Turns an actor or tenant identity into a value that may be stored outside this process.
|
||||
@@ -41,8 +37,6 @@ public final class GraphQlIdentityFingerprinter {
|
||||
/** Shortest key accepted, matching the block size a truncated key would be padded to anyway. */
|
||||
public static final int MINIMUM_KEY_BYTES = 16;
|
||||
|
||||
private static final String ALGORITHM = "HmacSHA256";
|
||||
|
||||
/**
|
||||
* Domain tags, so the same string used as an actor and as a tenant does not fingerprint the same.
|
||||
*
|
||||
@@ -131,20 +125,13 @@ public final class GraphQlIdentityFingerprinter {
|
||||
}
|
||||
|
||||
private String fingerprint(String domain, String value) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance(ALGORITHM);
|
||||
mac.init(new SecretKeySpec(keys.get(activeKeyId), ALGORITHM));
|
||||
// Length-framed, for the reason the canonical mutation input is: concatenating a domain and a
|
||||
// caller-influenced value lets one of them absorb the other's boundary, and two different
|
||||
// identities then produce one fingerprint.
|
||||
byte[] digest =
|
||||
mac.doFinal(
|
||||
(domain.length() + ":" + domain + "|" + value.length() + ":" + value + "|")
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
return activeKeyId + ":" + HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException | InvalidKeyException unavailable) {
|
||||
throw new IllegalStateException(
|
||||
"HMAC-SHA256 is required for identity fingerprints", unavailable);
|
||||
}
|
||||
// Length-framed, for the reason the canonical mutation input is: concatenating a domain and a
|
||||
// caller-influenced value lets one of them absorb the other's boundary, and two different
|
||||
// identities then produce one fingerprint.
|
||||
byte[] digest =
|
||||
HmacSha256.sign(
|
||||
keys.get(activeKeyId),
|
||||
domain.length() + ":" + domain + "|" + value.length() + ":" + value + "|");
|
||||
return activeKeyId + ":" + HexFormat.of().formatHex(digest);
|
||||
}
|
||||
}
|
||||
|
||||
+10
-12
@@ -1,6 +1,6 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.context;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
import dev.caskeleton.application.tenant.TenantId;
|
||||
|
||||
/**
|
||||
* The tenant a request executes in, together with where that decision came from.
|
||||
@@ -16,14 +16,6 @@ import java.util.regex.Pattern;
|
||||
*/
|
||||
public record TenantContext(String value, TenantSource source) {
|
||||
|
||||
/**
|
||||
* The web transport's tenant grammar ({@code adapter.inbound.web.core.TenantContext}).
|
||||
*
|
||||
* <p>Duplicated on purpose until the shared tenant value type exists (review S5-lead-3, Wave 3):
|
||||
* while the two transports disagreed, the same tenant passed one and was refused by the other.
|
||||
*/
|
||||
private static final Pattern GRAMMAR = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.-]{0,63}");
|
||||
|
||||
/** Trusted inputs a tenant may be derived from. */
|
||||
public enum TenantSource {
|
||||
/** A claim on the verified credential. */
|
||||
@@ -35,14 +27,20 @@ public record TenantContext(String value, TenantSource source) {
|
||||
}
|
||||
|
||||
public TenantContext {
|
||||
if (value == null || !GRAMMAR.matcher(value).matches()) {
|
||||
throw new IllegalArgumentException("tenant identity must match " + GRAMMAR.pattern());
|
||||
}
|
||||
// The grammar is application-core's TenantId, the one the web transport uses too (review
|
||||
// X2-P2-6a): while the two transports disagreed, the same tenant passed one and was refused by
|
||||
// the other.
|
||||
value = new TenantId(value).value();
|
||||
if (source == null) {
|
||||
throw new IllegalArgumentException("tenant source is required");
|
||||
}
|
||||
}
|
||||
|
||||
/** The tenant as the application-core value type. */
|
||||
public TenantId tenantId() {
|
||||
return new TenantId(value);
|
||||
}
|
||||
|
||||
/** Tenant taken from a claim on the verified credential. */
|
||||
public static TenantContext fromAuthenticatedCredential(String value) {
|
||||
return new TenantContext(value, TenantSource.AUTHENTICATED_CREDENTIAL);
|
||||
|
||||
+5
-19
@@ -1,14 +1,12 @@
|
||||
package dev.caskeleton.adapter.inbound.graphql.pagination;
|
||||
|
||||
import dev.caskeleton.shared.digest.HmacSha256;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/**
|
||||
* An HMAC-authenticated cursor codec (design §14).
|
||||
@@ -17,8 +15,8 @@ import javax.crypto.spec.SecretKeySpec;
|
||||
* decode, edit and send back, which turns pagination into an arbitrary "start reading from here"
|
||||
* parameter. Here the envelope is signed, so an edited cursor fails verification.
|
||||
*
|
||||
* <p>Signatures are compared with {@link MessageDigest#isEqual}, whose timing does not depend on
|
||||
* where the first differing byte is — a normal string comparison would leak that position.
|
||||
* <p>Signatures are verified by {@link HmacSha256#verify}, whose timing does not depend on where
|
||||
* the first differing byte is — a normal string comparison would leak that position.
|
||||
*
|
||||
* <p>The codec chooses the signing key. Letting the payload name it meant a caller could pin every
|
||||
* new cursor to a key that was being retired, which is rotation that never completes.
|
||||
@@ -28,7 +26,6 @@ public final class HmacGraphQlCursorCodec implements GraphQlCursorCodec {
|
||||
/** Largest cursor token accepted, before any decoding work is done. */
|
||||
public static final int MAXIMUM_CURSOR_CHARS = 4096;
|
||||
|
||||
private static final String ALGORITHM = "HmacSHA256";
|
||||
private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding();
|
||||
private static final Base64.Decoder DECODER = Base64.getUrlDecoder();
|
||||
|
||||
@@ -50,7 +47,7 @@ public final class HmacGraphQlCursorCodec implements GraphQlCursorCodec {
|
||||
}
|
||||
GraphQlCursorPayload signed = payload.signedWith(keyRing.activeKeyId());
|
||||
String canonical = signed.canonicalForm();
|
||||
byte[] signature = sign(canonical, keyRing.secret(signed.keyId()));
|
||||
byte[] signature = HmacSha256.sign(keyRing.secret(signed.keyId()), canonical);
|
||||
return ENCODER.encodeToString(canonical.getBytes(StandardCharsets.UTF_8))
|
||||
+ "."
|
||||
+ ENCODER.encodeToString(signature);
|
||||
@@ -82,8 +79,7 @@ public final class HmacGraphQlCursorCodec implements GraphQlCursorCodec {
|
||||
}
|
||||
|
||||
GraphQlCursorPayload payload = parse(canonical);
|
||||
byte[] expectedSignature = sign(canonical, keyRing.secret(payload.keyId()));
|
||||
if (!MessageDigest.isEqual(expectedSignature, presentedSignature)) {
|
||||
if (!HmacSha256.verify(keyRing.secret(payload.keyId()), canonical, presentedSignature)) {
|
||||
throw new GraphQlCursorException("cursor signature mismatch");
|
||||
}
|
||||
expected.verify(payload);
|
||||
@@ -168,14 +164,4 @@ public final class HmacGraphQlCursorCodec implements GraphQlCursorCodec {
|
||||
private static String unescape(String value) {
|
||||
return value.replace("\\;", ";").replace("\\=", "=").replace("\\|", "|").replace("\\\\", "\\");
|
||||
}
|
||||
|
||||
private static byte[] sign(String canonical, byte[] secret) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance(ALGORITHM);
|
||||
mac.init(new SecretKeySpec(secret, ALGORITHM));
|
||||
return mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (java.security.GeneralSecurityException ex) {
|
||||
throw new IllegalStateException("HMAC-SHA256 is required for signed cursors", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-1
@@ -13,6 +13,7 @@ import dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestTooLargeExcepti
|
||||
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
|
||||
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthenticatedPrincipal;
|
||||
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthenticationContextFactory;
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import graphql.ExecutionInput;
|
||||
import graphql.ExecutionResult;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -20,6 +21,7 @@ import java.time.Clock;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.graphql.ExecutionGraphQlResponse;
|
||||
import org.springframework.graphql.server.WebGraphQlInterceptor;
|
||||
import org.springframework.graphql.server.WebGraphQlRequest;
|
||||
@@ -154,10 +156,16 @@ public final class GraphQlPlatformWebInterceptor implements WebGraphQlIntercepto
|
||||
/**
|
||||
* A bounded correlation identity for an anonymous request.
|
||||
*
|
||||
* <p>Derived from the execution id Spring already assigned rather than from a client header: a
|
||||
* <p>The HTTP request id when the servlet request-id filter assigned one (review X2-P2-5): it is
|
||||
* already on MDC and in the response's {@code meta}, so a GraphQL error names the same request a
|
||||
* log search finds. Otherwise the execution id Spring assigned — never a client header: a
|
||||
* caller-supplied trace id becomes a log and metric value, and this one has to stay bounded.
|
||||
*/
|
||||
private static String traceId(WebGraphQlRequest request) {
|
||||
String requestId = MDC.get(MdcKeys.REQUEST_ID);
|
||||
if (requestId != null && !requestId.isBlank()) {
|
||||
return requestId;
|
||||
}
|
||||
String id = request.getId();
|
||||
return id == null || id.isBlank() ? "graphql" : id;
|
||||
}
|
||||
|
||||
+2
-10
@@ -3,13 +3,10 @@ package dev.caskeleton.adapter.inbound.graphql.runtime;
|
||||
import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext;
|
||||
import dev.caskeleton.adapter.inbound.graphql.execution.BoundedPreparsedDocumentProvider;
|
||||
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheKey;
|
||||
import dev.caskeleton.shared.digest.Sha256;
|
||||
import graphql.ExecutionInput;
|
||||
import graphql.execution.preparsed.PreparsedDocumentEntry;
|
||||
import graphql.execution.preparsed.PreparsedDocumentProvider;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Function;
|
||||
@@ -107,11 +104,6 @@ public final class GraphQlPreparsedDocumentAdapter implements PreparsedDocumentP
|
||||
* @param value the text to hash
|
||||
*/
|
||||
public static String sha256(String value) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return HexFormat.of().formatHex(digest.digest(value.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (NoSuchAlgorithmException absent) {
|
||||
throw new IllegalStateException("SHA-256 is required by every Java platform", absent);
|
||||
}
|
||||
return Sha256.ofUtf8(value).hex();
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ class GraphQlRequestContextTest {
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage("tenant identity must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}");
|
||||
.hasMessage("tenant identifier must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+31
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlRootAutoConfiguration;
|
||||
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
@@ -12,6 +13,7 @@ import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.springframework.graphql.ResponseError;
|
||||
@@ -126,6 +128,35 @@ class GraphQlPlatformWebInterceptorRequestBoundsTest {
|
||||
.containsExactly(false, "REQUEST_ERROR");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("servlet filter가 MDC에 둔 request_id가 거부 오류의 executionId가 된다")
|
||||
void aRejectionNamesTheHttpRequestIdTheFilterAssigned() {
|
||||
// given
|
||||
MDC.put(MdcKeys.REQUEST_ID, "http-request-7");
|
||||
String[] executionId = new String[1];
|
||||
|
||||
// when
|
||||
try {
|
||||
runner.run(
|
||||
context -> {
|
||||
WebGraphQlResponse response =
|
||||
context
|
||||
.getBean(GraphQlPlatformWebInterceptor.class)
|
||||
.intercept(
|
||||
request("{ _health }", Map.of(), Map.of("unregistered", "x")),
|
||||
next -> Mono.empty())
|
||||
.block();
|
||||
executionId[0] =
|
||||
String.valueOf(response.getErrors().get(0).getExtensions().get("executionId"));
|
||||
});
|
||||
} finally {
|
||||
MDC.remove(MdcKeys.REQUEST_ID);
|
||||
}
|
||||
|
||||
// then
|
||||
assertThat(executionId[0]).isEqualTo("http-request-7");
|
||||
}
|
||||
|
||||
private Outcome intercept(
|
||||
String document, Map<String, Object> variables, Map<String, Object> extensions) {
|
||||
AtomicBoolean executed = new AtomicBoolean();
|
||||
|
||||
Reference in New Issue
Block a user