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:
donghyeon-ka
2026-09-29 14:17:48 +09:00
co-authored by Claude Opus 5.5
parent 4f4bd1fd34
commit 09e2dd63d6
163 changed files with 2216 additions and 1389 deletions
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
@@ -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);
}
}
}
@@ -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;
}
@@ -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();
}
}
@@ -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
@@ -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();
@@ -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);
}
}
}
}
@@ -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++;
}
@@ -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();
}
}
}
@@ -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));
}
}
@@ -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;
}
}
@@ -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));
}
}
@@ -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. */
@@ -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(
@@ -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,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;
+2 -1
View File
@@ -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`.
@@ -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) {
@@ -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<>();
@@ -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;
}
}
@@ -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);
}
}
@@ -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,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;
@@ -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());
}
};
}
}
@@ -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);
}
}
@@ -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"));
}
}
@@ -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,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;
@@ -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,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,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));
@@ -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");
}
}
@@ -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, ""));
}
}
@@ -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;
@@ -30,7 +30,7 @@ class WebMvcPlatformAutoConfigurationTest {
.hasNotFailed()
.hasSingleBean(GlobalExceptionHandler.class)
.hasSingleBean(WebMvcRequestIdFilter.class)
.hasBean("webMvcRequestContextConfigurer"));
.doesNotHaveBean("webMvcRequestContextConfigurer"));
}
@Test
@@ -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
@@ -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;
@@ -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;
@@ -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"));
}
}
@@ -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) {
@@ -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));
}
}
@@ -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);
}
}
}
@@ -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() {
@@ -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());
}
}
@@ -1,8 +1,8 @@
package dev.caskeleton.adapter.outbound.cache.redis.cache;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.HexFormat;
import java.util.Objects;
@@ -211,11 +211,7 @@ final class CacheEnvelope {
}
private static byte[] sha256(byte[] value) {
try {
return MessageDigest.getInstance("SHA-256").digest(value);
} catch (NoSuchAlgorithmException impossible) {
throw new IllegalStateException("SHA-256 is unavailable", impossible);
}
return Sha256.of(value).bytes();
}
/** A stored entry this deployment must not treat as an ordinary miss. */
@@ -4,21 +4,18 @@ import dev.caskeleton.application.fileserver.admin.ContentReferenceLedgerPort;
import dev.caskeleton.application.fileserver.admin.OrphanObject;
import dev.caskeleton.application.fileserver.admin.OrphanScanPort;
import dev.caskeleton.application.fileserver.api.ContentKey;
import dev.caskeleton.shared.digest.Sha256;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
@@ -227,13 +224,6 @@ public final class LocalOrphanScanAdapter implements OrphanScanPort {
private static String fingerprint(ContentKey key, long size, Instant modifiedAt) {
String material = key.value() + '|' + size + '|' + modifiedAt.toEpochMilli();
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return HexFormat.of()
.formatHex(digest.digest(material.getBytes(StandardCharsets.UTF_8)))
.substring(0, 32);
} catch (NoSuchAlgorithmException unavailable) {
throw new IllegalStateException("SHA-256 is required by the platform", unavailable);
}
return Sha256.ofUtf8(material).hex().substring(0, 32);
}
}
@@ -1,8 +1,8 @@
package dev.caskeleton.adapter.outbound.fileserver.platform.local;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
/**
@@ -14,8 +14,6 @@ import java.util.HexFormat;
*/
final class StreamingDigest {
private static final String ALGORITHM = "SHA-256";
private final MessageDigest digest;
private long offset;
@@ -25,7 +23,7 @@ final class StreamingDigest {
}
static StreamingDigest empty() {
return new StreamingDigest(newDigest(), 0);
return new StreamingDigest(Sha256.newMessageDigest(), 0);
}
void update(ByteBuffer buffer) {
@@ -56,12 +54,4 @@ final class StreamingDigest {
throw new IllegalStateException("SHA-256 digest is not cloneable", exception);
}
}
private static MessageDigest newDigest() {
try {
return MessageDigest.getInstance(ALGORITHM);
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 is required by the Java platform", exception);
}
}
}
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.httpclient.resilience;
import dev.caskeleton.adapter.outbound.httpclient.profile.JitterStrategy;
import dev.caskeleton.adapter.outbound.httpclient.profile.RetryAfterPolicy;
import dev.caskeleton.shared.retry.Backoff;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
@@ -9,7 +10,9 @@ import java.util.random.RandomGenerator;
/**
* Exponential backoff with jitter, bounded by max backoff, {@code Retry-After}, and the remaining
* deadline (design §17.5).
* deadline (design §17.5). The ceiling and the jitter words ({@code NONE}, {@code FULL}, {@code
* DECORRELATED}) are shared-contract {@link Backoff}'s, so "full jitter" means {@code U[0,
* ceiling]} here as everywhere else.
*
* <p>Jitter is not decoration: without it, a fleet that failed together retries together, and the
* upstream recovery window never opens. The random source is injectable so the schedule is
@@ -22,6 +25,7 @@ public final class ExponentialFullJitterBackoff implements BackoffStrategy {
private final JitterStrategy jitter;
private final RetryAfterPolicy retryAfterPolicy;
private final RandomGenerator random;
private final Backoff schedule;
private Duration previousDelay;
public ExponentialFullJitterBackoff(
@@ -35,6 +39,7 @@ public final class ExponentialFullJitterBackoff implements BackoffStrategy {
this.jitter = Objects.requireNonNull(jitter, "jitter strategy");
this.retryAfterPolicy = Objects.requireNonNull(retryAfterPolicy, "retry-after policy");
this.random = Objects.requireNonNull(random, "random generator");
this.schedule = new Backoff(baseBackoff, maxBackoff);
this.previousDelay = baseBackoff;
}
@@ -70,17 +75,11 @@ public final class ExponentialFullJitterBackoff implements BackoffStrategy {
}
private Duration computed(int completedAttempts) {
long exponent = Math.max(0, completedAttempts - 1);
long scaled = baseBackoff.toMillis() << Math.min(exponent, 20);
long capped = Math.min(scaled, maxBackoff.toMillis());
int attempt = Math.max(1, completedAttempts);
return switch (jitter) {
case NONE -> Duration.ofMillis(capped);
case FULL -> Duration.ofMillis(capped <= 0 ? 0 : random.nextLong(capped + 1));
case DECORRELATED -> {
long lower = baseBackoff.toMillis();
long upper = Math.min(maxBackoff.toMillis(), Math.max(lower, previousDelay.toMillis() * 3));
yield Duration.ofMillis(upper <= lower ? lower : random.nextLong(lower, upper + 1));
}
case NONE -> schedule.ceiling(attempt);
case FULL -> schedule.fullJitter(attempt, random);
case DECORRELATED -> schedule.decorrelatedJitter(previousDelay, random);
};
}
@@ -5,7 +5,6 @@ import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.application.messaging.event.AggregateIdentity;
import dev.caskeleton.application.messaging.event.AggregateOrder;
import dev.caskeleton.application.messaging.event.EventId;
@@ -16,6 +15,7 @@ import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxPublishAmbiguousException;
import dev.caskeleton.application.outbox.OutboxPublishOutcome;
import dev.caskeleton.application.outbox.OutboxPublishRefusedException;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
@@ -5,7 +5,6 @@ import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.application.messaging.event.AggregateIdentity;
import dev.caskeleton.application.messaging.event.AggregateOrder;
import dev.caskeleton.application.messaging.event.EventId;
@@ -26,6 +25,7 @@ import dev.caskeleton.messaging.api.publish.RoutingOutcome;
import dev.caskeleton.messaging.api.publish.TransmissionEvidence;
import dev.caskeleton.messaging.schema.EncodedMessage;
import dev.caskeleton.messaging.schema.EncodedMessagePublisher;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
@@ -9,6 +9,8 @@ dependencies {
implementation project(':application-notification')
implementation project(':shared-contract')
implementation project(':adapter:outbound:support')
// UUIDv7 for notification ids: the generator the sample's identifier adapters already use.
implementation libs.uuid.creator
implementation 'org.springframework.boot:spring-boot-autoconfigure'
implementation 'org.springframework.boot:spring-boot-actuator'
@@ -7,6 +7,7 @@ ch.qos.logback:logback-core:1.5.38=compileClasspath,runtimeClasspath,testCompile
com.ethlo.time:itu:1.14.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
com.github.f4b6a3:uuid-creator:6.1.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
com.github.spotbugs:spotbugs:4.10.2=spotbugs
@@ -5,8 +5,6 @@ import dev.caskeleton.adapter.outbound.notification.platform.template.JacksonNot
import dev.caskeleton.adapter.outbound.notification.platform.template.JsonSchemaVariableValidator;
import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationTemplateEngine;
import dev.caskeleton.adapter.outbound.notification.platform.template.PlaceholderTemplateEngine;
import dev.caskeleton.adapter.outbound.notification.platform.template.Sha256MessageDigestAdapter;
import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort;
import dev.caskeleton.application.notification.platform.dispatch.NotificationVariablesCodecPort;
import dev.caskeleton.application.notification.platform.security.ContactPointProtector;
import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider;
@@ -40,13 +38,6 @@ class NotificationPlatformCoreConfig {
return new JacksonNotificationVariablesCodec();
}
/** Request fingerprint hashing. */
@Bean
@ConditionalOnMissingBean
public MessageDigestPort notificationMessageDigest() {
return new Sha256MessageDigestAdapter();
}
/** JSON Schema 2020-12 variable validation. */
@Bean
@ConditionalOnMissingBean
@@ -1,10 +1,9 @@
package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure;
import dev.caskeleton.application.notification.platform.dispatch.CanonicalNotificationPlanWriter;
import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort;
import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort;
import dev.caskeleton.application.notification.platform.dispatch.NotificationRoutePlannerPort;
import dev.caskeleton.application.notification.platform.dispatch.RequestFingerprint;
import dev.caskeleton.application.notification.platform.dispatch.PlanFingerprint;
import dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint;
import dev.caskeleton.application.notification.platform.policy.CompositeNotificationEligibilityPolicy;
import dev.caskeleton.application.notification.platform.policy.DeduplicationService;
@@ -100,21 +99,20 @@ class NotificationPlatformPolicyConfig {
return new RoutingDecisionEngine();
}
/** Canonical request fingerprint. */
/** Canonical plan fingerprint. */
@Bean
public RequestFingerprint requestFingerprint(MessageDigestPort digest) {
return new RequestFingerprint(digest);
public PlanFingerprint planFingerprint() {
return new PlanFingerprint();
}
/**
* Identity of an event the platform synthesised from a provider's answer.
*
* @param digest the hashing boundary
* @return the fingerprint
*/
@Bean
public SyntheticEventFingerprint syntheticEventFingerprint(MessageDigestPort digest) {
return new SyntheticEventFingerprint(digest);
public SyntheticEventFingerprint syntheticEventFingerprint() {
return new SyntheticEventFingerprint();
}
/** Durable row factory for a submission. */
@@ -1,54 +1,36 @@
package dev.caskeleton.adapter.outbound.notification.platform.dispatch;
import com.github.f4b6a3.uuid.factory.standard.TimeOrderedEpochFactory;
import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort;
import java.security.SecureRandom;
import java.time.Clock;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
/**
* RFC 9562 UUIDv7.
* RFC 9562 UUIDv7, minted by uuid-creator — the same generator the sample's identifier adapters use
* (review S1-lead-2), rather than a second hand-written bit layout.
*
* <p>Time-ordered rather than random because these identifiers are primary keys: a random UUID
* scatters inserts across the whole index, and a notification table takes the highest insert rate
* in the platform.
*
* <p>The monotonic counter guards the case two identifiers are requested inside the same
* millisecond, so ordering holds even under a burst.
* <p>{@code withIncrementPlus1}: two identifiers requested inside the same millisecond still come
* out in order, so ordering holds even under a burst.
*/
public final class UuidV7Generator implements NotificationIdGeneratorPort {
private static final long VERSION_7 = 0x7000L;
private static final long VARIANT_RFC = 0x8000000000000000L;
private final Clock clock;
private final SecureRandom random;
private final AtomicLong lastMillis = new AtomicLong();
private final AtomicLong sequence = new AtomicLong();
private final TimeOrderedEpochFactory factory;
public UuidV7Generator(Clock clock) {
this(clock, new SecureRandom());
}
UuidV7Generator(Clock clock, SecureRandom random) {
this.clock = Objects.requireNonNull(clock, "clock");
this.random = Objects.requireNonNull(random, "random");
this.factory =
TimeOrderedEpochFactory.builder()
.withClock(Objects.requireNonNull(clock, "clock"))
.withIncrementPlus1()
.build();
}
@Override
public UUID nextId() {
long millis = clock.millis();
long previous = lastMillis.getAndSet(millis);
long counter = millis == previous ? sequence.incrementAndGet() : sequence.updateAndGet(x -> 0L);
long high = (millis & 0xFFFFFFFFFFFFL) << 16;
high |= VERSION_7;
high |= counter & 0x0FFFL;
long low = random.nextLong();
low &= 0x3FFFFFFFFFFFFFFFL;
low |= VARIANT_RFC;
return new UUID(high, low);
return factory.create();
}
}
@@ -1,20 +1,17 @@
package dev.caskeleton.adapter.outbound.notification.platform.security;
import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationDigest;
import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent;
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
import dev.caskeleton.application.notification.platform.callback.CallbackPayloadProtectionPort;
import dev.caskeleton.application.notification.platform.security.NotificationPayloadProtection;
import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider;
import dev.caskeleton.application.notification.platform.security.SecretPurpose;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import dev.caskeleton.shared.digest.HmacSha256;
import dev.caskeleton.shared.digest.Sha256;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.Objects;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* Bounded, encrypted retention of raw callback payloads.
@@ -101,7 +98,7 @@ public final class AesGcmCallbackPayloadProtection implements CallbackPayloadPro
@Override
public String digest(byte[] rawBody) {
Objects.requireNonNull(rawBody, "rawBody");
return NotificationDigest.hex(rawBody);
return Sha256.of(rawBody).hex();
}
@Override
@@ -128,17 +125,9 @@ public final class AesGcmCallbackPayloadProtection implements CallbackPayloadPro
+ '\u001f'
+ rawPayloadDigest;
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(
new SecretKeySpec(
// A fingerprint key and a contact-lookup key protect different things and must not
// fall
// together.
secrets.activeKey(SecretPurpose.CALLBACK_FINGERPRINT_HMAC).material(), "HmacSHA256"));
return HexFormat.of().formatHex(mac.doFinal(seed.getBytes(StandardCharsets.UTF_8)));
} catch (GeneralSecurityException failure) {
throw new IllegalStateException("callback fingerprinting failed", failure);
}
// A fingerprint key and a contact-lookup key protect different things and must not fall
// together.
byte[] key = secrets.activeKey(SecretPurpose.CALLBACK_FINGERPRINT_HMAC).material();
return HexFormat.of().formatHex(HmacSha256.sign(key, seed));
}
}
@@ -16,6 +16,7 @@ import dev.caskeleton.application.notification.platform.security.ProtectedContac
import dev.caskeleton.application.notification.platform.security.SecretKeyMaterial;
import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider;
import dev.caskeleton.application.notification.platform.security.SecretPurpose;
import dev.caskeleton.shared.digest.HmacSha256;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
@@ -24,7 +25,6 @@ import java.util.Base64;
import java.util.HexFormat;
import java.util.Objects;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
@@ -42,7 +42,6 @@ import javax.crypto.spec.SecretKeySpec;
public final class AesGcmContactPointProtector implements ContactPointProtector {
private static final String CIPHER = "AES/GCM/NoPadding";
private static final String HMAC = "HmacSHA256";
private static final String KEY_ALGORITHM = "AES";
private static final int NONCE_BYTES = 12;
private static final int TAG_BITS = 128;
@@ -163,14 +162,8 @@ public final class AesGcmContactPointProtector implements ContactPointProtector
private static String fingerprint(
SecretKeyMaterial key, ContactPointType type, String normalized) {
try {
Mac mac = Mac.getInstance(HMAC);
mac.init(new SecretKeySpec(key.material(), HMAC));
mac.update((type.name() + ":").getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(mac.doFinal(normalized.getBytes(StandardCharsets.UTF_8)));
} catch (GeneralSecurityException failure) {
throw new IllegalStateException("contact point fingerprinting failed", failure);
}
return HexFormat.of()
.formatHex(HmacSha256.sign(key.material(), type.name() + ":" + normalized));
}
/**
@@ -4,12 +4,9 @@ import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort;
import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider;
import dev.caskeleton.application.notification.platform.security.SecretPurpose;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import dev.caskeleton.shared.digest.HmacSha256;
import java.util.HexFormat;
import java.util.Objects;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* Keyed hash of a provider request id.
@@ -32,22 +29,11 @@ public final class HmacProviderRequestIdHasher implements ProviderRequestIdHashe
public String hash(ProviderProfileId profileId, String providerRequestId) {
Objects.requireNonNull(profileId, "profileId");
Objects.requireNonNull(providerRequestId, "providerRequestId");
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(
new SecretKeySpec(
// Its own purpose. This shared the contact-lookup key, so one compromised key forged
// both
// the contact index and the provider-request index — purpose separation exists to
// stop
// exactly that.
secrets.activeKey(SecretPurpose.PROVIDER_REQUEST_LOOKUP_HMAC).material(),
"HmacSHA256"));
mac.update((profileId.value() + ":").getBytes(StandardCharsets.UTF_8));
return HexFormat.of()
.formatHex(mac.doFinal(providerRequestId.getBytes(StandardCharsets.UTF_8)));
} catch (GeneralSecurityException failure) {
throw new IllegalStateException("provider request id hashing failed", failure);
}
// Its own purpose. This shared the contact-lookup key, so one compromised key forged both the
// contact index and the provider-request index — purpose separation exists to stop exactly
// that.
byte[] key = secrets.activeKey(SecretPurpose.PROVIDER_REQUEST_LOOKUP_HMAC).material();
return HexFormat.of()
.formatHex(HmacSha256.sign(key, profileId.value() + ":" + providerRequestId));
}
}
@@ -18,6 +18,7 @@ import dev.caskeleton.application.notification.platform.template.RenderedNotific
import dev.caskeleton.application.notification.platform.template.TemplateRegistry;
import dev.caskeleton.application.notification.platform.template.TemplateSlot;
import dev.caskeleton.application.notification.platform.template.TemplateVariableValidator;
import dev.caskeleton.shared.digest.Sha256;
import java.net.URI;
import java.util.List;
import java.util.Map;
@@ -67,16 +68,17 @@ public final class CanonicalNotificationRenderer implements NotificationTemplate
NotificationContent content = buildContent(command.channel(), template, command.variables());
String digest =
NotificationDigest.hex(
command.channel().name()
+ '\u001f'
+ template.templateId()
+ '\u001f'
+ template.version()
+ '\u001f'
+ template.locale().toLanguageTag()
+ '\u001f'
+ canonicalForm(content));
Sha256.ofUtf8(
command.channel().name()
+ '\u001f'
+ template.templateId()
+ '\u001f'
+ template.version()
+ '\u001f'
+ template.locale().toLanguageTag()
+ '\u001f'
+ canonicalForm(content))
.hex();
return new RenderedNotificationContent(content, digest, command.selection(), template.locale());
}
@@ -1,31 +0,0 @@
package dev.caskeleton.adapter.outbound.notification.platform.template;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
/** SHA-256 helper shared by rendering, fingerprinting and payload protection. */
public final class NotificationDigest {
private NotificationDigest() {}
/** Hex SHA-256 of a UTF-8 string. */
public static String hex(String value) {
return hex(value.getBytes(StandardCharsets.UTF_8));
}
/** Hex SHA-256 of raw bytes. */
public static String hex(byte[] value) {
return HexFormat.of().formatHex(sha256(value));
}
/** Raw SHA-256 of bytes. */
public static byte[] sha256(byte[] value) {
try {
return MessageDigest.getInstance("SHA-256").digest(value);
} catch (NoSuchAlgorithmException impossible) {
throw new IllegalStateException("SHA-256 is required by the Java platform", impossible);
}
}
}
@@ -1,12 +0,0 @@
package dev.caskeleton.adapter.outbound.notification.platform.template;
import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort;
/** Hashing adapter for the canonical request fingerprint. */
public final class Sha256MessageDigestAdapter implements MessageDigestPort {
@Override
public byte[] sha256(byte[] input) {
return NotificationDigest.sha256(input);
}
}
@@ -6,7 +6,6 @@ import dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmCont
import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationTemplateEngine;
import dev.caskeleton.adapter.outbound.notification.platform.template.PlaceholderTemplateEngine;
import dev.caskeleton.application.notification.platform.admin.NotificationAdminService;
import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort;
import dev.caskeleton.application.notification.platform.security.ContactPointProtector;
import dev.caskeleton.application.notification.platform.security.SecretKeyMaterial;
import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider;
@@ -37,19 +36,13 @@ class NotificationPlatformCoreConfigurationTest {
.run(
context -> {
assertThat(context).hasNotFailed();
assertThat(context).doesNotHaveBean(MessageDigestPort.class);
assertThat(context).doesNotHaveBean(TemplateVariableValidator.class);
});
}
@Test
void enablingThePlatformContributesItsDefaultRuntimeBeans() {
enabled()
.run(
context -> {
assertThat(context).hasSingleBean(MessageDigestPort.class);
assertThat(context).hasSingleBean(TemplateVariableValidator.class);
});
enabled().run(context -> assertThat(context).hasSingleBean(TemplateVariableValidator.class));
}
@Test
@@ -0,0 +1,46 @@
package dev.caskeleton.adapter.outbound.notification.platform.dispatch;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class UuidV7GeneratorTest {
private static final Clock FIXED =
Clock.fixed(Instant.parse("2026-09-29T00:00:00Z"), ZoneOffset.UTC);
@Test
void anIdIsAVersionSevenUuid() {
assertThat(new UuidV7Generator(FIXED).nextId().version()).isEqualTo(7);
}
@Test
@DisplayName("같은 밀리초 안의 연속 id도 생성 순서대로 정렬된다")
void idsMintedInOneMillisecondStayInOrder() {
// given
UuidV7Generator generator = new UuidV7Generator(FIXED);
List<UUID> ids = new ArrayList<>();
// when
for (int i = 0; i < 1_000; i++) {
ids.add(generator.nextId());
}
// then
assertThat(ids).isSortedAccordingTo(UuidV7GeneratorTest::unsigned).doesNotHaveDuplicates();
}
private static int unsigned(UUID left, UUID right) {
int high = Long.compareUnsigned(left.getMostSignificantBits(), right.getMostSignificantBits());
return high != 0
? high
: Long.compareUnsigned(left.getLeastSignificantBits(), right.getLeastSignificantBits());
}
}
@@ -127,7 +127,7 @@ class NotificationPerformanceCertificationTest {
void backoffStaysWithinItsCeilingAcrossManyAttempts() {
var backoff =
new dev.caskeleton.application.notification.platform.policy.RetryBackoff(
Duration.ofSeconds(1), Duration.ofMinutes(5), 2.0d);
Duration.ofSeconds(1), Duration.ofMinutes(5));
var jitter = dev.caskeleton.application.notification.platform.policy.JitterSource.none();
for (int attempt = 1; attempt <= 40; attempt++) {
@@ -1,10 +1,7 @@
package dev.caskeleton.adapter.outbound.objectstorage.codec;
import dev.caskeleton.shared.digest.Sha256;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
/** Canonical lowercase Crockford Base32 and bounded namespace support. */
public final class CrockfordBase32 {
@@ -46,12 +43,6 @@ public final class CrockfordBase32 {
}
static String sha256Hex(String value) {
try {
return HexFormat.of()
.formatHex(
MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 must be available", exception);
}
return Sha256.ofUtf8(value).hex();
}
}
@@ -2,9 +2,7 @@ package dev.caskeleton.adapter.outbound.objectstorage.codec;
import dev.caskeleton.application.objectstorage.identity.ObjectId;
import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import dev.caskeleton.shared.digest.Sha256;
import java.util.Arrays;
import java.util.Objects;
@@ -31,13 +29,8 @@ public final class ObjectIdentityCodec {
+ operationKey.operationId().value()
+ "\n"
+ requestFingerprint;
try {
byte[] digest =
MessageDigest.getInstance("SHA-256").digest(seed.getBytes(StandardCharsets.UTF_8));
return ObjectId.parse(CrockfordBase32.encode(Arrays.copyOf(digest, 16), 26));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 must be available", exception);
}
byte[] digest = Sha256.ofUtf8(seed).bytes();
return ObjectId.parse(CrockfordBase32.encode(Arrays.copyOf(digest, 16), 26));
}
/** Lower-case hex SHA-256 of the UTF-8 bytes of {@code value}. */
@@ -6,6 +6,7 @@ import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectMutati
import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectReadAdapter;
import dev.caskeleton.adapter.outbound.objectstorage.s3.S3ObjectStorageProviderContribution;
import dev.caskeleton.application.outbound.SecretSourcePort;
import java.time.Clock;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
@@ -41,10 +42,11 @@ public class ObjectStorageCapabilityConfig {
matchIfMissing = true)
@ConditionalOnMissingBean(name = "s3ObjectStorageProviderContribution")
public ObjectStorageProviderContribution s3ObjectStorageProviderContribution(
ObjectProvider<SecretSourcePort> secretSources) {
ObjectProvider<SecretSourcePort> secretSources, ObjectProvider<Clock> clocks) {
// Looked up when an S3 binding actually resolves a credential, so a local-only composition
// without a secret backend still starts; an S3 credential without one fails at that point.
return new S3ObjectStorageProviderContribution(key -> secretSources.getObject().resolve(key));
return new S3ObjectStorageProviderContribution(
key -> secretSources.getObject().resolve(key), clock(clocks));
}
@Bean
@@ -54,7 +56,9 @@ public class ObjectStorageCapabilityConfig {
havingValue = "true",
matchIfMissing = true)
public ObjectStorageBindingCompiler objectStorageBindingCompiler(
List<ObjectStorageProviderContribution> contributions, Environment environment) {
List<ObjectStorageProviderContribution> contributions,
Environment environment,
ObjectProvider<Clock> clocks) {
Set<String> profiles =
Set.copyOf(
Arrays.asList(
@@ -64,7 +68,8 @@ public class ObjectStorageCapabilityConfig {
boolean scannerWorkflowEnabled =
environment.getProperty(
"app.object-storage.scan-maintenance.enabled", Boolean.class, false);
return new ObjectStorageBindingCompiler(contributions, profiles, scannerWorkflowEnabled);
return new ObjectStorageBindingCompiler(
contributions, profiles, scannerWorkflowEnabled, clock(clocks));
}
@Bean
@@ -97,8 +102,9 @@ public class ObjectStorageCapabilityConfig {
havingValue = "true",
matchIfMissing = true)
public RoutingObjectMutationAdapter routingObjectMutationAdapter(
ObjectStorageCapabilityAssembler.AssembledCapability capability) {
return new RoutingObjectMutationAdapter(capability);
ObjectStorageCapabilityAssembler.AssembledCapability capability,
ObjectProvider<Clock> clocks) {
return new RoutingObjectMutationAdapter(capability, clock(clocks));
}
@Bean
@@ -108,8 +114,9 @@ public class ObjectStorageCapabilityConfig {
havingValue = "true",
matchIfMissing = true)
public ObjectPublicationHandoffService objectPublicationHandoffService(
ObjectStorageCapabilityAssembler.AssembledCapability capability) {
return new ObjectPublicationHandoffService(capability, java.time.Clock.systemUTC());
ObjectStorageCapabilityAssembler.AssembledCapability capability,
ObjectProvider<Clock> clocks) {
return new ObjectPublicationHandoffService(capability, clock(clocks));
}
@Bean
@@ -122,4 +129,14 @@ public class ObjectStorageCapabilityConfig {
ObjectStorageCapabilityAssembler.AssembledCapability capability) {
return new RoutingObjectReadAdapter(capability);
}
/**
* The application's {@link Clock} bean, or the system UTC clock when the composition has none.
*
* <p>One clock for the whole capability: a component that read {@code Instant.now()} beside an
* injected clock recorded times a test (or a deployment with a controlled clock) could not see.
*/
static Clock clock(ObjectProvider<Clock> clocks) {
return clocks.getIfAvailable(Clock::systemUTC);
}
}
@@ -1,6 +1,8 @@
package dev.caskeleton.adapter.outbound.objectstorage.config;
import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectScanMaintenanceAdapter;
import java.time.Clock;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -20,7 +22,9 @@ public class ObjectStorageScanMaintenanceConfig {
name = "enabled",
havingValue = "true")
public RoutingObjectScanMaintenanceAdapter routingObjectScanMaintenanceAdapter(
ObjectStorageCapabilityAssembler.AssembledCapability capability) {
return new RoutingObjectScanMaintenanceAdapter(capability, java.time.Clock.systemUTC());
ObjectStorageCapabilityAssembler.AssembledCapability capability,
ObjectProvider<Clock> clocks) {
return new RoutingObjectScanMaintenanceAdapter(
capability, ObjectStorageCapabilityConfig.clock(clocks));
}
}
@@ -24,14 +24,13 @@ import dev.caskeleton.application.objectstorage.model.ObjectMediaType;
import dev.caskeleton.application.objectstorage.model.ObjectPublicationRequirement;
import dev.caskeleton.application.objectstorage.model.ObjectRetentionRequirement;
import dev.caskeleton.application.objectstorage.model.ObjectScanState;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Base64;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HexFormat;
import java.util.Objects;
import java.util.stream.Collectors;
@@ -104,11 +103,7 @@ public final class CanonicalJsonObjectControlRecordCodec implements ObjectContro
}
public String sha256Hex(byte[] value) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 must be available", exception);
}
return Sha256.of(value).hex();
}
private static byte[] payload(ObjectControlRecord record) {
@@ -3,12 +3,9 @@ package dev.caskeleton.adapter.outbound.objectstorage.control;
import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey;
import dev.caskeleton.application.objectstorage.identity.ObjectStageHandle;
import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import dev.caskeleton.shared.digest.Sha256;
import java.time.Duration;
import java.time.Instant;
import java.util.HexFormat;
import java.util.Objects;
/** Durable monotonically fenced application-to-publication handoff lease. */
@@ -191,13 +188,6 @@ public record ObjectPublicationHandoffRecord(
if (claimant == null || claimant.isBlank() || claimant.length() > 128) {
throw new IllegalArgumentException("handoff claimant is invalid");
}
try {
return HexFormat.of()
.formatHex(
MessageDigest.getInstance("SHA-256")
.digest(claimant.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 must be available", exception);
}
return Sha256.ofUtf8(claimant).hex();
}
}
@@ -11,6 +11,7 @@ import dev.caskeleton.application.objectstorage.identity.ObjectId;
import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken;
import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity;
import dev.caskeleton.application.objectstorage.model.ObjectDigest;
import dev.caskeleton.shared.digest.Sha256;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
@@ -20,7 +21,6 @@ import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Optional;
@@ -90,7 +90,7 @@ public final class LocalDevObjectDataStore {
return Optional.empty();
}
try {
MessageDigest digest = sha256();
MessageDigest digest = Sha256.newMessageDigest();
long size = 0;
ByteBuffer buffer = ByteBuffer.allocate(64 * 1024);
try (FileChannel channel = FileChannel.open(source, StandardOpenOption.READ)) {
@@ -173,14 +173,6 @@ public final class LocalDevObjectDataStore {
ObjectRouteToken.parse(segments[2]), ObjectId.parse(segments[4]));
}
private static MessageDigest sha256() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 must be available", exception);
}
}
private static ObjectStorageProviderException conflict() {
return new ObjectStorageProviderException(
ObjectStorageProviderException.Failure.CONFLICT, "local immutable object already exists");
@@ -15,13 +15,13 @@ import dev.caskeleton.application.objectstorage.content.ObjectContentProductionE
import dev.caskeleton.application.objectstorage.content.ObjectContentReadContext;
import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity;
import dev.caskeleton.application.objectstorage.model.ObjectDigest;
import dev.caskeleton.shared.digest.Sha256;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Objects;
@@ -39,7 +39,7 @@ public final class LocalObjectStreamTransfer {
throws IOException {
Objects.requireNonNull(producer, "producer must be non-null");
requireActive(operation.budget(), operation.cancellation().isCancelled());
MessageDigest digest = sha256();
MessageDigest digest = Sha256.newMessageDigest();
long[] written = {0};
ObjectContentProductionContext context =
ObjectContentProductionContext.open(
@@ -160,14 +160,6 @@ public final class LocalObjectStreamTransfer {
}
}
private static MessageDigest sha256() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 must be available", exception);
}
}
private static void requireActive(
dev.caskeleton.application.outbound.CallBudget budget, boolean cancelled) {
if (cancelled) {
@@ -19,7 +19,7 @@ import dev.caskeleton.application.objectstorage.model.ObjectMutationOutcome;
import dev.caskeleton.application.objectstorage.model.ObjectPublicationRequirement;
import dev.caskeleton.application.objectstorage.model.ObjectPublishReceipt;
import dev.caskeleton.application.objectstorage.request.ObjectPublishRequest;
import java.time.Instant;
import java.time.Clock;
import java.util.Objects;
import java.util.Optional;
@@ -33,12 +33,14 @@ import java.util.Optional;
public final class ManagedObjectPublicationKernel {
private final ObjectStorageCapabilityAssembler.DestinationRuntime runtime;
private final Clock clock;
private final ObjectReferencePublicationService references =
new ObjectReferencePublicationService();
public ManagedObjectPublicationKernel(
ObjectStorageCapabilityAssembler.DestinationRuntime runtime) {
ObjectStorageCapabilityAssembler.DestinationRuntime runtime, Clock clock) {
this.runtime = Objects.requireNonNull(runtime, "runtime must be non-null");
this.clock = Objects.requireNonNull(clock, "clock must be non-null");
}
public ObjectPublishReceipt publish(
@@ -69,7 +71,7 @@ public final class ManagedObjectPublicationKernel {
runtime.destination().route(),
runtime.destination().policySnapshot(),
request.contentIdentity(),
Instant.now());
clock.instant());
if (reserved.decision() == ObjectOperationKernelResult.Decision.CONFLICT) {
throw new IllegalArgumentException("operation identity conflicts with a different intent");
}
@@ -100,7 +102,7 @@ public final class ManagedObjectPublicationKernel {
operation,
PublicationOperationState.PUBLISHED,
stored.contentIdentity(),
Instant.now());
clock.instant());
}
}
ObjectOperationRecord terminal = requireOperation(request);
@@ -118,7 +120,7 @@ public final class ManagedObjectPublicationKernel {
runtime.destination().policySnapshot().policyRevision().value());
}
private static ObjectStorageProvider.StoredData continueDataPublication(
private ObjectStorageProvider.StoredData continueDataPublication(
ObjectOperationKernel kernel,
ObjectOperationRecord initial,
ObjectStorageProviderOperation providerOperation,
@@ -128,7 +130,7 @@ public final class ManagedObjectPublicationKernel {
if (operation.stablePhase() == PublicationOperationState.RESERVED) {
operation =
kernel.advancePublication(
operation, PublicationOperationState.DATA_UPLOAD_IN_PROGRESS, null, Instant.now());
operation, PublicationOperationState.DATA_UPLOAD_IN_PROGRESS, null, clock.instant());
}
if (operation.stablePhase() != PublicationOperationState.DATA_UPLOAD_IN_PROGRESS) {
return provider
@@ -160,17 +162,17 @@ public final class ManagedObjectPublicationKernel {
throw new IllegalStateException("provider create cannot be resolved safely");
}
if (operation.effectCertainty() != ObjectEffectCertainty.CONFIRMED) {
operation = kernel.confirmEffect(operation, Instant.now());
operation = kernel.confirmEffect(operation, clock.instant());
}
kernel.advancePublication(
operation,
PublicationOperationState.DATA_UPLOADED,
stored.contentIdentity(),
Instant.now());
clock.instant());
return stored;
}
private static ObjectOperationRecord advanceToReferencePublication(
private ObjectOperationRecord advanceToReferencePublication(
ObjectOperationKernel kernel, ObjectOperationRecord initial) {
ObjectOperationRecord operation = initial;
if (operation.stablePhase() == PublicationOperationState.DATA_UPLOADED) {
@@ -179,7 +181,7 @@ public final class ManagedObjectPublicationKernel {
operation,
PublicationOperationState.INTEGRITY_VERIFIED,
operation.observedContentIdentity(),
Instant.now());
clock.instant());
}
if (operation.stablePhase() == PublicationOperationState.INTEGRITY_VERIFIED) {
operation =
@@ -187,7 +189,7 @@ public final class ManagedObjectPublicationKernel {
operation,
PublicationOperationState.REFERENCE_PUBLISH_IN_PROGRESS,
operation.observedContentIdentity(),
Instant.now());
clock.instant());
}
return operation;
}
@@ -30,7 +30,6 @@ import dev.caskeleton.application.objectstorage.request.ObjectRetireRequest;
import dev.caskeleton.application.objectstorage.request.ObjectStageRequest;
import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest;
import java.time.Clock;
import java.time.Instant;
import java.util.Optional;
/** Normal mutation router. It never implements privileged purge or scanner-maintenance ports. */
@@ -43,11 +42,6 @@ public final class RoutingObjectMutationAdapter
private final ObjectStorageCapabilityAssembler.AssembledCapability capability;
private final Clock clock;
public RoutingObjectMutationAdapter(
ObjectStorageCapabilityAssembler.AssembledCapability capability) {
this(capability, Clock.systemUTC());
}
public RoutingObjectMutationAdapter(
ObjectStorageCapabilityAssembler.AssembledCapability capability, Clock clock) {
this.capability = java.util.Objects.requireNonNull(capability);
@@ -80,7 +74,7 @@ public final class RoutingObjectMutationAdapter
public ObjectPublishReceipt publish(
ObjectPublishRequest request, ObjectContentProducer producer) {
return new ManagedObjectPublicationKernel(
capability.destination(request.operationKey().destination()))
capability.destination(request.operationKey().destination()), clock)
.publish(request, producer);
}
@@ -106,7 +100,7 @@ public final class RoutingObjectMutationAdapter
request.operationKey(),
ObjectMutationOutcome.REJECTED,
ObjectOperationError.CONFLICT,
Instant.now());
clock.instant());
}
if (record.state() == PublishedReferenceState.RETIRED
|| record.state() == PublishedReferenceState.PURGE_ELIGIBLE
@@ -115,7 +109,7 @@ public final class RoutingObjectMutationAdapter
request.operationKey(),
ObjectMutationOutcome.REPLAYED,
ObjectOperationError.NONE,
Instant.now());
clock.instant());
}
ObjectReferenceRecord pending =
new ObjectReferenceRecord(
@@ -126,7 +120,7 @@ public final class RoutingObjectMutationAdapter
record.objectId(),
record.immutableDataVersion(),
PublishedReferenceState.RETIREMENT_PENDING,
Instant.now());
clock.instant());
current = store.compareAndSet(key, new ObjectControlMutation(current.version(), pending));
ObjectReferenceRecord retired =
new ObjectReferenceRecord(
@@ -137,13 +131,13 @@ public final class RoutingObjectMutationAdapter
record.objectId(),
record.immutableDataVersion(),
PublishedReferenceState.RETIRED,
Instant.now());
clock.instant());
store.compareAndSet(key, new ObjectControlMutation(current.version(), retired));
return new ObjectMutationReceipt(
request.operationKey(),
ObjectMutationOutcome.APPLIED,
ObjectOperationError.NONE,
Instant.now());
clock.instant());
}
@Override
@@ -9,9 +9,9 @@ import dev.caskeleton.application.objectstorage.content.ObjectContentProducer;
import dev.caskeleton.application.objectstorage.content.ObjectContentProductionContext;
import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity;
import dev.caskeleton.application.objectstorage.model.ObjectDigest;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
@@ -113,7 +113,7 @@ public final class S3AsyncRequestBodyBridge implements AsyncRequestBody {
}
private void produce() {
MessageDigest digest = sha256();
MessageDigest digest = Sha256.newMessageDigest();
long[] written = {0};
CancellationView cancellation = () -> operation.cancellation().isCancelled() || isCancelled();
ObjectContentProductionContext context =
@@ -243,14 +243,6 @@ public final class S3AsyncRequestBodyBridge implements AsyncRequestBody {
}
}
private static MessageDigest sha256() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 must be available", exception);
}
}
private static ObjectStorageProviderException providerFailure(
ObjectStorageProviderException.Failure failure, String message, Throwable cause) {
return cause == null
@@ -6,9 +6,9 @@ import dev.caskeleton.application.objectstorage.content.ObjectChunkReadException
import dev.caskeleton.application.objectstorage.content.ObjectChunkSource;
import dev.caskeleton.application.objectstorage.content.ObjectContentConsumer;
import dev.caskeleton.application.objectstorage.content.ObjectContentReadContext;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
@@ -109,7 +109,7 @@ public final class S3AsyncResponseBodyBridge<R> implements AsyncResponseTransfor
operation.contentIdentity(),
operation.exactVersion(),
operation.range());
MessageDigest digest = sha256();
MessageDigest digest = Sha256.newMessageDigest();
ChunkCursor cursor = new ChunkCursor(subscriber, digest);
ObjectChunkSource source = ObjectChunkSource.scoped(context, cursor::read);
Throwable failure = null;
@@ -323,14 +323,6 @@ public final class S3AsyncResponseBodyBridge<R> implements AsyncResponseTransfor
}
}
private static MessageDigest sha256() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 must be available", exception);
}
}
private static final class Chunk {
private final byte[] bytes;
@@ -35,11 +35,11 @@ public final class S3ObjectStorageProviderContribution
* Production contribution. Credential references resolve through the deployment's configured
* secret backend, never straight from the process environment.
*/
public S3ObjectStorageProviderContribution(SecretSourcePort secretSource) {
public S3ObjectStorageProviderContribution(SecretSourcePort secretSource, Clock clock) {
this(
Clock.systemUTC(),
clock,
new S3ProviderQualifier(
Clock.systemUTC(),
clock,
(binding, plan) -> {
throw new IllegalStateException("startup S3 probing is not configured");
}),
@@ -1,12 +1,9 @@
package dev.caskeleton.adapter.outbound.persistence.api.query;
import dev.caskeleton.shared.digest.HmacSha256;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Objects;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* A versioned, tamper-evident cursor codec built only on the Java standard library (design §27.3).
@@ -20,15 +17,14 @@ import javax.crypto.spec.SecretKeySpec;
* seek to arbitrary keys, which turns a paging token into an access-control bypass wherever the
* predicate depends on where the scan started.
*
* <p>Verification is constant-time via {@link MessageDigest#isEqual}. A short-circuiting comparison
* here leaks the correct MAC one byte at a time.
* <p>Signing and constant-time verification are shared-contract {@link HmacSha256}; a
* short-circuiting comparison here would leak the correct MAC one byte at a time.
*/
public final class SignedJsonCursorCodec<C> {
/** The only cursor version this codec issues and accepts. */
public static final String VERSION = "v1";
private static final String ALGORITHM = "HmacSHA256";
private static final int MINIMUM_KEY_LENGTH = 32;
private static final char SEPARATOR = '.';
@@ -56,9 +52,6 @@ public final class SignedJsonCursorCodec<C> {
/** Largest payload this codec will decode, in bytes. */
public static final int MAX_PAYLOAD_BYTES = 2048;
/** HMAC-SHA256 produces exactly this many bytes. */
private static final int MAC_LENGTH_BYTES = 32;
/** Encodes a cursor into a client-safe, tamper-evident token. */
public String encode(C cursor) {
Objects.requireNonNull(cursor, "cursor");
@@ -71,7 +64,7 @@ public final class SignedJsonCursorCodec<C> {
}
String payload = encoder.encodeToString(json);
String signed = VERSION + SEPARATOR + payload;
String token = signed + SEPARATOR + encoder.encodeToString(mac(signed));
String token = signed + SEPARATOR + encoder.encodeToString(HmacSha256.sign(key, signed));
if (token.length() > MAX_ENCODED_LENGTH) {
throw new IllegalStateException(
"cursor token is " + token.length() + " characters; the bound is " + MAX_ENCODED_LENGTH);
@@ -114,12 +107,10 @@ public final class SignedJsonCursorCodec<C> {
}
String signed = encoded.substring(0, macSeparator);
byte[] presented = decodeBase64(encoded.substring(macSeparator + 1));
if (presented.length != MAC_LENGTH_BYTES) {
// Checked before the comparison. `MessageDigest.isEqual` is constant time for equal-length
// inputs; feeding it a differently-sized array asks it a question it was not built to answer.
if (presented.length != HmacSha256.MAC_BYTES) {
throw new IllegalArgumentException("malformed cursor");
}
if (!MessageDigest.isEqual(mac(signed), presented)) {
if (!HmacSha256.verify(key, signed, presented)) {
throw new IllegalArgumentException("cursor signature does not verify");
}
// The payload decoder runs only after the signature verified, so an unsigned token never
@@ -140,14 +131,4 @@ public final class SignedJsonCursorCodec<C> {
throw new IllegalArgumentException("malformed cursor", malformed);
}
}
private byte[] mac(String signed) {
try {
Mac mac = Mac.getInstance(ALGORITHM);
mac.init(new SecretKeySpec(key, ALGORITHM));
return mac.doFinal(signed.getBytes(StandardCharsets.UTF_8));
} catch (GeneralSecurityException unavailable) {
throw new IllegalStateException("cursor signing algorithm is unavailable", unavailable);
}
}
}
@@ -3,14 +3,20 @@ package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa;
import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.entity.IdempotencyRecordEntity;
import java.time.Instant;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
/** Spring Data repository for {@link IdempotencyRecordEntity}: the reaper's expiry purge. */
public interface IdempotencyRecordJpaRepository
extends JpaRepository<IdempotencyRecordEntity, UUID> {
/**
* Spring Data repository for {@link IdempotencyRecordEntity}: the reaper's expiry purge, and
* nothing else.
*
* <p>A {@code Repository} marker rather than {@code JpaRepository}: the records belong to scopes,
* and the inherited {@code findAll}/{@code deleteAll} were statements across every scope that no
* caller used and any next caller could.
*/
public interface IdempotencyRecordJpaRepository extends Repository<IdempotencyRecordEntity, UUID> {
/** Reaper / TTL boundary (§E): purge every record whose expiry is at/before {@code now}. */
@Modifying
@@ -1,10 +1,10 @@
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import java.util.Objects;
import javax.sql.DataSource;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* The preconditions a mutation must meet before any SQL runs.
@@ -90,20 +90,6 @@ final class IdempotencyCapabilityGuard {
* @throws IllegalStateException naming which of the three conditions failed
*/
void requirePrimaryWriteTransaction() {
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException(
"owner-safe idempotency mutation requires an active primary transaction");
}
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
throw new IllegalStateException(
"owner-safe idempotency mutation requires a read-write transaction");
}
if (dataSource != null && !TransactionSynchronizationManager.hasResource(dataSource)) {
// The exact check the outbox and inbox adapters already make. Without it, a transaction on
// another data source satisfied the guard while this store's work committed on its own.
throw new IllegalStateException(
"owner-safe idempotency mutation requires a transaction bound to this store's data"
+ " source; the active transaction belongs to another one");
}
CallerTransaction.requireReadWrite("owner-safe idempotency mutation", dataSource);
}
}
@@ -1,9 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import dev.caskeleton.shared.digest.Sha256;
import java.util.Objects;
/**
@@ -73,12 +70,6 @@ final class IdempotencyDigestPolicy {
}
private static String sha256(String value) {
try {
return HexFormat.of()
.formatHex(
MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException unavailable) {
throw new IllegalStateException("SHA-256 unavailable", unavailable);
}
return Sha256.ofUtf8(value).hex();
}
}
@@ -19,9 +19,8 @@ import dev.caskeleton.application.idempotency.IdempotencyState;
import dev.caskeleton.application.idempotency.IdempotencyStorePort;
import dev.caskeleton.application.idempotency.StoredResponse;
import dev.caskeleton.application.transaction.OperationId;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
@@ -645,13 +644,7 @@ public class PostgreSqlOwnerSafeIdempotencyStore implements IdempotencyStorePort
}
private static String sha256(String value) {
try {
byte[] digest =
MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest);
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 unavailable", exception);
}
return Sha256.ofUtf8(value).hex();
}
private IllegalStateException indeterminateClaim() {
@@ -1,6 +1,7 @@
package dev.caskeleton.adapter.outbound.persistence.liveevent;
import dev.caskeleton.adapter.outbound.persistence.liveevent.entity.LiveEventEntity;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.realtime.LiveEventReplayPort;
import dev.caskeleton.application.realtime.ReplayCursorUnavailableException;
import dev.caskeleton.application.realtime.ReplayWindow;
@@ -16,7 +17,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.domain.Limit;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* Retained live-event history, on PostgreSQL.
@@ -161,9 +161,6 @@ public class JpaLiveEventReplayAdapter implements LiveEventReplayPort {
}
private static void requireCallerTransaction(String operation) {
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException(
"live-event " + operation + " requires an active caller transaction");
}
CallerTransaction.require("live-event " + operation);
}
}
@@ -1,6 +1,7 @@
package dev.caskeleton.adapter.outbound.persistence.operation;
import dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOperationEntity;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.idempotency.RequestFingerprint;
import dev.caskeleton.application.operation.DurableOperation;
import dev.caskeleton.application.operation.DurableOperationId;
@@ -16,7 +17,6 @@ import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* The PostgreSQL-backed {@link DurableOperationStorePort}.
@@ -171,10 +171,7 @@ public class DurableOperationStoreAdapter implements DurableOperationStorePort {
}
private static void requireCallerTransaction(String operation) {
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException(
"durable operation " + operation + " requires an active caller transaction");
}
CallerTransaction.require("durable operation " + operation);
}
private static DurableOperation expireIfStale(DurableOperation operation, Instant now) {
@@ -3,9 +3,10 @@ package dev.caskeleton.adapter.outbound.persistence.outbox.jpa;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
import java.time.Instant;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
@@ -13,8 +14,19 @@ import org.springframework.transaction.annotation.Transactional;
* Spring Data repository for {@link OutboxEventEntity} — only vendor-neutral operations.
* Vendor-specific row claiming lives in the {@link OutboxClaimRepository} SPI (see README
* "outbox").
*
* <p>A {@code Repository} marker declaring only what the store uses. It extended {@code
* JpaRepository}, which put {@code findAll}/{@code deleteAll} over the whole outbox on the
* interface every caller holds; nothing used them, and a {@code deleteAll} there is every
* unpublished event.
*/
public interface OutboxEventJpaRepository extends JpaRepository<OutboxEventEntity, String> {
public interface OutboxEventJpaRepository extends Repository<OutboxEventEntity, String> {
/** Appends a row (the store's {@code append}). */
<S extends OutboxEventEntity> S save(S entity);
/** Reads one row by its event id. */
Optional<OutboxEventEntity> findById(String eventId);
/**
* Deletes at most {@code limit} PUBLISHED rows whose {@code occurred_at} is before {@code
@@ -1,9 +1,9 @@
package dev.caskeleton.adapter.outbound.persistence.outbox.jpa;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.application.messaging.event.AggregateIdentity;
import dev.caskeleton.application.messaging.event.AggregateOrder;
import dev.caskeleton.application.messaging.event.EventId;
@@ -14,6 +14,7 @@ import dev.caskeleton.application.outbox.OutboxCompletion;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxLease;
import dev.caskeleton.application.outbox.OutboxStorePort;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
@@ -29,7 +30,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* JPA-backed {@link OutboxAppendPort} + {@link OutboxStorePort}. {@link #append} and the claim/mark
@@ -166,10 +166,7 @@ public class OutboxStoreAdapter implements OutboxAppendPort, OutboxStorePort {
}
private static void requireTransaction(String operation) {
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException(
"outbox " + operation + " requires an active caller transaction");
}
CallerTransaction.require("outbox " + operation);
}
@Override
@@ -4,6 +4,7 @@ import dev.caskeleton.adapter.outbound.persistence.api.query.QueryName;
import dev.caskeleton.adapter.outbound.persistence.api.query.QueryObservation;
import dev.caskeleton.adapter.outbound.persistence.api.query.QueryScope;
import dev.caskeleton.adapter.outbound.persistence.hibernate.QueryNameContext;
import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
@@ -58,7 +59,7 @@ public final class JpaStreamExecutor {
Objects.requireNonNull(policy, "policy");
Objects.requireNonNull(supplier, "supplier");
Objects.requireNonNull(consumer, "consumer");
JpaStreamScope.requireActiveReadOnly();
CallerTransaction.requireReadOnly("streaming");
return QueryNameContext.with(
query,
@@ -1,45 +0,0 @@
package dev.caskeleton.adapter.outbound.persistence.springdata;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* The guard every streaming read passes through (design §27.4).
*
* <p>A JPA {@code Stream} is a live cursor: it holds a JDBC {@code ResultSet}, which holds a
* statement, which holds the connection. All three are released only when the stream closes and the
* transaction ends. Returning one past the transaction boundary — from a repository to a
* controller, or out of a service method — leaves that chain open until the pool notices, which is
* a connection leak that presents as unrelated timeouts elsewhere.
*
* <p>Requiring a read-only transaction is not cosmetic either. Streaming inside a write transaction
* keeps a write connection pinned for the whole traversal, which is the slowest possible way to
* hold the most contended resource.
*/
public final class JpaStreamScope {
private JpaStreamScope() {}
/**
* Fails unless an actual read-only transaction is active.
*
* @throws IllegalStateException when no transaction is active, or the active one is a write
*/
public static void requireActiveReadOnly() {
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException(
"streaming requires an active transaction; without one the cursor closes after the first"
+ " statement and the connection is returned mid-traversal");
}
if (!TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
throw new IllegalStateException(
"streaming requires a read-only transaction; a write transaction pins a write connection"
+ " for the whole traversal");
}
}
/** Whether a read-only transaction is currently active. */
public static boolean readOnlyTransactionActive() {
return TransactionSynchronizationManager.isActualTransactionActive()
&& TransactionSynchronizationManager.isCurrentTransactionReadOnly();
}
}
@@ -0,0 +1,76 @@
package dev.caskeleton.adapter.outbound.persistence.transaction;
import java.util.Objects;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* The guard a store runs before a write that must join the caller's transaction.
*
* <p>A driven adapter does not open its own transaction around application work (the use case owns
* it through {@code TransactionPort}). Without this check a store called outside one still works —
* each statement commits on its own — and the write it was meant to be atomic with commits
* separately: an outbox row without its business row, a lease without its claim. The outbox, the
* durable operation store, the live-event replay store and owner-safe idempotency each carried a
* copy of the check; this is the one they call.
*/
public final class CallerTransaction {
private CallerTransaction() {}
/**
* Fails unless an actual transaction is active on this thread.
*
* @param operation what is being attempted, for the message ({@code "outbox append"})
* @throws IllegalStateException when no transaction is active
*/
public static void require(String operation) {
Objects.requireNonNull(operation, "operation");
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException(operation + " requires an active caller transaction");
}
}
/**
* Fails unless an actual read-only transaction is active: the guard every streaming read passes
* through (design §27.4, formerly {@code springdata.JpaStreamScope}).
*
* <p>A JPA {@code Stream} is a live cursor: it holds a JDBC {@code ResultSet}, which holds a
* statement, which holds the connection. Without a transaction the cursor closes after the first
* statement and the connection is returned mid-traversal; returned past the transaction boundary
* it leaks the connection. Read-only is not cosmetic either: streaming inside a write transaction
* pins a write connection for the whole traversal.
*
* @param operation what is being attempted, for the message ({@code "streaming"})
* @throws IllegalStateException when no transaction is active, or the active one is a write
*/
public static void requireReadOnly(String operation) {
require(operation);
if (!TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
throw new IllegalStateException(operation + " requires a read-only caller transaction");
}
}
/**
* Fails unless an actual read-write transaction is active and bound to {@code resource}.
*
* <p>The binding check matters when a deployment has more than one data source: a transaction on
* another one satisfies {@link #require} while this store's statements commit on their own.
*
* @param operation what is being attempted, for the message
* @param resource the store's transactional resource (its {@code DataSource}); {@code null} skips
* the binding check
* @throws IllegalStateException naming which condition failed
*/
public static void requireReadWrite(String operation, Object resource) {
require(operation);
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
throw new IllegalStateException(operation + " requires a read-write caller transaction");
}
if (resource != null && !TransactionSynchronizationManager.hasResource(resource)) {
throw new IllegalStateException(
operation
+ " requires a transaction bound to this store's data source; the active"
+ " transaction belongs to another one");
}
}
}
@@ -37,8 +37,6 @@ import dev.caskeleton.application.notification.platform.provider.ReconciliationR
import dev.caskeleton.application.notification.platform.security.NotificationPayloadProtection;
import dev.caskeleton.application.transaction.TransactionPort;
import jakarta.persistence.EntityManagerFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.time.Clock;
import java.time.Duration;
@@ -152,8 +150,7 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest {
projection,
event -> {},
new NoMetrics(),
new SyntheticEventFingerprint(
PostgreSqlNotificationBackgroundPassIntegrationTest::sha256),
new SyntheticEventFingerprint(),
transactions,
clock);
}
@@ -400,17 +397,9 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest {
event);
}
private static byte[] sha256(byte[] input) {
try {
return MessageDigest.getInstance("SHA-256").digest(input);
} catch (NoSuchAlgorithmException impossible) {
throw new IllegalStateException(impossible);
}
}
private static String sha256Hex(String value) {
return java.util.HexFormat.of()
.formatHex(sha256(value.getBytes(java.nio.charset.StandardCharsets.UTF_8)));
.formatHex(dev.caskeleton.shared.digest.Sha256.ofUtf8(value).bytes());
}
/** The notification entities and repositories, wired the way the production scan wires them. */
@@ -95,7 +95,9 @@ class JpaModuleBoundaryTest {
Map.entry(
"h2", Set.of("api", "config", "failure", "idempotency", "outbox", "transaction")),
Map.entry("hibernate", Set.of("api")),
Map.entry("idempotency", Set.of("api", "audit", "failure")),
// `transaction` for the one caller-transaction guard (CallerTransaction) the stores
// share.
Map.entry("idempotency", Set.of("api", "audit", "failure", "transaction")),
Map.entry("lock", Set.of("api")),
Map.entry("migration", Set.of("api")),
Map.entry("observation", Set.of("api")),
@@ -103,12 +105,12 @@ class JpaModuleBoundaryTest {
// logs: the outbox is a delivery queue whose rows are consumed and retired, and this is a
// replay window whose rows are read many times and expire on a clock. Sharing a package
// would put one retention policy on two different lifecycles.
Map.entry("liveevent", Set.of()),
Map.entry("liveevent", Set.of("transaction")),
// Durable long-running operations. No edge to `idempotency` even though the two share a
// fingerprint type: that type comes from application-core, and an edge here would let a
// change to the idempotency store's row shape reach the operation queue.
Map.entry("operation", Set.of()),
Map.entry("outbox", Set.of("api", "audit", "failure")),
Map.entry("operation", Set.of("transaction")),
Map.entry("outbox", Set.of("api", "audit", "failure", "transaction")),
Map.entry(
"postgresql",
Set.of(
@@ -126,7 +128,7 @@ class JpaModuleBoundaryTest {
"transaction")),
Map.entry("querydsl", Set.of("api", "springdata")),
Map.entry("security", Set.of("api")),
Map.entry("springdata", Set.of("api", "hibernate")),
Map.entry("springdata", Set.of("api", "hibernate", "transaction")),
// The startup policy relational persistence runs under — migration sequencing and the
// OSIV/DDL/pool/TLS/vendor guards — which the composition root used to own.
Map.entry("startup", Set.of("api", "config", "hibernate", "migration", "security")),
@@ -0,0 +1,56 @@
package dev.caskeleton.adapter.outbound.persistence;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyRecordJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.operation.DurableOperationJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/**
* Repositories over rows that belong to a tenant, a scope or a relay offer no statement that reads
* or deletes across all of them (review E-6b).
*
* <p>Extending {@code JpaRepository} used to put {@code findAll} and {@code deleteAll} on the one
* interface every caller holds: nothing in the adapters used them, and nothing stopped the next
* caller from doing so.
*/
class ScopedRowRepositoryShapeTest {
private static final Set<String> UNSCOPED_BULK_METHODS =
Set.of(
"findAll",
"findAllById",
"deleteAll",
"deleteAllById",
"deleteAllInBatch",
"deleteAllByIdInBatch",
"count");
@ParameterizedTest
@ValueSource(
classes = {
DurableOperationJpaRepository.class,
IdempotencyRecordJpaRepository.class,
OutboxEventJpaRepository.class
})
@DisplayName("범위 없는 findAll·deleteAll·count 같은 일괄 메서드를 노출하지 않는다")
void repositoryExposesNoUnscopedBulkReadOrDelete(Class<?> repository) {
// when
List<String> exposed =
Arrays.stream(repository.getMethods())
.map(Method::getName)
.filter(UNSCOPED_BULK_METHODS::contains)
.distinct()
.toList();
// then
assertThat(exposed).isEmpty();
}
}
@@ -57,7 +57,7 @@ class OwnerSafeIdempotencyPreconditionTest {
void aClaimWithNoTransactionIsRefused() {
assertThatThrownBy(() -> store.claim(claimRequest()))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("active primary transaction");
.hasMessage("owner-safe idempotency mutation requires an active caller transaction");
verifyNothingWasWritten();
}
@@ -1,44 +0,0 @@
package dev.caskeleton.adapter.outbound.persistence.operation;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
/**
* {@code durable_operation} rows belong to a tenant, so its repository offers no statement that
* reads or deletes across tenants.
*
* <p>Extending {@code JpaRepository} used to put {@code findAll} and {@code deleteAll} on the one
* interface every caller holds: nothing in the adapter used them, and nothing stopped the next
* caller from doing so.
*/
class DurableOperationJpaRepositoryShapeTest {
private static final Set<String> UNSCOPED_BULK_METHODS =
Set.of(
"findAll",
"findAllById",
"deleteAll",
"deleteAllById",
"deleteAllInBatch",
"deleteAllByIdInBatch",
"count");
@Test
void repositoryExposesNoUnscopedBulkReadOrDelete() {
// when
List<String> exposed =
Arrays.stream(DurableOperationJpaRepository.class.getMethods())
.map(Method::getName)
.filter(UNSCOPED_BULK_METHODS::contains)
.distinct()
.toList();
// then
assertThat(exposed).isEmpty();
}
}
@@ -16,7 +16,6 @@ import static org.mockito.Mockito.when;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.application.messaging.event.AggregateIdentity;
import dev.caskeleton.application.messaging.event.AggregateOrder;
import dev.caskeleton.application.messaging.event.EventId;
@@ -25,6 +24,7 @@ import dev.caskeleton.application.outbox.ClaimedOutboxEvent;
import dev.caskeleton.application.outbox.OutboxCompletion;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxLease;
import dev.caskeleton.shared.digest.Sha256;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
@@ -82,7 +82,7 @@ class JpaStreamExecutorTest {
executor.consume(
QUERY, ScrollPolicy.bounded(100, 100), this::trackedStream, Stream::count))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("active transaction");
.hasMessage("streaming requires an active caller transaction");
}
@Test
@@ -95,7 +95,7 @@ class JpaStreamExecutorTest {
executor.consume(
QUERY, ScrollPolicy.bounded(100, 100), this::trackedStream, Stream::count))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("read-only");
.hasMessage("streaming requires a read-only caller transaction");
}
@Test
@@ -0,0 +1,79 @@
package dev.caskeleton.adapter.outbound.persistence.transaction;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.transaction.support.TransactionSynchronizationManager;
class CallerTransactionTest {
private static final Object DATA_SOURCE = new Object();
@AfterEach
void clearTransactionState() {
TransactionSynchronizationManager.setActualTransactionActive(false);
TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
if (TransactionSynchronizationManager.hasResource(DATA_SOURCE)) {
TransactionSynchronizationManager.unbindResource(DATA_SOURCE);
}
}
@Test
void aWriteOutsideACallerTransactionIsRefusedNamingTheOperation() {
// when
Throwable thrown = catchThrowable(() -> CallerTransaction.require("outbox append"));
// then
assertThat(thrown)
.isInstanceOf(IllegalStateException.class)
.hasMessage("outbox append requires an active caller transaction");
}
@Test
void aWriteInsideAReadOnlyTransactionIsRefused() {
// given
TransactionSynchronizationManager.setActualTransactionActive(true);
TransactionSynchronizationManager.setCurrentTransactionReadOnly(true);
// when
Throwable thrown = catchThrowable(() -> CallerTransaction.requireReadWrite("claim", null));
// then
assertThat(thrown)
.isInstanceOf(IllegalStateException.class)
.hasMessage("claim requires a read-write caller transaction");
}
@Test
void aWriteInsideATransactionOnAnotherDataSourceIsRefused() {
// given
TransactionSynchronizationManager.setActualTransactionActive(true);
// when
Throwable thrown =
catchThrowable(() -> CallerTransaction.requireReadWrite("claim", DATA_SOURCE));
// then
assertThat(thrown)
.isInstanceOf(IllegalStateException.class)
.hasMessage(
"claim requires a transaction bound to this store's data source; the active"
+ " transaction belongs to another one");
}
@Test
void aWriteInsideAReadWriteTransactionBoundToTheStoreIsAllowed() {
// given
TransactionSynchronizationManager.setActualTransactionActive(true);
TransactionSynchronizationManager.bindResource(DATA_SOURCE, new Object());
// when
Throwable thrown =
catchThrowable(() -> CallerTransaction.requireReadWrite("claim", DATA_SOURCE));
// then
assertThat(thrown).isNull();
}
}
@@ -4,6 +4,7 @@ import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityGua
import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedEntryPoint;
import dev.caskeleton.adapter.outbound.mongo.api.capability.MongoCapability;
import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
@@ -31,6 +32,8 @@ public final class MongoTenantClientRegistry {
private final java.util.function.Function<String, AutoCloseable> clientFactory;
private final Clock clock;
public MongoTenantClientRegistry(MongoAdvancedCapabilityGuard guard, int maximumActiveClients) {
this(guard, maximumActiveClients, Duration.ofMinutes(10));
}
@@ -40,9 +43,20 @@ public final class MongoTenantClientRegistry {
this(guard, maximumActiveClients, idleEviction, tenant -> () -> {});
}
public MongoTenantClientRegistry(
MongoAdvancedCapabilityGuard guard,
int maximumActiveClients,
Duration idleEviction,
java.util.function.Function<String, AutoCloseable> clientFactory) {
this(guard, maximumActiveClients, idleEviction, clientFactory, Clock.systemUTC());
}
/**
* A registry that owns real clients.
*
* <p>Idle eviction reads {@code clock}; {@link #acquire(String)} used to read {@code
* Instant.now()} beside it.
*
* <p>The factory is called at most once per tenant, inside the map's own computation, so two
* threads asking for the same tenant get one client rather than two — a per-tenant client carries
* a connection pool and monitoring threads, and creating a second one silently doubles both.
@@ -51,9 +65,11 @@ public final class MongoTenantClientRegistry {
MongoAdvancedCapabilityGuard guard,
int maximumActiveClients,
Duration idleEviction,
java.util.function.Function<String, AutoCloseable> clientFactory) {
java.util.function.Function<String, AutoCloseable> clientFactory,
Clock clock) {
Objects.requireNonNull(guard, "guard").require(MongoTenantClientRegistry.class);
this.clientFactory = Objects.requireNonNull(clientFactory, "clientFactory");
this.clock = Objects.requireNonNull(clock, "clock");
this.idleEviction = Objects.requireNonNull(idleEviction, "idleEviction");
if (maximumActiveClients <= 0) {
throw new IllegalArgumentException("the client cap must be positive");
@@ -67,7 +83,7 @@ public final class MongoTenantClientRegistry {
* @throws MongoOperationRejectedException when the cap is reached and nothing can be evicted
*/
public void acquire(String tenantKey) {
acquire(tenantKey, Instant.now());
acquire(tenantKey, clock.instant());
}
/** Acquires a client for a tenant at an explicit instant, so eviction is testable. */

Some files were not shown because too many files have changed in this diff Show More