diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md index c8127597..71cfd8cf 100644 --- a/docs/manual/07-authorization.md +++ b/docs/manual/07-authorization.md @@ -102,9 +102,10 @@ client가 같은 이름의 역할을 정의해도 이 서비스 권한이 되지 | 규칙 | 무엇을 막나 | 어디 | | --- | --- | --- | | bean 금지 | `@SystemInvoked` 유스케이스가 bean이면 기동 실패. 호출자가 `new`로 만들어 혼자 들고 있는 것만 허용한다 | `src/bootstrap/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java` | -| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스와 그 안에 중첩된 클래스만 예외 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | +| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스와 그 안에 중첩된 클래스만 예외. inbound 밖 사용자 전송과 중간 클래스를 거친 길은 아래 「전송 → 시스템 호출자 금지」가 잡는다 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | +| controller 위치 | Spring controller는 `..adapter.inbound..`에만 둔다. 조립 루트나 조립 모듈에 둔 controller는 빌드 실패 | `CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS`(`AdapterBoundaryArchitectureTest`) | | 표시 검사 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·JAX-RS·GraphQL·STOMP mapping과 channel interceptor·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) | -| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등)에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 넷이다. ① 사용자 전송 패키지에 있는 클래스. ② 설정(`@Configuration`·`@AutoConfiguration`) 클래스 자신이 요청 처리기 타입(함수형 `RouterFunction`·`HandlerFunction`, `@RestController`·`@RequestMapping`, servlet·`Filter`·`HandlerInterceptor`, `WebSocketHandler`, GraphQL `DataFetcher`·`RuntimeWiringConfigurer`, gRPC `BindableService`·`ServerInterceptor`, STOMP `ChannelInterceptor`·`ExecutorChannelInterceptor` 등)에 의존하는 것. 요청 처리 코드를 설정에 직접 쓴 경우와 등록만 한 경우가 모두 든다. channel interceptor를 구현한 설정은 프레임마다 자기 메서드가 돈다. interceptor를 `@Bean`으로 내놓는 설정은 route를 등록하는 설정과 같다. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. 처리 코드를 다른 클래스에 두고 메서드 참조로 등록만 해도(`route().GET("/orders", orders::list)`) 설정은 route builder에 의존한다. 클래스 의존으로는 등록과 처리 코드를 가를 수 없어서 둘 다 사용자 전송으로 센다. ③ 설정 안에 중첩된 클래스 가운데 사용자 전송 타입에 의존하는 것. 중첩된 JAX-RS 자원·`@ServerEndpoint`, `configureClientInboundChannel`에서 등록하는 STOMP channel interceptor(익명 클래스여도, STOMP 헤더를 읽지 않아도)도 여기서 잡힌다. 설정용 타입(`WebMvcConfigurer`·`WebSocketConfigurer`·STOMP broker 설정과 그 registry, CORS 설정, `RequestMethod`)에만 의존하는 중첩 클래스는 설정의 일부로 본다. inbound channel의 thread 수만 정하는 설정도 설정용이다. ④ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 사용자 전송 패키지 밖에 둔 channel interceptor가 여기에 든다. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`(설정 필드를 읽는 익명 클래스여도)·CORS 설정·controller bean을 함께 만들어도 걸리지 않는다. 같은 클래스에 "지금 실행" route·data fetcher·interceptor를 쓰거나, route를 등록하거나, 안에 중첩한 endpoint가 작업을 부르면(설정의 메서드를 거쳐 불러도) 걸린다. route·data fetcher·interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) | +| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등), 또는 `@SystemInvoked` 유스케이스 자신에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 타입에는 Spring Security의 요청 경로 확장점(`org.springframework.security.web`·`.config.annotation.web`·`.oauth2.server.resource`·`.oauth2.jwt` 패키지, `AuthenticationProvider`, `AuthorizationManager`)이 든다. 그래서 web 패키지 밖에 둔 JWT converter나 authorization manager도 사용자 전송이다. 사용자 전송 클래스는 넷이다. ① 사용자 전송 패키지에 있는 클래스. ② 설정(`@Configuration`·`@AutoConfiguration`) 클래스 자신이 요청 처리기 타입(함수형 `RouterFunction`·`HandlerFunction`, `@RestController`·`@RequestMapping`, servlet·`Filter`·`HandlerInterceptor`, `WebSocketHandler`, GraphQL `DataFetcher`·`RuntimeWiringConfigurer`, gRPC `BindableService`·`ServerInterceptor`, STOMP `ChannelInterceptor`·`ExecutorChannelInterceptor` 등)에 의존하는 것. 요청 처리 코드를 설정에 직접 쓴 경우와 등록만 한 경우가 모두 든다. 요청 처리기 타입을 구현·상속한 프로젝트 클래스(예: `ChannelInterceptor`를 구현한 interceptor)를 필드·생성자 인자·`new`로 쥔 설정도 든다. `registration.interceptors(frameCounter)`는 클래스 의존으로 `ChannelRegistration`만 남기므로 그 필드의 타입이 설정을 사용자 전송으로 만든다. channel interceptor를 구현한 설정은 프레임마다 자기 메서드가 돈다. interceptor를 `@Bean`으로 내놓는 설정은 route를 등록하는 설정과 같다. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. 처리 코드를 다른 클래스에 두고 메서드 참조로 등록만 해도(`route().GET("/orders", orders::list)`) 설정은 route builder에 의존한다. 클래스 의존으로는 등록과 처리 코드를 가를 수 없어서 둘 다 사용자 전송으로 센다. ③ 설정 안에 중첩된 클래스 가운데 사용자 전송 타입에 의존하는 것. 중첩된 JAX-RS 자원·`@ServerEndpoint`, `configureClientInboundChannel`에서 등록하는 STOMP channel interceptor(익명 클래스여도, STOMP 헤더를 읽지 않아도)도 여기서 잡힌다. 설정용 타입(`WebMvcConfigurer`·`WebSocketConfigurer`·STOMP broker 설정과 그 registry, CORS 설정, `RequestMethod`)에만 의존하는 중첩 클래스는 설정의 일부로 본다. inbound channel의 thread 수만 정하는 설정도 설정용이다. ④ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 사용자 전송 패키지 밖에 둔 channel interceptor가 여기에 든다. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`(설정 필드를 읽는 익명 클래스여도)·CORS 설정·controller bean을 함께 만들어도 걸리지 않는다. 같은 클래스에 "지금 실행" route·data fetcher·interceptor를 쓰거나, route를 등록하거나, 안에 중첩한 endpoint가 작업을 부르면(설정의 메서드를 거쳐 불러도) 걸린다. route·data fetcher·interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) | | 프로젝트 밖 상위 타입 금지 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스(익명·지역 클래스와 예외 제외)는 프로젝트(`dev.caskeleton..`와 소유자의 별도 repo 라이브러리 `dev.cakit..`) 밖의 클래스·인터페이스를 상속·구현하지 않는다. `Runnable`은 누구나 의존하는 타입이라, endpoint가 작업을 `Runnable`로 주입받아도 위 규칙이 다른 사용과 구별하지 못하기 때문이다. 메시지 handler의 `MessageHandler`(메시징 라이브러리 `dev.cakit.messaging`)는 프로젝트 타입으로 쳐서 된다. record·enum은 언어가 붙이는 상위 타입(`Record`, `Enum`과 `Enum`이 구현하는 `Comparable`·`Serializable`·`Constable`)만은 가져도 된다. 그래서 handler 안의 파싱 결과 record, 결과 enum, 독(poison) 메시지 예외, record로 쓴 handler는 통과하고, `Runnable`을 구현한 record는 걸린다 | `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`(같은 파일) | 규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 이 성질은 **패키지** 쪽에서만 온다. diff --git a/src/bootstrap/app/AGENTS.md b/src/bootstrap/app/AGENTS.md index 175c9045..201001a6 100644 --- a/src/bootstrap/app/AGENTS.md +++ b/src/bootstrap/app/AGENTS.md @@ -27,7 +27,7 @@ ## 금지 - 구체적인 업무 정책. -- bootstrap 아래에 직접 쓴 controller, 유스케이스, repository 어댑터, mapper. +- bootstrap 아래에 직접 쓴 controller, 유스케이스, repository 어댑터, mapper. controller는 `CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS`가 빌드에서 막는다. - 업무 로직을 구현하는 설정 클래스. - `application-core`나 `domain-core` 포트를 구현하기. 포트를 구현하는 클래스는 의존성을 어떻게 설정했든 outbound 어댑터이고 `adapter/outbound/*` leaf에 둔다 — diff --git a/src/bootstrap/app/build.gradle b/src/bootstrap/app/build.gradle index e0697407..1ed7df74 100644 --- a/src/bootstrap/app/build.gradle +++ b/src/bootstrap/app/build.gradle @@ -138,6 +138,7 @@ def capabilityProjects = [ ':adapter:outbound:objectstorage', ':adapter:inbound:websocket', ':adapter:inbound:grpc', + ':adapter:inbound:messaging', ':composition:fileserver-platform', ':composition:notification-platform', ] @@ -164,6 +165,7 @@ dependencies { // runtimeOnly project(':adapter:outbound:objectstorage') // 객체 저장소 (S3/로컬) // runtimeOnly project(':adapter:inbound:websocket') // WebSocket (STOMP push) // runtimeOnly project(':adapter:inbound:grpc') // gRPC 서버 + // runtimeOnly project(':adapter:inbound:messaging') // Kafka 소비 inbox (handler가 있을 때만) // runtimeOnly project(':composition:fileserver-platform') // 파일 서버 // runtimeOnly project(':composition:notification-platform') // 알림 (persistence-jpa·persistence-notification을 함께 가져온다) diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java index 10371835..17516da9 100644 --- a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java @@ -406,6 +406,67 @@ class AdapterBoundaryArchitectureTest { + "notification) are peers: none may depend on a sibling; shared outbound code " + "lives in :adapter:outbound:support (Task 7 adapter topology)"); + /** + * The endpoints a user request lands on: a Spring controller wherever it is filed, and a gRPC + * service, which carries no controller annotation (review 2026-11-12). + */ + static final DescribedPredicate ARE_ENDPOINTS = + CleanArchitectureRuleSupport.ARE_CONTROLLERS.or( + DescribedPredicate.describe( + "are gRPC services", type -> type.isAssignableTo("io.grpc.BindableService"))); + + /** + * A domain repository port, an application store port or a read-model query port: the ports a use + * case owns to reach persistence. The generator files the repository port beside its aggregate in + * {@code dev.caskeleton.domain.}, not in a {@code ..repository..} package, so the + * package rule below never saw it. + */ + static final DescribedPredicate ARE_PERSISTENCE_PORTS = + JavaClass.Predicates.resideInAnyPackage("..domain..", "..application..") + .and( + DescribedPredicate.describe( + "named *Repository, *StorePort or *QueryPort", + type -> + type.getName().startsWith("dev.caskeleton.") + && (type.getSimpleName().endsWith("Repository") + || type.getSimpleName().endsWith("StorePort") + || type.getSimpleName().endsWith("QueryPort")))) + .as("domain repository, application store and query ports"); + + /** + * HARD-STOP 2 for the ports themselves: an endpoint reaches persistence only through a use case. + * A controller handed {@code OrderRepository} compiles (web depends on domain-core) and passed + * every rule until 2026-11-12, because the rules below look for repository packages and Spring + * Data types. + */ + @ArchTest + static final ArchRule ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS = + noClasses() + .that(ARE_ENDPOINTS) + .should() + .dependOnClassesThat(ARE_PERSISTENCE_PORTS) + .as( + "ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS: a controller or gRPC service calls a use" + + " case; it does not hold a domain repository port, an application store port" + + " or a query port (AGENTS.md HARD-STOP 2)") + .allowEmptyShould(true); + + /** + * A controller is an inbound adapter, so it lives in one. One filed in the composition root or a + * composition module is reached by no transport rule that names inbound packages (app {@code + * AGENTS.md}: no controller in bootstrap). + */ + @ArchTest + static final ArchRule CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS = + classes() + .that(CleanArchitectureRuleSupport.ARE_CONTROLLERS) + .should() + .resideInAPackage("..adapter.inbound..") + .as( + "CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS: a Spring controller lives in an inbound" + + " adapter package (..adapter.inbound..), not in bootstrap or a composition module") + .allowEmptyShould(true); + @ArchTest static final ArchRule CONTROLLERS_DO_NOT_ACCESS_REPOSITORIES_OR_JPA_ENTITIES = noClasses() diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java index 77ae0111..2bd3a769 100644 --- a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java @@ -478,7 +478,14 @@ class ApplicationBoundaryArchitectureTest { "jakarta.servlet", "jakarta.websocket", "jakarta.ws.rs", - "graphql"); + "graphql", + // Spring Security's request-path extension points: a bearer token resolver, an entry + // point, a JWT converter or decoder, the filter-chain DSL. One filed outside the web + // package depends on no servlet type and was no transport (review 2026-11-12). + "org.springframework.security.web", + "org.springframework.security.config.annotation.web", + "org.springframework.security.oauth2.server.resource", + "org.springframework.security.oauth2.jwt"); /** * The single user-transport types named beside the framework packages. A STOMP client-inbound @@ -491,7 +498,9 @@ class ApplicationBoundaryArchitectureTest { "org.springframework.stereotype.Controller", "org.springframework.messaging.handler.annotation.MessageMapping", "org.springframework.messaging.support.ChannelInterceptor", - "org.springframework.messaging.support.ExecutorChannelInterceptor"); + "org.springframework.messaging.support.ExecutorChannelInterceptor", + "org.springframework.security.authentication.AuthenticationProvider", + "org.springframework.security.authorization.AuthorizationManager"); /** * What makes a class a way in for a user request: a user-transport adapter package, or the @@ -529,7 +538,11 @@ class ApplicationBoundaryArchitectureTest { "org.springframework.graphql.data.method.annotation", "org.springframework.graphql.server", "jakarta.servlet.http", - "graphql.schema"); + "graphql.schema", + "org.springframework.security.web", + "org.springframework.security.config.annotation.web", + "org.springframework.security.oauth2.server.resource", + "org.springframework.security.oauth2.jwt"); /** The single request-handler types {@code ARE_REQUEST_HANDLER_TYPES} names beside packages. */ static final Set REQUEST_HANDLER_TYPE_NAMES = @@ -555,7 +568,9 @@ class ApplicationBoundaryArchitectureTest { "io.grpc.ServerCall", "io.grpc.stub.StreamObserver", "org.springframework.messaging.support.ChannelInterceptor", - "org.springframework.messaging.support.ExecutorChannelInterceptor"); + "org.springframework.messaging.support.ExecutorChannelInterceptor", + "org.springframework.security.authentication.AuthenticationProvider", + "org.springframework.security.authorization.AuthorizationManager"); /** * The framework types request-handling code is written against or registered with: an annotated @@ -622,9 +637,35 @@ class ApplicationBoundaryArchitectureTest { .or(namedAnyOf("transport setup values", TRANSPORT_SETUP_TYPE_NAMES)) .as("transport setup types (configurers, registries, CORS settings)"); - /** What makes a configuration a way in: a request-handler type that is no setup type. */ + /** + * A project class that is a request-handler type by what it extends or implements: an + * interceptor, a filter or a handler the configuration holds by its own class. {@code + * registration.interceptors(frameCounter)} with a field of the interceptor's own class records + * only {@code ChannelRegistration}, a setup type, and the varargs array it builds is no class + * dependency ArchUnit 1.3 records (review 2026-11-12), so the field type has to make the + * configuration a way in by itself. + */ + private static final DescribedPredicate ARE_PROJECT_REQUEST_HANDLERS = + DescribedPredicate.describe( + "project classes that extend or implement a request-handler type", + type -> + type.getName().startsWith("dev.caskeleton.") + && java.util.stream.Stream.concat( + type.getAllRawSuperclasses().stream(), + type.getAllRawInterfaces().stream()) + .anyMatch( + supertype -> + ARE_REQUEST_HANDLER_TYPES.test(supertype) + && !ARE_TRANSPORT_SETUP_TYPES.test(supertype))); + + /** + * What makes a configuration a way in: a request-handler type that is no setup type, or a project + * class that is one. + */ private static final DescribedPredicate MAKE_A_CONFIGURATION_A_WAY_IN = - ARE_REQUEST_HANDLER_TYPES.and(DescribedPredicate.not(ARE_TRANSPORT_SETUP_TYPES)); + ARE_REQUEST_HANDLER_TYPES + .and(DescribedPredicate.not(ARE_TRANSPORT_SETUP_TYPES)) + .or(ARE_PROJECT_REQUEST_HANDLERS); /** What makes a class nested in a configuration a way in: any user-transport type but setup. */ private static final DescribedPredicate MAKE_A_NESTED_CLASS_A_WAY_IN = @@ -746,6 +787,16 @@ class ApplicationBoundaryArchitectureTest { } }; + /** + * A {@link SystemInvoked} use case itself, as a target of the transitive rule below: a user + * transport outside {@code ..adapter.inbound..} (a controller in a composition module, a JWT + * converter) or one that reaches the use case through an unmarked class in between is no + * dependency the direct rule here sees (review 2026-11-12). + */ + private static final DescribedPredicate ARE_SYSTEM_INVOKED_USE_CASES = + DescribedPredicate.describe( + "@SystemInvoked use cases", type -> type.isAnnotatedWith(SystemInvoked.class)); + /** * A {@link SystemInvoked} use case is a write with no permission check, so no user request may * reach it. A user comes in through a transport; the system comes in through a delivery or a tick @@ -823,7 +874,8 @@ class ApplicationBoundaryArchitectureTest { noClasses() .that(ARE_USER_TRANSPORTS) .should() - .transitivelyDependOnClassesThat(ARE_TYPES_A_SYSTEM_CALLER_IS_HANDED_AS) + .transitivelyDependOnClassesThat( + ARE_TYPES_A_SYSTEM_CALLER_IS_HANDED_AS.or(ARE_SYSTEM_INVOKED_USE_CASES)) .as( "USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS: a class a user request comes in " + "through (a user-transport package; a configuration that holds or registers " diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java index b559a106..3c5fc54f 100644 --- a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java @@ -95,9 +95,11 @@ class ArchRuleDiscoveryContractTest { "CONFIGURATION_PROPERTIES_END_WITH_SETTINGS_OR_POLICY", "CONTACT_POINT_VALUES_ARE_IMMUTABLE_RECORDS", "CONTROLLERS_DO_NOT_ACCESS_REPOSITORIES_OR_JPA_ENTITIES", + "CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS", "CONTROLLERS_DO_NOT_RETURN_DOMAIN_OR_ENTITY_TYPES", "CONTROLLER_REQUEST_MAPPINGS_FOLLOW_AIP122", "DOMAIN_CONTEXT_PROPAGATION_PRIMITIVES_STAY_UNSHIPPED", + "ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS", "DOMAIN_ENTITIES_DO_NOT_CARRY_AUDIT_FIELDS", "DOMAIN_EVENTS_ARE_RECORDS", "DOMAIN_EVENTS_ARE_TRANSPORT_FREE", diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java index 5f9be05a..de48d4ea 100644 --- a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java @@ -36,12 +36,14 @@ import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.schedule import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.ScheduledWorkFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemCallerWithNestedEndpointFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemJobLauncherFixture; +import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.DomainRepositoryHoldingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.MessageHandlerInjectingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerInvokingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerRelayingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemInvokedCallingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemJobInterfaceInvokingControllerFixture; +import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.UnmarkedRelayCallingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.outbound.RawExternalResponseFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.outbound.messaging.GenericTypeLeakingAdapterFixture; import dev.caskeleton.bootstrap.architecture.violations.application.BulkWriteWithoutWriteAccessUseCase; @@ -60,11 +62,15 @@ import dev.caskeleton.bootstrap.architecture.violations.configuration.RunNowRout import dev.caskeleton.bootstrap.architecture.violations.domain.AnnotatedPublicNoArgValueObjectFixture; import dev.caskeleton.bootstrap.architecture.violations.domain.JakartaValidationDomainFixture; import dev.caskeleton.bootstrap.architecture.violations.domain.entity.FakeDomainEntity; +import dev.caskeleton.bootstrap.architecture.violations.domain.order.OrderRepository; import dev.caskeleton.bootstrap.architecture.violations.domain.vo.PackagePublicNoArgValueObjectFixture; +import dev.caskeleton.bootstrap.architecture.violations.ops.OpsControllerReachingSystemInvokedFixture; +import dev.caskeleton.bootstrap.architecture.violations.ops.UnmarkedSystemWorkRelayFixture; import dev.caskeleton.bootstrap.architecture.violations.persistence.flyway.ClassicConfigurationFlywayFixture; import dev.caskeleton.bootstrap.architecture.violations.persistence.flyway.ConfigureCallingFlywayFixture; import dev.caskeleton.bootstrap.architecture.violations.persistence.flyway.FluentConfigurationFlywayFixture; import dev.caskeleton.bootstrap.architecture.violations.persistence.flyway.ReferencedConfigurationFlywayFixture; +import dev.caskeleton.bootstrap.architecture.violations.security.AuthorizationManagerReachingSystemCallerFixture; import dev.caskeleton.bootstrap.architecture.violations.streaming.JakartaWebSocketEndpointFixture; import dev.caskeleton.bootstrap.architecture.violations.streaming.SpringWebSocketHandlerFixture; import org.junit.jupiter.api.DisplayName; @@ -840,7 +846,8 @@ class ArchitectureViolationFixtureTest { "RunNowOnFrameConfigurationFixture$RunNowAfterHandling", "RunNowOnFrameInterceptorFixture", "RunNowInterceptingConfigurationFixture", - "InterceptorBesideASystemCallerConfigurationFixture" + "InterceptorBesideASystemCallerConfigurationFixture", + "InterceptorFieldBesideASystemCallerConfigurationFixture" }) void aStompChannelInterceptorThatCallsASystemCallerIsCaughtWhereverItIsKept(String interceptor) { // when @@ -1726,4 +1733,124 @@ class ArchitectureViolationFixtureTest { // then assertThat(result.getFailureReport().getDetails()).isEmpty(); } + + @Test + @DisplayName("inbound 밖에 둔 controller가 @SystemInvoked 유스케이스를 만들어 부르면 전송 규칙과 배치 규칙에 걸린다") + void aControllerOutsideTheInboundPackagesThatRunsASystemInvokedUseCaseIsCaught() { + // given + JavaClasses fixtureOnly = + new ClassFileImporter() + .importClasses( + OpsControllerReachingSystemInvokedFixture.class, SystemInvokedFixtureUseCase.class); + + // when + EvaluationResult transport = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + fixtureOnly); + EvaluationResult placement = + AdapterBoundaryArchitectureTest.CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS.evaluate(fixtureOnly); + + // then + assertThat(transport.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains(OpsControllerReachingSystemInvokedFixture.class.getName()) + .contains(SystemInvokedFixtureUseCase.class.getName())); + assertThat(placement.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains(OpsControllerReachingSystemInvokedFixture.class.getName())); + } + + @Test + @DisplayName("controller가 표시 없는 중간 클래스를 거쳐 @SystemInvoked 유스케이스에 닿아도 걸린다") + void aControllerThatReachesASystemInvokedUseCaseThroughAnUnmarkedClassIsCaught() { + // given + JavaClasses fixtureOnly = + new ClassFileImporter() + .importClasses( + UnmarkedRelayCallingControllerFixture.class, + UnmarkedSystemWorkRelayFixture.class, + SystemInvokedFixtureUseCase.class); + + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + fixtureOnly); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains(UnmarkedRelayCallingControllerFixture.class.getName()) + .contains(SystemInvokedFixtureUseCase.class.getName())); + } + + @Test + @DisplayName("controller가 domain repository 포트를 직접 들면 endpoint 포트 규칙에 걸린다") + void aControllerHoldingADomainRepositoryPortIsCaught() { + // given + JavaClasses fixtureOnly = + new ClassFileImporter() + .importClasses(DomainRepositoryHoldingControllerFixture.class, OrderRepository.class); + + // when + EvaluationResult result = + AdapterBoundaryArchitectureTest.ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS.evaluate( + fixtureOnly); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains(DomainRepositoryHoldingControllerFixture.class.getName()) + .contains(OrderRepository.class.getName())); + } + + @Test + @DisplayName("포트를 들지 않고 inbound 패키지에 있는 controller는 endpoint 포트 규칙과 배치 규칙을 통과한다") + void anInboundControllerHoldingNoPersistencePortPasses() { + // given + JavaClasses fixtureOnly = new ClassFileImporter().importClasses(PingControllerFixture.class); + + // when + EvaluationResult ports = + AdapterBoundaryArchitectureTest.ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS.evaluate( + fixtureOnly); + EvaluationResult placement = + AdapterBoundaryArchitectureTest.CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS.evaluate(fixtureOnly); + + // then + assertThat(ports.getFailureReport().getDetails()).isEmpty(); + assertThat(placement.getFailureReport().getDetails()).isEmpty(); + } + + @Test + @DisplayName("web 패키지 밖의 Spring Security AuthorizationManager가 시스템 호출자에 닿으면 걸린다") + void aSecurityExtensionPointOutsideTheWebPackageThatReachesASystemCallerIsCaught() { + // given + JavaClasses fixtureOnly = + new ClassFileImporter() + .importClasses( + AuthorizationManagerReachingSystemCallerFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + fixtureOnly); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains(AuthorizationManagerReachingSystemCallerFixture.class.getName()) + .contains(SystemCallerHandlerFixture.class.getName())); + } } diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/DomainRepositoryHoldingControllerFixture.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/DomainRepositoryHoldingControllerFixture.java new file mode 100644 index 00000000..70a7dda2 --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/DomainRepositoryHoldingControllerFixture.java @@ -0,0 +1,26 @@ +package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller; + +import dev.caskeleton.bootstrap.architecture.violations.domain.order.OrderRepository; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * Negative fixture for {@code ENDPOINTS_DO_NOT_HOLD_PERSISTENCE_PORTS}: a controller handed the + * domain repository port instead of a use case (HARD-STOP 2). The repository port lives in a {@code + * ..domain..} package, not a {@code ..repository..} one, so the package rule missed it (review + * 2026-11-12). + */ +@RestController +public class DomainRepositoryHoldingControllerFixture { + + private final OrderRepository orders; + + public DomainRepositoryHoldingControllerFixture(OrderRepository orders) { + this.orders = orders; + } + + @PostMapping("/orders") + public void create() { + orders.save("order"); + } +} diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/UnmarkedRelayCallingControllerFixture.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/UnmarkedRelayCallingControllerFixture.java new file mode 100644 index 00000000..2684cace --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/UnmarkedRelayCallingControllerFixture.java @@ -0,0 +1,16 @@ +package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller; + +import dev.caskeleton.bootstrap.architecture.violations.ops.UnmarkedSystemWorkRelayFixture; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a controller that + * reaches a {@code @SystemInvoked} use case through a plain class in between (review 2026-11-12). + */ +public class UnmarkedRelayCallingControllerFixture { + + private final UnmarkedSystemWorkRelayFixture relay = new UnmarkedSystemWorkRelayFixture(); + + public void trigger() { + relay.run(); + } +} diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/InterceptorFieldBesideASystemCallerConfigurationFixture.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/InterceptorFieldBesideASystemCallerConfigurationFixture.java new file mode 100644 index 00000000..69e16857 --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/InterceptorFieldBesideASystemCallerConfigurationFixture.java @@ -0,0 +1,33 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.stomp; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.FrameCountingInterceptorFixture; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.simp.config.ChannelRegistration; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: the configuration + * registers an interceptor held in a field of the interceptor's own class and builds the message + * handler. {@code registration.interceptors(frameCounter)} records only {@code + * ChannelRegistration}, a setup type, and the varargs array is no dependency ArchUnit records, so + * the configuration was no way in (review 2026-11-12). The interceptor's own class makes it one. + */ +@Configuration(proxyBeanMethods = false) +public class InterceptorFieldBesideASystemCallerConfigurationFixture + implements WebSocketMessageBrokerConfigurer { + + private final FrameCountingInterceptorFixture frameCounter = + new FrameCountingInterceptorFixture(); + + @Override + public void configureClientInboundChannel(ChannelRegistration registration) { + registration.interceptors(frameCounter); + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/domain/order/OrderRepository.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/domain/order/OrderRepository.java new file mode 100644 index 00000000..6bbbdd4b --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/domain/order/OrderRepository.java @@ -0,0 +1,10 @@ +package dev.caskeleton.bootstrap.architecture.violations.domain.order; + +/** + * A domain repository port where the generator files one, beside its aggregate. Not a violation on + * its own: {@code DomainRepositoryHoldingControllerFixture} holds it. + */ +public interface OrderRepository { + + void save(String order); +} diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/OpsControllerReachingSystemInvokedFixture.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/OpsControllerReachingSystemInvokedFixture.java new file mode 100644 index 00000000..2de444cf --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/OpsControllerReachingSystemInvokedFixture.java @@ -0,0 +1,20 @@ +package dev.caskeleton.bootstrap.architecture.violations.ops; + +import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} and {@code + * CONTROLLERS_LIVE_IN_INBOUND_ADAPTERS}: an operations endpoint filed outside {@code + * ..adapter.inbound..}, as a composition module might, that builds a {@code @SystemInvoked} use + * case and runs it. The direct rule reads inbound packages only, so it passed (review 2026-11-12). + */ +@RestController +public class OpsControllerReachingSystemInvokedFixture { + + @PostMapping("/ops/run") + public void run() { + new SystemInvokedFixtureUseCase().handle(); + } +} diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/UnmarkedSystemWorkRelayFixture.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/UnmarkedSystemWorkRelayFixture.java new file mode 100644 index 00000000..ddf5e240 --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/ops/UnmarkedSystemWorkRelayFixture.java @@ -0,0 +1,17 @@ +package dev.caskeleton.bootstrap.architecture.violations.ops; + +import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; + +/** + * An unmarked class between a user transport and a {@code @SystemInvoked} use case: it is no + * {@code @SystemCaller}, so a controller that calls it named neither the use case nor a system + * caller (review 2026-11-12). + */ +public final class UnmarkedSystemWorkRelayFixture { + + private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase(); + + public void run() { + useCase.handle(); + } +} diff --git a/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/security/AuthorizationManagerReachingSystemCallerFixture.java b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/security/AuthorizationManagerReachingSystemCallerFixture.java new file mode 100644 index 00000000..37660282 --- /dev/null +++ b/src/bootstrap/app/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/security/AuthorizationManagerReachingSystemCallerFixture.java @@ -0,0 +1,26 @@ +package dev.caskeleton.bootstrap.architecture.violations.security; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import java.util.function.Supplier; +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.authorization.AuthorizationManager; +import org.springframework.security.authorization.AuthorizationResult; +import org.springframework.security.core.Authentication; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a method-security + * authorization manager filed outside the web package runs on every request it guards, but names no + * servlet type, so it was no transport (review 2026-11-12). + */ +public final class AuthorizationManagerReachingSystemCallerFixture + implements AuthorizationManager { + + private final SystemCallerHandlerFixture handler = new SystemCallerHandlerFixture(); + + @Override + public AuthorizationResult authorize( + Supplier authentication, Object object) { + handler.handle(); + return new AuthorizationDecision(true); + } +}