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
+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"));
}
}