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();
|
||||
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package dev.caskeleton.adapter.inbound.grpc;
|
||||
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import dev.caskeleton.shared.tracing.TraceParent;
|
||||
import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import org.slf4j.MDC;
|
||||
|
||||
/**
|
||||
* Puts a call's correlation on MDC under the same keys the HTTP path uses (review X2-P2-5).
|
||||
*
|
||||
* <p>Correlation used to stop at the servlet filter: a log line written while a gRPC call ran
|
||||
* carried no {@code request_id}, so it could not be joined to anything. Each call gets its own
|
||||
* request id — minted here, never taken from the caller, for the reason the web filter gives — and
|
||||
* the trace of a {@code traceparent} header that the shared {@link TraceParent} parser accepts.
|
||||
*
|
||||
* <p>gRPC runs a call's callbacks on whichever executor thread is free, so the entries are put
|
||||
* around every callback and the thread's previous MDC is restored afterwards, rather than set once.
|
||||
*/
|
||||
final class GrpcCorrelationInterceptor implements ServerInterceptor {
|
||||
|
||||
static final Metadata.Key<String> TRACEPARENT =
|
||||
Metadata.Key.of("traceparent", Metadata.ASCII_STRING_MARSHALLER);
|
||||
|
||||
@Override
|
||||
public <Q, R> ServerCall.Listener<Q> interceptCall(
|
||||
ServerCall<Q, R> call, Metadata headers, ServerCallHandler<Q, R> next) {
|
||||
Map<String, String> correlation = correlation(headers);
|
||||
ServerCall.Listener<Q> delegate = withMdc(correlation, () -> next.startCall(call, headers));
|
||||
return new SimpleForwardingServerCallListener<>(delegate) {
|
||||
@Override
|
||||
public void onMessage(Q message) {
|
||||
withMdc(correlation, () -> super.onMessage(message));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onHalfClose() {
|
||||
withMdc(correlation, super::onHalfClose);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel() {
|
||||
withMdc(correlation, super::onCancel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
withMdc(correlation, super::onComplete);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReady() {
|
||||
withMdc(correlation, super::onReady);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static Map<String, String> correlation(Metadata headers) {
|
||||
Map<String, String> entries = new HashMap<>();
|
||||
entries.put(MdcKeys.REQUEST_ID, UUID.randomUUID().toString());
|
||||
TraceParent.parse(headers.get(TRACEPARENT))
|
||||
.ifPresent(
|
||||
trace -> {
|
||||
entries.put(MdcKeys.TRACE_ID, trace.traceId());
|
||||
entries.put(MdcKeys.SPAN_ID, trace.spanId());
|
||||
});
|
||||
return Map.copyOf(entries);
|
||||
}
|
||||
|
||||
private static void withMdc(Map<String, String> correlation, Runnable callback) {
|
||||
withMdc(
|
||||
correlation,
|
||||
() -> {
|
||||
callback.run();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private static <T> T withMdc(Map<String, String> correlation, Supplier<T> callback) {
|
||||
Map<String, String> previous = MDC.getCopyOfContextMap();
|
||||
correlation.forEach(MDC::put);
|
||||
try {
|
||||
return callback.get();
|
||||
} finally {
|
||||
if (previous == null) {
|
||||
MDC.clear();
|
||||
} else {
|
||||
MDC.setContextMap(previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -78,10 +78,13 @@ public class GrpcServerRunner implements SmartLifecycle {
|
||||
? null
|
||||
: new GrpcAuthenticationInterceptor(authenticationPolicy, statusMapper);
|
||||
|
||||
// Last, so outermost: the correlation is on MDC before authentication or error mapping logs.
|
||||
var correlationInterceptor = new GrpcCorrelationInterceptor();
|
||||
int registered = 0;
|
||||
for (BindableService service : featureServices) {
|
||||
builder.addService(
|
||||
ServerInterceptors.intercept(service, exceptionInterceptor, authenticationInterceptor));
|
||||
ServerInterceptors.intercept(
|
||||
service, exceptionInterceptor, authenticationInterceptor, correlationInterceptor));
|
||||
registered++;
|
||||
}
|
||||
|
||||
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
package dev.caskeleton.adapter.inbound.grpc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.MethodDescriptor;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.Status;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.MDC;
|
||||
|
||||
class GrpcCorrelationInterceptorTest {
|
||||
|
||||
private static final String TRACEPARENT =
|
||||
"00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01";
|
||||
|
||||
@AfterEach
|
||||
void clearMdc() {
|
||||
MDC.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("callback이 도는 동안 MDC에 request_id와 traceparent의 trace가 있다")
|
||||
void aCallbackRunsWithTheCallsCorrelationOnMdc() {
|
||||
// given
|
||||
Metadata headers = new Metadata();
|
||||
headers.put(GrpcCorrelationInterceptor.TRACEPARENT, TRACEPARENT);
|
||||
Map<String, String> seen = new HashMap<>();
|
||||
ServerCall.Listener<String> listener =
|
||||
new GrpcCorrelationInterceptor()
|
||||
.interceptCall(new NoopCall(), headers, (call, h) -> recordingListener(seen));
|
||||
|
||||
// when
|
||||
listener.onMessage("request");
|
||||
|
||||
// then
|
||||
assertThat(seen)
|
||||
.containsEntry(MdcKeys.TRACE_ID, "0af7651916cd43dd8448eb211c80319c")
|
||||
.containsEntry(MdcKeys.SPAN_ID, "b7ad6b7169203331")
|
||||
.containsKey(MdcKeys.REQUEST_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theThreadsMdcIsRestoredAfterTheCallback() {
|
||||
// given
|
||||
MDC.put("unrelated", "kept");
|
||||
ServerCall.Listener<String> listener =
|
||||
new GrpcCorrelationInterceptor()
|
||||
.interceptCall(
|
||||
new NoopCall(), new Metadata(), (call, h) -> recordingListener(new HashMap<>()));
|
||||
|
||||
// when
|
||||
listener.onHalfClose();
|
||||
|
||||
// then
|
||||
assertThat(MDC.getCopyOfContextMap()).containsExactlyEntriesOf(Map.of("unrelated", "kept"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("공유 parser가 거부하는 traceparent(버전 ff)는 trace로 쓰지 않는다")
|
||||
void aTraceparentTheSharedParserRefusesIsNotAdopted() {
|
||||
// given
|
||||
Metadata headers = new Metadata();
|
||||
headers.put(
|
||||
GrpcCorrelationInterceptor.TRACEPARENT,
|
||||
"ff-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01");
|
||||
Map<String, String> seen = new HashMap<>();
|
||||
ServerCall.Listener<String> listener =
|
||||
new GrpcCorrelationInterceptor()
|
||||
.interceptCall(new NoopCall(), headers, (call, h) -> recordingListener(seen));
|
||||
|
||||
// when
|
||||
listener.onMessage("request");
|
||||
|
||||
// then
|
||||
assertThat(seen).containsOnlyKeys(MdcKeys.REQUEST_ID);
|
||||
}
|
||||
|
||||
private static ServerCall.Listener<String> recordingListener(Map<String, String> seen) {
|
||||
return new ServerCall.Listener<>() {
|
||||
@Override
|
||||
public void onMessage(String message) {
|
||||
seen.putAll(MDC.getCopyOfContextMap());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static final class NoopCall extends ServerCall<String, String> {
|
||||
|
||||
private static final MethodDescriptor.Marshaller<String> UNUSED =
|
||||
new MethodDescriptor.Marshaller<>() {
|
||||
@Override
|
||||
public InputStream stream(String value) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String parse(InputStream stream) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public void request(int numMessages) {}
|
||||
|
||||
@Override
|
||||
public void sendHeaders(Metadata headers) {}
|
||||
|
||||
@Override
|
||||
public void sendMessage(String message) {}
|
||||
|
||||
@Override
|
||||
public void close(Status status, Metadata trailers) {}
|
||||
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MethodDescriptor<String, String> getMethodDescriptor() {
|
||||
return MethodDescriptor.<String, String>newBuilder()
|
||||
.setType(MethodDescriptor.MethodType.UNARY)
|
||||
.setFullMethodName("test.correlation.Feature/Check")
|
||||
.setRequestMarshaller(UNUSED)
|
||||
.setResponseMarshaller(UNUSED)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -2,6 +2,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.mvc;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming;
|
||||
import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder;
|
||||
import java.time.Clock;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
@@ -21,7 +23,9 @@ public class MvcJsonSequenceConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(name = "mvcJsonSequenceWriter")
|
||||
public MvcStreamWriter mvcJsonSequenceWriter(StreamRecordEncoder encoder) {
|
||||
return new MvcStreamWriter(encoder, StreamFraming.JSON_SEQUENCE);
|
||||
public MvcStreamWriter mvcJsonSequenceWriter(
|
||||
StreamRecordEncoder encoder, ObjectProvider<Clock> clocks) {
|
||||
return new MvcStreamWriter(
|
||||
encoder, StreamFraming.JSON_SEQUENCE, clocks.getIfAvailable(Clock::systemUTC));
|
||||
}
|
||||
}
|
||||
|
||||
+9
-7
@@ -8,7 +8,7 @@ import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming
|
||||
import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.time.Instant;
|
||||
import java.time.Clock;
|
||||
import java.util.Iterator;
|
||||
import java.util.Objects;
|
||||
|
||||
@@ -28,10 +28,12 @@ public final class MvcStreamWriter {
|
||||
|
||||
private final StreamRecordEncoder encoder;
|
||||
private final StreamFraming framing;
|
||||
private final Clock clock;
|
||||
|
||||
public MvcStreamWriter(StreamRecordEncoder encoder, StreamFraming framing) {
|
||||
public MvcStreamWriter(StreamRecordEncoder encoder, StreamFraming framing, Clock clock) {
|
||||
this.encoder = Objects.requireNonNull(encoder, "encoder");
|
||||
this.framing = Objects.requireNonNull(framing, "framing");
|
||||
this.clock = Objects.requireNonNull(clock, "clock");
|
||||
}
|
||||
|
||||
/** The media type to set on the response. */
|
||||
@@ -63,11 +65,11 @@ public final class MvcStreamWriter {
|
||||
}
|
||||
}
|
||||
writeRecord(NdjsonRecord.<T>complete(lastSequence), output);
|
||||
evidence.recordTermination(WebStreamTermination.NORMAL_COMPLETE, Instant.now());
|
||||
evidence.recordTermination(WebStreamTermination.NORMAL_COMPLETE, clock.instant());
|
||||
return WebStreamTermination.NORMAL_COMPLETE;
|
||||
} catch (IOException failure) {
|
||||
WebStreamTermination how = MvcDisconnectDetector.classify(failure);
|
||||
evidence.recordTermination(how, Instant.now());
|
||||
evidence.recordTermination(how, clock.instant());
|
||||
return how;
|
||||
} catch (RuntimeException failure) {
|
||||
return terminate(failure, output, evidence, lastSequence);
|
||||
@@ -84,7 +86,7 @@ public final class MvcStreamWriter {
|
||||
// gone would then be counted as a server fault, and the fault rate would track the
|
||||
// tab-closing rate.
|
||||
if (MvcDisconnectDetector.clientWentAway(failure)) {
|
||||
evidence.recordTermination(WebStreamTermination.CLIENT_DISCONNECTED, Instant.now());
|
||||
evidence.recordTermination(WebStreamTermination.CLIENT_DISCONNECTED, clock.instant());
|
||||
return WebStreamTermination.CLIENT_DISCONNECTED;
|
||||
}
|
||||
// Otherwise the source failed after commit. The status is already 200, so the failure goes
|
||||
@@ -97,11 +99,11 @@ public final class MvcStreamWriter {
|
||||
"DEPENDENCY_FAILURE",
|
||||
"the stream ended early because a dependency failed"),
|
||||
output);
|
||||
evidence.recordTermination(WebStreamTermination.TERMINAL_ERROR_RECORD, Instant.now());
|
||||
evidence.recordTermination(WebStreamTermination.TERMINAL_ERROR_RECORD, clock.instant());
|
||||
return WebStreamTermination.TERMINAL_ERROR_RECORD;
|
||||
} catch (IOException | RuntimeException unwritable) {
|
||||
Objects.requireNonNull(unwritable);
|
||||
evidence.recordTermination(WebStreamTermination.ABRUPT_CLOSE, Instant.now());
|
||||
evidence.recordTermination(WebStreamTermination.ABRUPT_CLOSE, clock.instant());
|
||||
return WebStreamTermination.ABRUPT_CLOSE;
|
||||
}
|
||||
}
|
||||
|
||||
+6
-2
@@ -2,6 +2,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.mvc;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming;
|
||||
import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder;
|
||||
import java.time.Clock;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
@@ -21,7 +23,9 @@ public class MvcStreamingExecutorConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(name = "mvcNdjsonWriter")
|
||||
public MvcStreamWriter mvcNdjsonWriter(StreamRecordEncoder encoder) {
|
||||
return new MvcStreamWriter(encoder, StreamFraming.NDJSON);
|
||||
public MvcStreamWriter mvcNdjsonWriter(
|
||||
StreamRecordEncoder encoder, ObjectProvider<Clock> clocks) {
|
||||
return new MvcStreamWriter(
|
||||
encoder, StreamFraming.NDJSON, clocks.getIfAvailable(Clock::systemUTC));
|
||||
}
|
||||
}
|
||||
|
||||
+36
-21
@@ -7,6 +7,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* Every stream currently open on this node.
|
||||
@@ -23,6 +24,10 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
public final class WebStreamRegistry {
|
||||
|
||||
private final Map<StreamId, WebStreamSession> sessions = new ConcurrentHashMap<>();
|
||||
|
||||
/** Admitted streams, including one whose insert is in progress; never above the ceiling. */
|
||||
private final AtomicInteger slots = new AtomicInteger();
|
||||
|
||||
private final int maxConcurrentStreams;
|
||||
|
||||
public WebStreamRegistry(int maxConcurrentStreams) {
|
||||
@@ -39,31 +44,41 @@ public final class WebStreamRegistry {
|
||||
*/
|
||||
public boolean register(WebStreamSession session) {
|
||||
Objects.requireNonNull(session, "session");
|
||||
// Checked and inserted under computeIfAbsent so two concurrent admissions cannot both see room
|
||||
// for the last slot.
|
||||
boolean[] admitted = new boolean[1];
|
||||
sessions.compute(
|
||||
session.streamId(),
|
||||
(id, existing) -> {
|
||||
if (existing != null) {
|
||||
throw new IllegalStateException(
|
||||
"two streams registered as "
|
||||
+ id.value()
|
||||
+ "; one would be unreachable to a drain");
|
||||
}
|
||||
if (sessions.size() >= maxConcurrentStreams) {
|
||||
admitted[0] = false;
|
||||
return null;
|
||||
}
|
||||
admitted[0] = true;
|
||||
return session;
|
||||
});
|
||||
return admitted[0];
|
||||
// The slot is reserved before the insert, on a counter of its own. Checking the map's size
|
||||
// inside compute() was not atomic: compute() locks one bin, and the map's size is updated after
|
||||
// that lock is released, so two arrivals on different bins could both read 999 of 1000 and
|
||||
// both insert (ORCH-new-3: a soak run admitted 1001).
|
||||
if (!reserveSlot()) {
|
||||
return false;
|
||||
}
|
||||
if (sessions.putIfAbsent(session.streamId(), session) != null) {
|
||||
slots.decrementAndGet();
|
||||
throw new IllegalStateException(
|
||||
"two streams registered as "
|
||||
+ session.streamId().value()
|
||||
+ "; one would be unreachable to a drain");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean reserveSlot() {
|
||||
int taken;
|
||||
do {
|
||||
taken = slots.get();
|
||||
if (taken >= maxConcurrentStreams) {
|
||||
return false;
|
||||
}
|
||||
} while (!slots.compareAndSet(taken, taken + 1));
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Forget a stream that has ended. */
|
||||
public boolean deregister(StreamId streamId) {
|
||||
return sessions.remove(streamId) != null;
|
||||
boolean removed = sessions.remove(streamId) != null;
|
||||
if (removed) {
|
||||
slots.decrementAndGet();
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
/** Every open stream. */
|
||||
|
||||
+11
-4
@@ -15,6 +15,7 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
@@ -48,7 +49,8 @@ class MvcStreamingWiringTest {
|
||||
// and fails the only property the client wanted.
|
||||
CountingStream output = new CountingStream();
|
||||
MvcStreamWriter writer =
|
||||
new MvcStreamWriter(encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON);
|
||||
new MvcStreamWriter(
|
||||
encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON, Clock.systemUTC());
|
||||
|
||||
writer.write(
|
||||
List.<NdjsonRecord<String>>of(NdjsonRecord.item(1, "a"), NdjsonRecord.item(2, "b"))
|
||||
@@ -67,7 +69,8 @@ class MvcStreamingWiringTest {
|
||||
CountingStream output = new CountingStream();
|
||||
WebStreamEvidence evidence = new WebStreamEvidence(new StreamId("feed"), NOW);
|
||||
MvcStreamWriter writer =
|
||||
new MvcStreamWriter(encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON);
|
||||
new MvcStreamWriter(
|
||||
encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON, Clock.systemUTC());
|
||||
|
||||
assertThat(writer.write(List.<NdjsonRecord<String>>of().iterator(), output, evidence))
|
||||
.isEqualTo(WebStreamTermination.NORMAL_COMPLETE);
|
||||
@@ -80,7 +83,10 @@ class MvcStreamingWiringTest {
|
||||
CountingStream output = new CountingStream();
|
||||
WebStreamEvidence evidence = new WebStreamEvidence(new StreamId("feed"), NOW);
|
||||
MvcStreamWriter writer =
|
||||
new MvcStreamWriter(encoder(WebStreamPolicy.conventional()), StreamFraming.JSON_SEQUENCE);
|
||||
new MvcStreamWriter(
|
||||
encoder(WebStreamPolicy.conventional()),
|
||||
StreamFraming.JSON_SEQUENCE,
|
||||
Clock.systemUTC());
|
||||
|
||||
WebStreamTermination how =
|
||||
writer.write(failingAfter(NdjsonRecord.item(1, "a")), output, evidence);
|
||||
@@ -98,7 +104,8 @@ class MvcStreamingWiringTest {
|
||||
output.failAt = 1;
|
||||
WebStreamEvidence evidence = new WebStreamEvidence(new StreamId("feed"), NOW);
|
||||
MvcStreamWriter writer =
|
||||
new MvcStreamWriter(encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON);
|
||||
new MvcStreamWriter(
|
||||
encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON, Clock.systemUTC());
|
||||
|
||||
assertThat(
|
||||
writer.write(
|
||||
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package dev.caskeleton.adapter.inbound.web.advanced.stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The admission ceiling under racing arrivals (ORCH-new-3). */
|
||||
@Tag("web-advanced")
|
||||
class WebStreamRegistryAdmissionTest {
|
||||
|
||||
private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z");
|
||||
private static final int CEILING = 64;
|
||||
private static final int RACERS = 96;
|
||||
private static final int ROUNDS = 200;
|
||||
|
||||
@Test
|
||||
@DisplayName("다른 stream id로 동시에 도착한 요청들도 상한을 한 번도 넘지 못한다")
|
||||
void racingArrivalsWithDistinctIdsNeverExceedTheCeiling() throws Exception {
|
||||
// given
|
||||
List<Integer> overAdmittedRounds = new ArrayList<>();
|
||||
|
||||
// when
|
||||
try (ExecutorService executor = Executors.newFixedThreadPool(RACERS)) {
|
||||
for (int round = 0; round < ROUNDS; round++) {
|
||||
WebStreamRegistry registry = new WebStreamRegistry(CEILING);
|
||||
CyclicBarrier start = new CyclicBarrier(RACERS);
|
||||
List<Future<Boolean>> arrivals = new ArrayList<>();
|
||||
for (int racer = 0; racer < RACERS; racer++) {
|
||||
String id = "r" + round + "-" + racer;
|
||||
arrivals.add(
|
||||
executor.submit(
|
||||
() -> {
|
||||
start.await(10, TimeUnit.SECONDS);
|
||||
return registry.register(new Session(id));
|
||||
}));
|
||||
}
|
||||
for (Future<Boolean> arrival : arrivals) {
|
||||
arrival.get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
if (registry.activeStreams() > CEILING) {
|
||||
overAdmittedRounds.add(round);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// then
|
||||
assertThat(overAdmittedRounds).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeregisteredStreamFreesItsSlot() {
|
||||
// given
|
||||
WebStreamRegistry registry = new WebStreamRegistry(1);
|
||||
registry.register(new Session("first"));
|
||||
registry.deregister(new StreamId("first"));
|
||||
|
||||
// when
|
||||
boolean admitted = registry.register(new Session("second"));
|
||||
|
||||
// then
|
||||
assertThat(admitted).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecondRegistrationOfTheSameIdIsRefused() {
|
||||
// given
|
||||
WebStreamRegistry registry = new WebStreamRegistry(2);
|
||||
registry.register(new Session("same"));
|
||||
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> registry.register(new Session("same")));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessage("two streams registered as same; one would be unreachable to a drain");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedDuplicateRegistrationTakesNoSlot() {
|
||||
// given
|
||||
WebStreamRegistry registry = new WebStreamRegistry(2);
|
||||
registry.register(new Session("same"));
|
||||
Throwable duplicate = catchThrowable(() -> registry.register(new Session("same")));
|
||||
assertThat(duplicate).isInstanceOf(IllegalStateException.class);
|
||||
|
||||
// when
|
||||
boolean admitted = registry.register(new Session("other"));
|
||||
|
||||
// then
|
||||
assertThat(admitted).isTrue();
|
||||
}
|
||||
|
||||
private static final class Session implements WebStreamSession {
|
||||
|
||||
private final StreamId id;
|
||||
|
||||
Session(String id) {
|
||||
this.id = new StreamId(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public StreamId streamId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant startedAt() {
|
||||
return NOW;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void requestReconnect() {}
|
||||
|
||||
@Override
|
||||
public void forceClose(WebStreamTermination reason) {}
|
||||
|
||||
@Override
|
||||
public boolean open() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,9 +1,9 @@
|
||||
package dev.caskeleton.adapter.inbound.web.fileserver.security;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal;
|
||||
import dev.caskeleton.adapter.inbound.web.observability.MdcKeys;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileAccessSubject;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import org.slf4j.MDC;
|
||||
|
||||
@@ -384,7 +384,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
|
||||
## observability
|
||||
|
||||
### MdcKeys
|
||||
- snake_case MDC 키 이름은 로그/진단 레지스트리(`mdc-keys.yaml`)를 따른다.
|
||||
- 키 상수는 shared-contract `observability/MdcKeys` 가 소유한다(GraphQL·WebSocket·gRPC 도 같은 이름을
|
||||
쓰도록 web 에서 옮겼다). snake_case MDC 키 이름은 로그/진단 레지스트리(`mdc-keys.yaml`)를 따른다.
|
||||
같은 논리 ID 의 envelope 형태(camelCase)와 HTTP 헤더 형태(kebab-case)는 D19 projection 이며,
|
||||
변환 단일 지점은 `ResponseMetaFactory`.
|
||||
|
||||
|
||||
+18
-1
@@ -1,16 +1,33 @@
|
||||
package dev.caskeleton.adapter.inbound.web.auth;
|
||||
|
||||
import dev.caskeleton.application.tenant.TenantId;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Principal exposed to controllers via {@code @AuthenticationPrincipal}. Carries the IdP-side
|
||||
* identifier ({@code idpUserId}, JWT {@code sub} claim) plus any claims a controller is likely to
|
||||
* want without reaching into the raw Jwt.
|
||||
*
|
||||
* <p>{@code tenant} is the verified token's tenant claim, when it has one — the only place a web
|
||||
* request's tenant comes from. A request parameter or header never becomes one.
|
||||
*
|
||||
* @param idpUserId the verified subject
|
||||
* @param email the email claim, when present
|
||||
* @param roles the granted roles
|
||||
* @param tenant the verified tenant, empty for a token without a tenant claim
|
||||
*/
|
||||
public record AuthenticatedPrincipal(String idpUserId, String email, Set<String> roles) {
|
||||
public record AuthenticatedPrincipal(
|
||||
String idpUserId, String email, Set<String> roles, Optional<TenantId> tenant) {
|
||||
|
||||
public AuthenticatedPrincipal {
|
||||
roles = roles == null ? Set.of() : Set.copyOf(roles);
|
||||
tenant = tenant == null ? Optional.empty() : tenant;
|
||||
}
|
||||
|
||||
/** A principal whose token carries no tenant. */
|
||||
public AuthenticatedPrincipal(String idpUserId, String email, Set<String> roles) {
|
||||
this(idpUserId, email, roles, Optional.empty());
|
||||
}
|
||||
|
||||
public boolean hasRole(String role) {
|
||||
|
||||
+30
-1
@@ -1,11 +1,13 @@
|
||||
package dev.caskeleton.adapter.inbound.web.auth;
|
||||
|
||||
import dev.caskeleton.application.tenant.TenantId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
@@ -13,6 +15,7 @@ import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@@ -26,11 +29,20 @@ import org.springframework.stereotype.Component;
|
||||
public class JwtToAuthenticatedPrincipalConverter
|
||||
implements Converter<Jwt, AbstractAuthenticationToken> {
|
||||
|
||||
/**
|
||||
* The claim a token names its tenant in.
|
||||
*
|
||||
* <p>Snake case like the rest of this platform's field names ({@code tenant_id} is also the MDC
|
||||
* and baggage key). An IdP that puts the tenant elsewhere maps it to this claim.
|
||||
*/
|
||||
public static final String TENANT_CLAIM = "tenant_id";
|
||||
|
||||
@Override
|
||||
public AbstractAuthenticationToken convert(Jwt jwt) {
|
||||
Set<String> roles = extractRoles(jwt);
|
||||
String email = jwt.getClaimAsString("email");
|
||||
AuthenticatedPrincipal principal = new AuthenticatedPrincipal(jwt.getSubject(), email, roles);
|
||||
AuthenticatedPrincipal principal =
|
||||
new AuthenticatedPrincipal(jwt.getSubject(), email, roles, tenant(jwt));
|
||||
Collection<GrantedAuthority> authorities =
|
||||
roles.stream()
|
||||
.map(r -> new SimpleGrantedAuthority("ROLE_" + r.toUpperCase(Locale.ROOT)))
|
||||
@@ -38,6 +50,23 @@ public class JwtToAuthenticatedPrincipalConverter
|
||||
return new AuthenticatedJwtToken(jwt, authorities, principal);
|
||||
}
|
||||
|
||||
/**
|
||||
* The token's tenant, refusing the token when the claim is present but malformed.
|
||||
*
|
||||
* <p>A malformed tenant is not read as "no tenant": an operation submitted without a tenant is
|
||||
* visible to every call made without one, so that reading would widen what the caller sees.
|
||||
*/
|
||||
@SuppressWarnings("UnusedException") // see the catch block
|
||||
private static Optional<TenantId> tenant(Jwt jwt) {
|
||||
try {
|
||||
return TenantId.optional(jwt.getClaimAsString(TENANT_CLAIM));
|
||||
} catch (IllegalArgumentException malformed) {
|
||||
// No cause: Spring's (description, cause) constructor replaces the description with the
|
||||
// cause's message, and a 401 description names the claim, not our grammar.
|
||||
throw new InvalidBearerTokenException("the token's tenant claim is malformed");
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> extractRoles(Jwt jwt) {
|
||||
Set<String> roles = new HashSet<>();
|
||||
|
||||
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
package dev.caskeleton.adapter.inbound.web.core;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* How the request looked from outside the trust boundary, normalised.
|
||||
*
|
||||
* <p>The platform builds absolute URLs — {@code Location} headers, pagination links, sunset links —
|
||||
* and it must build them the way a client sees the deployment, not the way the application server
|
||||
* sees itself. Behind a proxy those differ: the server believes it is {@code http://10.0.0.4:8080}
|
||||
* while the client asked {@code https://api.example.com/gateway}.
|
||||
*
|
||||
* <p>Only scheme, host, port and prefix are kept, and each is normalised on the way in. Everything
|
||||
* else a forwarded header could carry — the original path, the query, a client-chosen prefix — is
|
||||
* discarded, because this record is consumed to build URLs and anything retained here would become
|
||||
* a way for a caller to choose where a {@code Location} header points.
|
||||
*
|
||||
* @param scheme the external scheme, lower case
|
||||
* @param host the external host, lower case
|
||||
* @param port the external port
|
||||
* @param prefix the external path prefix, empty or beginning with a slash and never ending in one
|
||||
*/
|
||||
public record ExternalRequestContext(String scheme, String host, int port, String prefix) {
|
||||
|
||||
public ExternalRequestContext {
|
||||
Objects.requireNonNull(scheme, "scheme");
|
||||
Objects.requireNonNull(host, "host");
|
||||
Objects.requireNonNull(prefix, "prefix");
|
||||
scheme = scheme.toLowerCase(Locale.ROOT);
|
||||
host = host.toLowerCase(Locale.ROOT);
|
||||
if (!scheme.equals("http") && !scheme.equals("https")) {
|
||||
throw new IllegalArgumentException("external scheme must be http or https, was: " + scheme);
|
||||
}
|
||||
if (host.isBlank()) {
|
||||
throw new IllegalArgumentException("external host is required");
|
||||
}
|
||||
if (port < 1 || port > 65535) {
|
||||
throw new IllegalArgumentException("external port out of range: " + port);
|
||||
}
|
||||
if (!prefix.isEmpty()) {
|
||||
if (!prefix.startsWith("/")) {
|
||||
throw new IllegalArgumentException("external prefix must begin with a slash: " + prefix);
|
||||
}
|
||||
if (prefix.endsWith("/")) {
|
||||
throw new IllegalArgumentException("external prefix must not end with a slash: " + prefix);
|
||||
}
|
||||
if (prefix.contains("..")) {
|
||||
throw new IllegalArgumentException("external prefix must not traverse: " + prefix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The origin a client would type, with the default port for the scheme left implicit. */
|
||||
public String origin() {
|
||||
boolean defaultPort =
|
||||
(scheme.equals("https") && port == 443) || (scheme.equals("http") && port == 80);
|
||||
return defaultPort ? scheme + "://" + host : scheme + "://" + host + ":" + port;
|
||||
}
|
||||
|
||||
/** The absolute base every generated URL is built from. */
|
||||
public String baseUrl() {
|
||||
return origin() + prefix;
|
||||
}
|
||||
}
|
||||
+11
-13
@@ -1,8 +1,8 @@
|
||||
package dev.caskeleton.adapter.inbound.web.core;
|
||||
|
||||
import dev.caskeleton.application.tenant.TenantId;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Which tenant the request is scoped to, as established by the security layer.
|
||||
@@ -12,39 +12,37 @@ import java.util.regex.Pattern;
|
||||
* caller. {@link #resolved} is the only way to name one, and the platform calls it from the
|
||||
* security bridge alone.
|
||||
*
|
||||
* @param tenantId the resolved tenant identifier, empty when the operation is not tenant scoped
|
||||
* <p>The identifier is application-core's {@link TenantId}, the grammar GraphQL shares: a tenant
|
||||
* one transport accepts, the other accepts too.
|
||||
*
|
||||
* @param tenant the resolved tenant, empty when the operation is not tenant scoped
|
||||
*/
|
||||
public record TenantContext(String tenantId) {
|
||||
|
||||
/** Tenant identifiers are opaque, short and safe to place in a log field. */
|
||||
private static final Pattern GRAMMAR = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.-]{0,63}");
|
||||
public record TenantContext(Optional<TenantId> tenant) {
|
||||
|
||||
public TenantContext {
|
||||
Objects.requireNonNull(tenantId, "tenantId");
|
||||
if (!tenantId.isEmpty() && !GRAMMAR.matcher(tenantId).matches()) {
|
||||
throw new IllegalArgumentException("invalid tenant identifier: " + tenantId);
|
||||
}
|
||||
Objects.requireNonNull(tenant, "tenant");
|
||||
}
|
||||
|
||||
/** The context for an operation that is not scoped to a tenant. */
|
||||
public static TenantContext none() {
|
||||
return new TenantContext("");
|
||||
return new TenantContext(Optional.empty());
|
||||
}
|
||||
|
||||
/**
|
||||
* A tenant the security layer resolved.
|
||||
*
|
||||
* @param tenantId the resolved tenant identifier
|
||||
* @throws IllegalArgumentException when it is blank or breaks the {@link TenantId} grammar
|
||||
*/
|
||||
public static TenantContext resolved(String tenantId) {
|
||||
if (tenantId == null || tenantId.isBlank()) {
|
||||
throw new IllegalArgumentException("a resolved tenant must carry an identifier");
|
||||
}
|
||||
return new TenantContext(tenantId);
|
||||
return new TenantContext(Optional.of(new TenantId(tenantId)));
|
||||
}
|
||||
|
||||
/** The tenant, when the operation is scoped to one. */
|
||||
public Optional<String> value() {
|
||||
return tenantId.isEmpty() ? Optional.empty() : Optional.of(tenantId);
|
||||
return tenant.map(TenantId::value);
|
||||
}
|
||||
}
|
||||
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
package dev.caskeleton.adapter.inbound.web.core;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Everything the platform knows about one request, fixed at admission.
|
||||
*
|
||||
* <p>Immutable on purpose. This value is read by the filter chain, the controller, the idempotency
|
||||
* gate, the evidence recorder and the access log, and a mutable context read by that many stages is
|
||||
* a context whose value at the point of a failure nobody can reconstruct. Anything that needs to
|
||||
* change produces a new context rather than editing this one.
|
||||
*
|
||||
* <p>The deadline is absolute rather than a duration. A budget expressed as "three seconds"
|
||||
* restarts at every hop that reads it, so a request with a three second budget can spend nine; an
|
||||
* instant cannot be accidentally renewed.
|
||||
*
|
||||
* @param requestId this exchange's identity
|
||||
* @param traceId the distributed trace this exchange belongs to
|
||||
* @param operationName the low-cardinality operation identity
|
||||
* @param apiVersion the major API version addressed
|
||||
* @param actor who is calling, as the security layer established it
|
||||
* @param tenant which tenant the call is scoped to
|
||||
* @param locale the negotiated locale
|
||||
* @param receivedAt when the platform admitted the request
|
||||
* @param deadline when the request's budget expires
|
||||
* @param externalRequest how the request looked from outside the trust boundary
|
||||
*/
|
||||
public record WebRequestContext(
|
||||
WebRequestId requestId,
|
||||
WebTraceId traceId,
|
||||
WebOperationName operationName,
|
||||
ApiMajorVersion apiVersion,
|
||||
ActorContext actor,
|
||||
TenantContext tenant,
|
||||
Locale locale,
|
||||
Instant receivedAt,
|
||||
Instant deadline,
|
||||
ExternalRequestContext externalRequest) {
|
||||
|
||||
public WebRequestContext {
|
||||
Objects.requireNonNull(requestId, "requestId");
|
||||
Objects.requireNonNull(traceId, "traceId");
|
||||
Objects.requireNonNull(operationName, "operationName");
|
||||
Objects.requireNonNull(apiVersion, "apiVersion");
|
||||
Objects.requireNonNull(actor, "actor");
|
||||
Objects.requireNonNull(tenant, "tenant");
|
||||
Objects.requireNonNull(locale, "locale");
|
||||
Objects.requireNonNull(receivedAt, "receivedAt");
|
||||
Objects.requireNonNull(deadline, "deadline");
|
||||
Objects.requireNonNull(externalRequest, "externalRequest");
|
||||
if (deadline.isBefore(receivedAt)) {
|
||||
throw new IllegalArgumentException(
|
||||
"deadline precedes receive time; a request admitted already out of budget would be "
|
||||
+ "cancelled before any stage could report why");
|
||||
}
|
||||
}
|
||||
|
||||
/** How much of the budget is left at an instant, never negative. */
|
||||
public Duration remainingBudget(Instant now) {
|
||||
Objects.requireNonNull(now, "now");
|
||||
Duration remaining = Duration.between(now, deadline);
|
||||
return remaining.isNegative() ? Duration.ZERO : remaining;
|
||||
}
|
||||
|
||||
/** Whether the budget has run out at an instant. */
|
||||
public boolean expired(Instant now) {
|
||||
Objects.requireNonNull(now, "now");
|
||||
return !now.isBefore(deadline);
|
||||
}
|
||||
|
||||
/** The whole budget this request was admitted with. */
|
||||
public Duration budget() {
|
||||
return Duration.between(receivedAt, deadline);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,8 +1,8 @@
|
||||
package dev.caskeleton.adapter.inbound.web.filter;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal;
|
||||
import dev.caskeleton.adapter.inbound.web.observability.MdcKeys;
|
||||
import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort;
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
+3
-20
@@ -1,11 +1,9 @@
|
||||
package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
|
||||
import dev.caskeleton.adapter.inbound.web.mvc.context.WebMvcRequestContextArgumentResolver;
|
||||
import dev.caskeleton.adapter.inbound.web.mvc.filter.JsonBodyLimitFilter;
|
||||
import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter;
|
||||
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
|
||||
import java.util.List;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
@@ -14,8 +12,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplicat
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import tools.jackson.core.StreamReadFeature;
|
||||
|
||||
/**
|
||||
@@ -25,10 +21,9 @@ import tools.jackson.core.StreamReadFeature;
|
||||
* corrected onto: the condition lives here and everything else is imported, so "off" means no beans
|
||||
* rather than beans that happen not to be called.
|
||||
*
|
||||
* <p>The {@code Envelope} error handler, the request-id filter, the request-body boundary (JSON
|
||||
* size ceiling and duplicate-key refusal), and the argument resolver that lets a controller declare
|
||||
* {@code WebRequestContext}. HTTP errors are the {@code Envelope} this handler writes; {@code
|
||||
* spring.mvc.problemdetails.enabled} stays false.
|
||||
* <p>The {@code Envelope} error handler, the request-id filter and the request-body boundary (JSON
|
||||
* size ceiling and duplicate-key refusal). HTTP errors are the {@code Envelope} this handler
|
||||
* writes; {@code spring.mvc.problemdetails.enabled} stays false.
|
||||
*
|
||||
* <p>Every bean is {@link ConditionalOnMissingBean}: the platform supplies the one that would
|
||||
* otherwise be missing rather than the one that must be used.
|
||||
@@ -83,16 +78,4 @@ public class WebMvcPlatformAutoConfiguration {
|
||||
public JsonMapperBuilderCustomizer strictDuplicateJsonKeys() {
|
||||
return builder -> builder.enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION);
|
||||
}
|
||||
|
||||
/** Lets a controller declare the request context instead of the servlet request. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(name = "webMvcRequestContextConfigurer")
|
||||
public WebMvcConfigurer webMvcRequestContextConfigurer() {
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
|
||||
resolvers.add(new WebMvcRequestContextArgumentResolver());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
package dev.caskeleton.adapter.inbound.web.mvc.context;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.core.WebRequestContext;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.web.bind.support.WebDataBinderFactory;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
|
||||
/**
|
||||
* Lets a controller declare {@link WebRequestContext} as a parameter.
|
||||
*
|
||||
* <p>This is what keeps {@code HttpServletRequest} out of controller signatures. A controller that
|
||||
* takes the servlet request has to be given one by every test, cannot be called by another
|
||||
* transport, and — the part that matters most here — can read any header it likes, which routes
|
||||
* around the normalisation the platform did on the way in.
|
||||
*
|
||||
* <p>Resolution fails rather than returning null when no context is bound. A null actor reaching a
|
||||
* use case is an authorization decision made by accident.
|
||||
*/
|
||||
public final class WebMvcRequestContextArgumentResolver implements HandlerMethodArgumentResolver {
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(MethodParameter parameter) {
|
||||
return WebRequestContext.class.equals(parameter.getParameterType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolveArgument(
|
||||
MethodParameter parameter,
|
||||
ModelAndViewContainer mavContainer,
|
||||
NativeWebRequest webRequest,
|
||||
WebDataBinderFactory binderFactory) {
|
||||
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
|
||||
if (request == null) {
|
||||
throw new IllegalStateException(
|
||||
"no servlet request available to resolve the web request context from");
|
||||
}
|
||||
return WebMvcRequestContextHolder.require(request);
|
||||
}
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
package dev.caskeleton.adapter.inbound.web.mvc.context;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.core.WebRequestContext;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Where the request context lives for the duration of one servlet request.
|
||||
*
|
||||
* <p>A request attribute rather than a {@code ThreadLocal}. The platform serves async dispatches
|
||||
* and virtual threads, and both break the assumption a thread-local encodes: the thread that
|
||||
* completes a response is not always the thread that started it, so a thread-local either loses the
|
||||
* context or — worse, and this is the failure that is hard to see — hands the next request the
|
||||
* previous one's actor.
|
||||
*
|
||||
* <p>The attribute travels with the request object, which is the thing that actually spans the
|
||||
* dispatches.
|
||||
*/
|
||||
public final class WebMvcRequestContextHolder {
|
||||
|
||||
/** Where the context lives. */
|
||||
public static final String CONTEXT_ATTRIBUTE =
|
||||
WebMvcRequestContextHolder.class.getName() + ".context";
|
||||
|
||||
private WebMvcRequestContextHolder() {}
|
||||
|
||||
/**
|
||||
* Stores the context for this request.
|
||||
*
|
||||
* @throws IllegalStateException when a context is already present, because a second one would
|
||||
* mean two stages disagree about who the caller is
|
||||
*/
|
||||
public static void store(HttpServletRequest request, WebRequestContext context) {
|
||||
Objects.requireNonNull(request, "request");
|
||||
Objects.requireNonNull(context, "context");
|
||||
if (request.getAttribute(CONTEXT_ATTRIBUTE) != null) {
|
||||
throw new IllegalStateException(
|
||||
"a request context is already bound to this request; replacing it would let two stages"
|
||||
+ " disagree about the actor, the tenant and the deadline");
|
||||
}
|
||||
request.setAttribute(CONTEXT_ATTRIBUTE, context);
|
||||
}
|
||||
|
||||
/** The context for this request, when one has been established. */
|
||||
public static Optional<WebRequestContext> find(HttpServletRequest request) {
|
||||
Objects.requireNonNull(request, "request");
|
||||
Object value = request.getAttribute(CONTEXT_ATTRIBUTE);
|
||||
return value instanceof WebRequestContext context ? Optional.of(context) : Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The context for this request.
|
||||
*
|
||||
* @throws IllegalStateException when none was established, rather than fabricating an anonymous
|
||||
* one that would make an unauthenticated request look like a deliberate decision
|
||||
*/
|
||||
public static WebRequestContext require(HttpServletRequest request) {
|
||||
return find(request)
|
||||
.orElseThrow(
|
||||
() ->
|
||||
new IllegalStateException(
|
||||
"no web request context on this request; a fabricated one here would make an"
|
||||
+ " unauthenticated call look like an anonymous actor somebody chose"));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -3,7 +3,7 @@ package dev.caskeleton.adapter.inbound.web.mvc.filter;
|
||||
import dev.caskeleton.adapter.inbound.web.core.WebRequestId;
|
||||
import dev.caskeleton.adapter.inbound.web.core.WebTraceId;
|
||||
import dev.caskeleton.adapter.inbound.web.observability.HeaderSanitizer;
|
||||
import dev.caskeleton.adapter.inbound.web.observability.MdcKeys;
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import dev.caskeleton.shared.tracing.TraceParent;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
|
||||
+1
@@ -1,6 +1,7 @@
|
||||
package dev.caskeleton.adapter.inbound.web.observability;
|
||||
|
||||
import dev.caskeleton.application.observability.CorrelationIdPort;
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package dev.caskeleton.adapter.inbound.web.observability;
|
||||
|
||||
/** snake_case MDC key names. See README for the design rationale. */
|
||||
public final class MdcKeys {
|
||||
|
||||
public static final String REQUEST_ID = "request_id";
|
||||
public static final String TRACE_ID = "trace_id";
|
||||
public static final String SPAN_ID = "span_id";
|
||||
public static final String CORRELATION_ID = "correlation_id";
|
||||
public static final String USER_PRINCIPAL = "user_principal";
|
||||
|
||||
private MdcKeys() {}
|
||||
}
|
||||
+1
@@ -1,5 +1,6 @@
|
||||
package dev.caskeleton.adapter.inbound.web.observability;
|
||||
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import dev.caskeleton.shared.response.ResponseMeta;
|
||||
import org.slf4j.MDC;
|
||||
|
||||
|
||||
+12
-5
@@ -12,6 +12,7 @@ import dev.caskeleton.application.operation.GetDurableOperationUseCase;
|
||||
import dev.caskeleton.application.operation.OperationAcceptance;
|
||||
import dev.caskeleton.application.operation.OperationCommand;
|
||||
import dev.caskeleton.application.operation.SubmitDurableOperationUseCase;
|
||||
import dev.caskeleton.application.tenant.TenantId;
|
||||
import dev.caskeleton.shared.response.Envelope;
|
||||
import jakarta.validation.Valid;
|
||||
import java.net.URI;
|
||||
@@ -39,8 +40,9 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
* operation exactly as for one that does not exist — so both are the same 404 here. Registered by
|
||||
* the composition that assembles those use cases, which exists only when a store is selected.
|
||||
*
|
||||
* <p>No tenant is passed: nothing on this transport resolves one yet, and an operation submitted
|
||||
* without a tenant is visible only to calls made without one.
|
||||
* <p>The tenant is the verified token's ({@link AuthenticatedPrincipal#tenant()}, claim {@code
|
||||
* tenant_id}); a token without one submits and reads operations without a tenant, which are visible
|
||||
* only to calls made without one.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/operations")
|
||||
@@ -84,7 +86,7 @@ public class DurableOperationController {
|
||||
new DurableOperationId(UUID.randomUUID().toString()),
|
||||
request.operationName(),
|
||||
principalId(principal),
|
||||
null,
|
||||
tenantOf(principal),
|
||||
RequestFingerprint.ofSha256(payload.getBytes(StandardCharsets.UTF_8)),
|
||||
payload,
|
||||
OperationCommand.DEFAULT_TIME_TO_LIVE));
|
||||
@@ -106,7 +108,7 @@ public class DurableOperationController {
|
||||
@PathVariable String operationId, @AuthenticationPrincipal AuthenticatedPrincipal principal) {
|
||||
return get.handle(
|
||||
new GetDurableOperationQuery(
|
||||
new DurableOperationId(operationId), principalId(principal), null))
|
||||
new DurableOperationId(operationId), principalId(principal), tenantOf(principal)))
|
||||
.<ResponseEntity<Envelope<?>>>map(
|
||||
operation ->
|
||||
ResponseEntity.ok(
|
||||
@@ -127,7 +129,7 @@ public class DurableOperationController {
|
||||
@PathVariable String operationId, @AuthenticationPrincipal AuthenticatedPrincipal principal) {
|
||||
DurableOperationId id = new DurableOperationId(operationId);
|
||||
return cancel
|
||||
.handle(new CancelDurableOperationCommand(id, principalId(principal), null))
|
||||
.handle(new CancelDurableOperationCommand(id, principalId(principal), tenantOf(principal)))
|
||||
.<ResponseEntity<Envelope<?>>>map(
|
||||
canceled ->
|
||||
ResponseEntity.accepted()
|
||||
@@ -148,6 +150,11 @@ public class DurableOperationController {
|
||||
return principal.idpUserId();
|
||||
}
|
||||
|
||||
// The operation use cases take the tenant as a plain string; null means "not tenant scoped".
|
||||
private static String tenantOf(AuthenticatedPrincipal principal) {
|
||||
return principal == null ? null : principal.tenant().map(TenantId::value).orElse(null);
|
||||
}
|
||||
|
||||
private static ResponseEntity<Envelope<?>> notFound() {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ErrorResponseFactory.body(OperationErrorCode.OPERATION_NOT_FOUND, null));
|
||||
|
||||
+46
@@ -1,12 +1,16 @@
|
||||
package dev.caskeleton.adapter.inbound.web.auth;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.application.tenant.TenantId;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
|
||||
|
||||
class JwtToAuthenticatedPrincipalConverterTest {
|
||||
|
||||
@@ -31,4 +35,46 @@ class JwtToAuthenticatedPrincipalConverterTest {
|
||||
Locale.setDefault(originalDefault);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTokensTenantClaimBecomesThePrincipalsTenant() {
|
||||
// given
|
||||
Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "acme").build();
|
||||
|
||||
// when
|
||||
var authentication = new JwtToAuthenticatedPrincipalConverter().convert(jwt);
|
||||
|
||||
// then
|
||||
assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).tenant())
|
||||
.contains(new TenantId("acme"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTokenWithoutATenantClaimHasNoTenant() {
|
||||
// when
|
||||
var authentication = new JwtToAuthenticatedPrincipalConverter().convert(token().build());
|
||||
|
||||
// then
|
||||
assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).tenant()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("형식이 틀린 tenant claim은 '없음'이 아니라 잘못된 token으로 거부한다(401)")
|
||||
void aTokenWithAMalformedTenantClaimIsRefused() {
|
||||
// given
|
||||
Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "ac me").build();
|
||||
|
||||
// when
|
||||
Throwable thrown =
|
||||
catchThrowable(() -> new JwtToAuthenticatedPrincipalConverter().convert(jwt));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(InvalidBearerTokenException.class)
|
||||
.hasMessage("the token's tenant claim is malformed");
|
||||
}
|
||||
|
||||
private static Jwt.Builder token() {
|
||||
return Jwt.withTokenValue("token").header("alg", "none").subject("user-1");
|
||||
}
|
||||
}
|
||||
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
package dev.caskeleton.adapter.inbound.web.core;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The request context fixes the facts a whole request path reads, and refuses impossible ones. */
|
||||
class WebRequestContextTest {
|
||||
|
||||
private static final Instant NOW = Instant.parse("2026-08-13T00:00:00Z");
|
||||
|
||||
@Test
|
||||
@DisplayName("a deadline before the receive time is rejected")
|
||||
void aDeadlineBeforeTheReceiveTimeIsRejected() {
|
||||
assertThatThrownBy(() -> context(NOW, NOW.minusSeconds(1)))
|
||||
.as("a request admitted already out of budget is cancelled before any stage reports why")
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("deadline precedes receive time");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the remaining budget is measured against the absolute deadline")
|
||||
void theRemainingBudgetIsMeasuredAgainstTheAbsoluteDeadline() {
|
||||
WebRequestContext context = context(NOW, NOW.plusSeconds(3));
|
||||
|
||||
assertThat(context.budget()).isEqualTo(Duration.ofSeconds(3));
|
||||
assertThat(context.remainingBudget(NOW.plusSeconds(1))).isEqualTo(Duration.ofSeconds(2));
|
||||
assertThat(context.remainingBudget(NOW.plusSeconds(9)))
|
||||
.as("a spent budget is zero, never negative, so a caller cannot read it as more time")
|
||||
.isEqualTo(Duration.ZERO);
|
||||
assertThat(context.expired(NOW.plusSeconds(3))).isTrue();
|
||||
assertThat(context.expired(NOW.plusSeconds(2))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("an anonymous actor cannot carry a subject")
|
||||
void anAnonymousActorCannotCarryASubject() {
|
||||
assertThat(ActorContext.anonymous().authenticated()).isFalse();
|
||||
assertThat(ActorContext.authenticated("user-1", Set.of("ROLE_USER")).subject())
|
||||
.isEqualTo("user-1");
|
||||
assertThatThrownBy(() -> new ActorContext("user-1", false, Set.of()))
|
||||
.as("an unverified identifier that reaches an audit record looking verified is the risk")
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> ActorContext.authenticated(" ", Set.of()))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a tenant is resolved or absent, never a caller-supplied blank")
|
||||
void aTenantIsResolvedOrAbsent() {
|
||||
assertThat(TenantContext.none().value()).isEmpty();
|
||||
assertThat(TenantContext.resolved("acme").value()).contains("acme");
|
||||
assertThatThrownBy(() -> TenantContext.resolved(" "))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> new TenantContext("../other"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the external request keeps only a normalised origin and prefix")
|
||||
void theExternalRequestKeepsOnlyANormalisedOriginAndPrefix() {
|
||||
ExternalRequestContext external =
|
||||
new ExternalRequestContext("HTTPS", "API.Example.COM", 443, "/gateway");
|
||||
|
||||
assertThat(external.scheme()).isEqualTo("https");
|
||||
assertThat(external.host()).isEqualTo("api.example.com");
|
||||
assertThat(external.origin())
|
||||
.as("the default port is left implicit so generated URLs match what a client typed")
|
||||
.isEqualTo("https://api.example.com");
|
||||
assertThat(external.baseUrl()).isEqualTo("https://api.example.com/gateway");
|
||||
assertThat(new ExternalRequestContext("http", "localhost", 8080, "").baseUrl())
|
||||
.isEqualTo("http://localhost:8080");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("an external prefix that could redirect a generated URL is rejected")
|
||||
void anExternalPrefixThatCouldRedirectAGeneratedUrlIsRejected() {
|
||||
assertThatThrownBy(() -> new ExternalRequestContext("https", "api.example.com", 443, "gateway"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(
|
||||
() -> new ExternalRequestContext("https", "api.example.com", 443, "/gateway/"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(
|
||||
() -> new ExternalRequestContext("https", "api.example.com", 443, "/../evil"))
|
||||
.as("a prefix is used to build Location headers, so traversal in it chooses a target")
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> new ExternalRequestContext("ftp", "api.example.com", 21, ""))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> new ExternalRequestContext("https", "api.example.com", 0, ""))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
private static WebRequestContext context(Instant receivedAt, Instant deadline) {
|
||||
return new WebRequestContext(
|
||||
new WebRequestId("req-1"),
|
||||
new WebTraceId("0af7651916cd43dd8448eb211c80319c"),
|
||||
new WebOperationName("orders.list"),
|
||||
new ApiMajorVersion(1),
|
||||
ActorContext.anonymous(),
|
||||
TenantContext.none(),
|
||||
Locale.ENGLISH,
|
||||
receivedAt,
|
||||
deadline,
|
||||
new ExternalRequestContext("https", "api.example.com", 443, ""));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -6,7 +6,7 @@ import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal;
|
||||
import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter;
|
||||
import dev.caskeleton.adapter.inbound.web.observability.MdcKeys;
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ class WebMvcPlatformAutoConfigurationTest {
|
||||
.hasNotFailed()
|
||||
.hasSingleBean(GlobalExceptionHandler.class)
|
||||
.hasSingleBean(WebMvcRequestIdFilter.class)
|
||||
.hasBean("webMvcRequestContextConfigurer"));
|
||||
.doesNotHaveBean("webMvcRequestContextConfigurer"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+25
-1
@@ -2,7 +2,7 @@ package dev.caskeleton.adapter.inbound.web.mvc.filter;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.observability.MdcKeys;
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import dev.caskeleton.shared.tracing.TraceParent;
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import java.util.HashMap;
|
||||
@@ -10,6 +10,8 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
@@ -74,6 +76,28 @@ class WebMvcRequestIdFilterTest {
|
||||
.isPresent();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(
|
||||
strings = {
|
||||
"ff-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",
|
||||
"00-00000000000000000000000000000000-b7ad6b7169203331-01",
|
||||
"00-0af7651916cd43dd8448eb211c80319c-0000000000000000-01"
|
||||
})
|
||||
@DisplayName("공유 TraceParent가 거부하는 traceparent(버전 ff, 0 trace/span id)는 채택하지 않는다")
|
||||
void aTraceparentTheSharedParserRefusesIsReplaced(String traceparent) throws Exception {
|
||||
// given
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader(WebMvcRequestIdFilter.TRACEPARENT_HEADER, traceparent);
|
||||
|
||||
// when
|
||||
new WebMvcRequestIdFilter()
|
||||
.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
|
||||
|
||||
// then
|
||||
assertThat(WebMvcRequestIdFilter.traceId(request).orElseThrow().value())
|
||||
.isNotEqualTo(traceparent.substring(3, 35));
|
||||
}
|
||||
|
||||
@Test
|
||||
void assignedIdentifiersAreOnMdcDuringTheChainAndMatchWhatTheResponseCarries() throws Exception {
|
||||
// given
|
||||
|
||||
+1
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.web.observability;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.MDC;
|
||||
|
||||
+1
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.web.observability;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import dev.caskeleton.shared.response.ResponseMeta;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.MDC;
|
||||
|
||||
+47
@@ -19,15 +19,18 @@ import dev.caskeleton.application.operation.GetDurableOperationUseCase;
|
||||
import dev.caskeleton.application.operation.SubmitDurableOperationUseCase;
|
||||
import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore;
|
||||
import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore;
|
||||
import dev.caskeleton.application.tenant.TenantId;
|
||||
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
|
||||
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
@@ -160,6 +163,38 @@ class DurableOperationControllerTest {
|
||||
.andExpect(jsonPath("$.error.code").value("OPERATION_NOT_FOUND"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 subject라도 token의 tenant가 다르면 남의 operation처럼 404다")
|
||||
void theSameSubjectInAnotherTenantGetsTheSame404() throws Exception {
|
||||
// given
|
||||
signIn("alice", "tenant-a");
|
||||
String operationId = operationIdOf(submit(REPORT).andReturn());
|
||||
signIn("alice", "tenant-b");
|
||||
|
||||
// when
|
||||
ResultActions response = mvc.perform(get("/operations/" + operationId));
|
||||
|
||||
// then
|
||||
response
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(jsonPath("$.error.code").value("OPERATION_NOT_FOUND"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSubmitterReadsTheirOperationInTheTenantTheyAreSignedInTo() throws Exception {
|
||||
// given
|
||||
signIn("alice", "tenant-a");
|
||||
String operationId = operationIdOf(submit(REPORT).andReturn());
|
||||
|
||||
// when
|
||||
ResultActions response = mvc.perform(get("/operations/" + operationId));
|
||||
|
||||
// then
|
||||
response
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.operationId").value(operationId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownOperationIs404() throws Exception {
|
||||
// given
|
||||
@@ -245,4 +280,16 @@ class DurableOperationControllerTest {
|
||||
new TestingAuthenticationToken(
|
||||
new AuthenticatedPrincipal(subject, subject + "@example.test", Set.of()), "n/a"));
|
||||
}
|
||||
|
||||
private static void signIn(String subject, String tenant) {
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(
|
||||
new TestingAuthenticationToken(
|
||||
new AuthenticatedPrincipal(
|
||||
subject,
|
||||
subject + "@example.test",
|
||||
Set.of(),
|
||||
Optional.of(new TenantId(tenant))),
|
||||
"n/a"));
|
||||
}
|
||||
}
|
||||
|
||||
+8
-3
@@ -1,11 +1,13 @@
|
||||
package dev.caskeleton.adapter.inbound.websocket.stomp;
|
||||
|
||||
import dev.caskeleton.domain.stereotype.DomainEvent;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.event.EventListener;
|
||||
@@ -39,14 +41,17 @@ public class LiveEventStompBroadcaster {
|
||||
private final SimpMessagingTemplate messaging;
|
||||
private final WebSocketSettings properties;
|
||||
private final List<LiveEventProjector<?>> projectors;
|
||||
private final Clock clock;
|
||||
|
||||
public LiveEventStompBroadcaster(
|
||||
SimpMessagingTemplate messaging,
|
||||
WebSocketSettings properties,
|
||||
List<LiveEventProjector<?>> projectors) {
|
||||
List<LiveEventProjector<?>> projectors,
|
||||
Clock clock) {
|
||||
this.messaging = messaging;
|
||||
this.properties = properties;
|
||||
this.projectors = List.copyOf(projectors);
|
||||
this.clock = Objects.requireNonNull(clock, "clock");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,13 +95,13 @@ public class LiveEventStompBroadcaster {
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> LiveEvent project(LiveEventProjector<T> projector, Object event) {
|
||||
private <T> LiveEvent project(LiveEventProjector<T> projector, Object event) {
|
||||
String eventType = projector.eventType();
|
||||
Map<String, String> fields = projector.project(projector.sourceType().cast(event));
|
||||
if (!validEventType(eventType) || !validFields(fields)) {
|
||||
return null;
|
||||
}
|
||||
return new LiveEvent(eventType, fields, Instant.now());
|
||||
return new LiveEvent(eventType, fields, clock.instant());
|
||||
}
|
||||
|
||||
private static boolean validEventType(String eventType) {
|
||||
|
||||
+10
-3
@@ -1,6 +1,8 @@
|
||||
package dev.caskeleton.adapter.inbound.websocket.stomp;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
|
||||
@@ -49,6 +51,7 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
private final SafeStompSubProtocolErrorHandler errorHandler =
|
||||
new SafeStompSubProtocolErrorHandler();
|
||||
private final WebSocketInboundAuthorizationInterceptor inboundAuthorization;
|
||||
private final WebSocketCorrelationInterceptor correlation = new WebSocketCorrelationInterceptor();
|
||||
|
||||
public WebSocketConfig(WebSocketSettings properties) {
|
||||
this.properties = properties;
|
||||
@@ -67,7 +70,8 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
|
||||
@Override
|
||||
public void configureClientInboundChannel(ChannelRegistration registration) {
|
||||
bounded(registration).interceptors(inboundAuthorization);
|
||||
// Correlation first, so an authorization refusal is logged with the frame's request id.
|
||||
bounded(registration).interceptors(correlation, inboundAuthorization);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -106,7 +110,10 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
|
||||
@Bean
|
||||
LiveEventStompBroadcaster liveEventStompBroadcaster(
|
||||
SimpMessagingTemplate messaging, List<LiveEventProjector<?>> projectors) {
|
||||
return new LiveEventStompBroadcaster(messaging, properties, projectors);
|
||||
SimpMessagingTemplate messaging,
|
||||
List<LiveEventProjector<?>> projectors,
|
||||
ObjectProvider<Clock> clocks) {
|
||||
return new LiveEventStompBroadcaster(
|
||||
messaging, properties, projectors, clocks.getIfAvailable(Clock::systemUTC));
|
||||
}
|
||||
}
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package dev.caskeleton.adapter.inbound.websocket.stomp;
|
||||
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.messaging.MessageChannel;
|
||||
import org.springframework.messaging.MessageHandler;
|
||||
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
|
||||
import org.springframework.messaging.support.ExecutorChannelInterceptor;
|
||||
|
||||
/**
|
||||
* Puts an inbound STOMP message's correlation on MDC under the keys the HTTP path uses (review
|
||||
* X2-P2-5).
|
||||
*
|
||||
* <p>Correlation used to stop at the servlet filter, so a log line written while a STOMP frame was
|
||||
* handled could not be joined to anything. Each inbound message gets its own {@code request_id},
|
||||
* minted here; {@code correlation_id} is the server-assigned session id, which joins every frame of
|
||||
* one connection. Neither is taken from a client header.
|
||||
*
|
||||
* <p>An {@link ExecutorChannelInterceptor} because the frames are handled on the inbound channel's
|
||||
* executor threads: the entries go on for the handling and the thread's previous MDC comes back
|
||||
* after it.
|
||||
*/
|
||||
final class WebSocketCorrelationInterceptor implements ExecutorChannelInterceptor {
|
||||
|
||||
private static final ThreadLocal<Map<String, String>> PREVIOUS = new ThreadLocal<>();
|
||||
|
||||
@Override
|
||||
public Message<?> beforeHandle(
|
||||
Message<?> message, MessageChannel channel, MessageHandler handler) {
|
||||
PREVIOUS.set(MDC.getCopyOfContextMap());
|
||||
MDC.put(MdcKeys.REQUEST_ID, UUID.randomUUID().toString());
|
||||
String session = SimpMessageHeaderAccessor.getSessionId(message.getHeaders());
|
||||
if (session != null) {
|
||||
MDC.put(MdcKeys.CORRELATION_ID, session);
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterMessageHandled(
|
||||
Message<?> message, MessageChannel channel, MessageHandler handler, Exception failure) {
|
||||
Map<String, String> restored = PREVIOUS.get();
|
||||
PREVIOUS.remove();
|
||||
if (restored == null) {
|
||||
MDC.clear();
|
||||
} else {
|
||||
MDC.setContextMap(restored);
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -11,6 +11,9 @@ import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.websocket.stomp.LiveEventStompBroadcaster.LiveEvent;
|
||||
import dev.caskeleton.domain.stereotype.DomainEvent;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -144,7 +147,8 @@ class LiveEventStompBroadcasterTest {
|
||||
}
|
||||
|
||||
private LiveEventStompBroadcaster broadcaster(List<LiveEventProjector<?>> projectors) {
|
||||
return new LiveEventStompBroadcaster(messaging, properties, projectors);
|
||||
return new LiveEventStompBroadcaster(
|
||||
messaging, properties, projectors, Clock.fixed(Instant.EPOCH, ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
private static LiveEventProjector<SampleReserved> sampleProjector() {
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package dev.caskeleton.adapter.inbound.websocket.stomp;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.shared.observability.MdcKeys;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.messaging.simp.stomp.StompCommand;
|
||||
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
|
||||
import org.springframework.messaging.support.MessageBuilder;
|
||||
|
||||
class WebSocketCorrelationInterceptorTest {
|
||||
|
||||
private final WebSocketCorrelationInterceptor interceptor = new WebSocketCorrelationInterceptor();
|
||||
|
||||
@AfterEach
|
||||
void clearMdc() {
|
||||
MDC.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("frame을 처리하는 동안 MDC에 request_id와 session id(correlation_id)가 있다")
|
||||
void aFrameIsHandledWithItsCorrelationOnMdc() {
|
||||
// when
|
||||
interceptor.beforeHandle(frame("session-1"), null, null);
|
||||
|
||||
// then
|
||||
assertThat(MDC.getCopyOfContextMap())
|
||||
.containsEntry(MdcKeys.CORRELATION_ID, "session-1")
|
||||
.containsKey(MdcKeys.REQUEST_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theThreadsMdcIsRestoredAfterTheFrame() {
|
||||
// given
|
||||
MDC.put("unrelated", "kept");
|
||||
Message<byte[]> frame = frame("session-1");
|
||||
interceptor.beforeHandle(frame, null, null);
|
||||
|
||||
// when
|
||||
interceptor.afterMessageHandled(frame, null, null, null);
|
||||
|
||||
// then
|
||||
assertThat(MDC.getCopyOfContextMap()).containsExactlyEntriesOf(Map.of("unrelated", "kept"));
|
||||
}
|
||||
|
||||
private static Message<byte[]> frame(String session) {
|
||||
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
|
||||
accessor.setSessionId(session);
|
||||
accessor.setDestination("/app/echo");
|
||||
return MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user