diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md index c1f0bd40..68bedd30 100644 --- a/docs/manual/07-authorization.md +++ b/docs/manual/07-authorization.md @@ -102,15 +102,19 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re | bean 금지 | `@SystemInvoked` 유스케이스가 bean이면 기동 실패. 호출자가 `new`로 만들어 혼자 들고 있는 것만 허용한다 | `src/composition/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`) | | 표시 검사 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·JAX-RS·GraphQL·STOMP mapping·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` 등)에 의존하는 것. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. ③ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`(설정 필드를 읽는 익명 클래스여도)·controller bean을 함께 만들어도 걸리지 않지만, 같은 클래스에 "지금 실행" route·data fetcher·interceptor를 직접 쓰면 걸린다. 요청 처리 코드는 handler를 등록하는 설정과 다른 클래스에 둔다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) | +| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등)에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 넷이다. ① 사용자 전송 패키지에 있는 클래스. ② 설정(`@Configuration`·`@AutoConfiguration`) 클래스 자신이 요청 처리기 타입(함수형 `RouterFunction`·`HandlerFunction`, `@RestController`·`@RequestMapping`, servlet·`Filter`·`HandlerInterceptor`, `WebSocketHandler`, GraphQL `DataFetcher`·`RuntimeWiringConfigurer`, gRPC `BindableService`·`ServerInterceptor` 등)에 의존하는 것. 요청 처리 코드를 설정에 직접 쓴 경우와 등록만 한 경우가 모두 든다. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. 처리 코드를 다른 클래스에 두고 메서드 참조로 등록만 해도(`route().GET("/orders", orders::list)`) 설정은 route builder에 의존한다. 클래스 의존으로는 등록과 처리 코드를 가를 수 없어서 둘 다 사용자 전송으로 센다. ③ 설정 안에 중첩된 클래스 가운데 사용자 전송 타입에 의존하는 것. 중첩된 JAX-RS 자원·`@ServerEndpoint`도 여기서 잡힌다. 설정용 타입(`WebMvcConfigurer`·`WebSocketConfigurer`·STOMP broker 설정과 그 registry, CORS 설정, `RequestMethod`)에만 의존하는 중첩 클래스는 설정의 일부로 본다. ④ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 그래서 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..`) 밖의 클래스·인터페이스를 상속·구현하지 않는다. `Runnable`은 누구나 의존하는 타입이라, endpoint가 작업을 `Runnable`로 주입받아도 위 규칙이 다른 사용과 구별하지 못하기 때문이다. 메시지 handler의 `MessageHandler`는 프로젝트 타입이라 된다. record·enum은 언어가 붙이는 상위 타입(`Record`, `Enum`과 `Enum`이 구현하는 `Comparable`·`Serializable`·`Constable`)만은 가져도 된다. 그래서 handler 안의 파싱 결과 record, 결과 enum, 독(poison) 메시지 예외, record로 쓴 handler는 통과하고, `Runnable`을 구현한 record는 걸린다 | `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`(같은 파일) | 규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 이 성질은 **패키지** 쪽에서만 온다. 패키지는 허용 목록이라, 나중에 새 전송 패키지가 생겨도 따로 고치지 않아도 막힌다. 사용자 전송 **타입** 쪽은 나열 목록이다(`ARE_USER_TRANSPORT_TYPES`). 시스템 패키지 안에 놓인 endpoint를 알아보는 데 쓰는 목록이라, 목록에 없는 전송 라이브러리로 만든 endpoint는 전송으로 보이지 않는다. 새 전송 라이브러리를 -들이면 그 패키지를 이 목록에 더한다. 설정 안의 요청 처리 코드를 알아보는 요청 처리기 타입 -(`ARE_REQUEST_HANDLER_TYPES`)도 나열 목록이라, 새 전송 라이브러리의 handler 타입을 함께 더한다. +들이면 그 패키지를 이 목록에 더한다. 설정 클래스 자신을 판정하는 요청 처리기 타입 +(`ARE_REQUEST_HANDLER_TYPES`)도 나열 목록이라, 새 전송 라이브러리의 handler 타입을 함께 더한다. 요청 처리기 +타입은 모두 사용자 전송 타입이어야 하고, 설정용 타입(`ARE_TRANSPORT_SETUP_TYPES`)은 요청 처리기 타입을 덮지 +않아야 한다. `UserTransportTypeListsTest`가 둘을 검사한다. 설정용 타입 목록에 없는 configurer 타입을 쓰는 중첩 +클래스는 사용자 전송으로 읽혀, 설정 필드를 읽으면 빌드가 실패한다. 그 타입이 요청마다 도는 코드가 아니라 기동 때 +한 번 도는 설정용 타입이면 설정용 타입 목록에 더한다. 쓰기 유스케이스의 권한 선언 검사(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`) 실패를 끄려고 이 표시를 쓰지 않는다. 사용자가 부르는 쓰기라면 권한을 선언하고 역할에 매핑한다. 같은 쓰기를 사용자도 시스템도 부르면 유스케이스를 둘로 나눈다 @@ -123,10 +127,11 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re - 이름이나 `Object`로 bean을 찾는 코드: `getBean("nightlyJob")`, `Map` 주입 뒤 reflection 호출. - 설정이 사용자 전송에 작업을 감싼 함수를 넘기는 코드: `new RunNowController(job::run)`처럼 controller는 - `Runnable`만 받는다. 의존은 설정 → 작업 쪽에만 있고, 요청 처리 코드를 직접 갖지 않은 설정은 사용자 전송이 + `Runnable`만 받는다. 의존은 설정 → 작업 쪽에만 있고, 요청 처리기 타입에 의존하지 않는 설정은 사용자 전송이 아니다. -- 설정 안의 요청 처리 코드가 요청 처리기 타입 목록(`ARE_REQUEST_HANDLER_TYPES`)에 없는 타입으로 쓰인 경우. - 목록 방식이라, 목록에 없는 endpoint 타입으로 설정 안에 쓴 endpoint는 사용자 전송으로 보이지 않는다. +- 설정 클래스 자신에 쓴 요청 처리 코드가 요청 처리기 타입 목록(`ARE_REQUEST_HANDLER_TYPES`)에 없는 타입으로 + 쓰인 경우. 목록 방식이라, 목록에 없는 endpoint 타입으로 설정 클래스에 직접 쓴 endpoint는 사용자 전송으로 + 보이지 않는다. 설정 안에 중첩한 클래스는 더 넓은 사용자 전송 타입 목록으로 보므로 여기에 들지 않는다. 이 길을 막는 것은 ArchUnit 규칙이 아니라 다음 셋이다. @@ -137,7 +142,7 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re 못 한다. 예약 작업은 서비스 자기 leaf에 있어서 같은 leaf의 controller와 사이에는 이 게이트가 없다. 그래서 위 길들은 사실상 controller와 작업이 같은 leaf에 있을 때, 또는 둘을 모두 보는 설정에서 생긴다. - 리뷰: 설정에서 시스템 호출자를 함수로 감싸 다른 bean에 넘기거나, 사용자 전송이 bean을 이름으로 찾거나, 목록에 - 없는 타입으로 설정 안에 endpoint를 쓰는 코드는 리뷰에서 거절한다. 사용자도 같은 일을 시켜야 하면 위 문단대로 + 없는 타입으로 설정 클래스에 endpoint를 쓰는 코드는 리뷰에서 거절한다. 사용자도 같은 일을 시켜야 하면 위 문단대로 사용자용 유스케이스를 따로 만든다. ## web 없는 조립 diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index d3c1e855..899423aa 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -75,7 +75,7 @@ | B-13 | `app.security.*` strict 바인딩: 접두어 아래 오타 키, 또는 설정·placeholder 어디에도 쓰이지 않는 `APP_SECURITY_*` 환경 변수가 기동을 막는다 | 기동 실패(메시지는 `StrictSettingsBinder`가 키 이름을 담아 냄, 정확한 문구 확인 못 함) | 쓰지 않는 `APP_SECURITY_*` 변수를 지운다 | `5786126c` · `SecuritySettings.bind`, `src/adapter/outbound/support/.../StrictSettingsBinder.java` | | B-14 | prod 프로필에서 `fixture-`로 시작하는 비밀값을 거부(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/` 참조 대상. `HOSTNAME`·앱 이름 같은 비밀 아닌 값은 보지 않는다 — RR2-04-01). Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl` | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로. Redis SDK admin 계정(`RedisAccountContribution`)을 조립했다면 그 변수를 `static` `RequiredProductionSecrets` bean으로도 낸다(코드에 든 참조는 검사가 보지 않는다, RR3-04-03, `src/adapter/outbound/redis-sdk/README.md`) | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` | | B-15 | 기동 rule이 모든 singleton보다 먼저 돈다(`StartupRuleRunner`가 `BeanFactoryPostProcessor`). `StartupRule`과 `RequiredProductionSecrets` bean은 `static @Bean`이고 `Environment`, bean factory, static 무인자 `RequiredProductionSecrets`의 `ObjectProvider`만 받아야 한다. 두 타입의 클래스는 `@Value`·`@Autowired`·`@Inject`·`@Resource` 멤버, `@PostConstruct`·`@PreDestroy`, `@ConfigurationProperties`를 가질 수 없다(post-processor보다 먼저 만들어져 비어 있게 된다, RR2-04-03) | non-static `@Bean`이거나 다른 bean을 받으면 기동 실패 `startup rule or secret list '<이름>' created [] while creating it ... Declare the rule with a static @Bean method ...`, 위 멤버가 있으면 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one: [...]`(둘 다 exit 78, 둘 다 모든 프로필. runner가 rule과 비밀 목록을 프로필과 무관하게 먼저 만들어, 인터페이스 타입 `@Bean`이 돌려준 실제 클래스까지 본다, RR3-04-01) | rule 선언을 `static`으로, 인자를 위 셋으로 줄인다. 값은 `violations(Environment)`가 받는 `Environment`에서 읽는다. 다른 bean이 필요한 검사는 rule이 아니라 일반 bean으로 둔다 | `34565130`, `bbe944bd` · `src/adapter/outbound/support/.../startup/StartupRule.java`, `StartupRuleRunner.java` | -| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`, `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르거나, 사용자 전송(controller 등)이 `@SystemCaller` bean을 직접·중간 클래스를 거쳐·그 작업이 구현하는 프로젝트 인터페이스로 부르면 architectureTest 실패. `@SystemCaller` 클래스가 `Runnable`·`ApplicationRunner` 같은 프로젝트 밖 타입을 구현·상속해도 실패. 설정(`@Configuration`)은 웹 bean과 handler bean을 함께 등록해도 사용자 전송으로 세지 않지만, 요청 처리 코드(함수형 route·data fetcher·interceptor 같은 요청 처리기 타입)를 그 설정이나 그 안에 중첩된 클래스에 직접 쓰면 사용자 전송으로 센다. record·enum이 언어로 받는 상위 타입(`Record`·`Enum` 등)과 예외 클래스는 프로젝트 밖 상위 타입으로 세지 않는다 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 스케줄러에 넘기거나, 메시지 handler·예약 작업이면 그 클래스에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다. 예약 작업은 서비스 leaf의 `..adapter.inbound.scheduler..` 패키지에 둔다. 세 경로와 두는 곳은 매뉴얼 07장 「시스템이 부르는 쓰기」(handler 작업 순서는 09장 「소비」 4단계). "지금 실행" endpoint가 필요하면 `@RequiresPermission` 유스케이스를 따로 만든다. 작업을 task scheduler에 직접 등록하던 코드는 작업이 `Runnable`을 구현하는 대신 등록하는 곳에서 `job::run`을 넘긴다. 요청 처리 코드는 handler를 등록하는 설정과 다른 클래스에 둔다. `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd`, r9 · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` | +| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`, `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르거나, 사용자 전송(controller 등)이 `@SystemCaller` bean을 직접·중간 클래스를 거쳐·그 작업이 구현하는 프로젝트 인터페이스로 부르면 architectureTest 실패. `@SystemCaller` 클래스가 `Runnable`·`ApplicationRunner` 같은 프로젝트 밖 타입을 구현·상속해도 실패. 설정(`@Configuration`)은 웹 bean(`WebMvcConfigurer`·CORS 설정·controller bean)과 handler bean을 함께 등록해도 사용자 전송으로 세지 않지만, 요청 처리기 타입(함수형 route·data fetcher·interceptor)에 의존하면 사용자 전송으로 센다. 처리 코드를 설정에 직접 쓰든, 다른 클래스의 메서드를 참조해 등록만 하든 같다. 설정 안에 중첩된 클래스는 설정용 타입(configurer·registry·CORS 설정·`RequestMethod`)에만 의존할 때를 빼고 다른 클래스처럼 사용자 전송 타입으로 판정한다(중첩된 JAX-RS 자원·`@ServerEndpoint`도 잡힌다). record·enum이 언어로 받는 상위 타입(`Record`·`Enum` 등)과 예외 클래스는 프로젝트 밖 상위 타입으로 세지 않는다 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 스케줄러에 넘기거나, 메시지 handler·예약 작업이면 그 클래스에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다. 예약 작업은 서비스 leaf의 `..adapter.inbound.scheduler..` 패키지에 둔다. 세 경로와 두는 곳은 매뉴얼 07장 「시스템이 부르는 쓰기」(handler 작업 순서는 09장 「소비」 4단계). "지금 실행" endpoint가 필요하면 `@RequiresPermission` 유스케이스를 따로 만든다. 작업을 task scheduler에 직접 등록하던 코드는 작업이 `Runnable`을 구현하는 대신 등록하는 곳에서 `job::run`을 넘긴다. route·data fetcher·interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다. `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd`, r9 · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` | | B-17 | `IntegrationEventDraft`: `eventId`·`causationId`는 소문자 UUIDv7만. ArchUnit `INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`: `new IntegrationEventDraft<>(...)` 금지, `IntegrationEventDrafts.draft(...)`만 | 이벤트를 만드는 쓰기 요청이 `IllegalArgumentException: eventId must be a canonical lower-case UUIDv7...`로 실패. architectureTest 실패 | event id를 UUIDv7로 만든다(예: sample `UuidOutboxEventIdFactory`가 `UuidCreator.getTimeOrderedEpochPlus1()`). draft는 헬퍼로 만든다. tenant가 없는 이벤트는 `IntegrationEventDrafts.SINGLE_TENANT_SCOPE`(`global`) | `1400dc15`, `bbe944bd` · `src/application-core/.../messaging/event/IntegrationEventDraft.java`, `IntegrationEventDrafts.java` | | B-18 | `MessageHandler.schemaVersions()`(vendored `messaging-core-api`, default `{v1}`): 소비자 decode 목록을 handler 선언으로 만든다. 같은 (메시지 타입, 버전)에 다른 payload class를 선언하면 실패 | 컴파일은 된다. v1이 아닌 메시지는 `SCHEMA_VERSION_NOT_REGISTERED`로 거부. 발행 등록(`MessageContracts`)과 class가 다르면 기동 실패 `MESSAGING_CONTRACT_CONFLICT` | v2 이상을 읽는 handler는 `schemaVersions()`를 override한다. 소비 타입을 `MessageContracts`에 따로 등록하던 코드는 지운다 | `5786126c` · `src/messaging/messaging-core-api/.../delivery/MessageHandler.java`, `messaging-spring-boot-starter/.../MessageContracts.java` | | B-19 | `APP_FLYWAY_ENABLED`가 모든 프로필에서 읽힌다. dev·prod 프로필 파일의 `spring.flyway.enabled: true`·`app.persistence.vendor` 고정값을 지우고 persistence-jpa `config/module-defaults`가 `${APP_FLYWAY_ENABLED:true}`를 싣는다 | dev·prod 환경에 `APP_FLYWAY_ENABLED=false`가 있으면 전에는 무시됐지만 이제 기동 때 마이그레이션이 안 돈다 | dev·prod 환경 값을 확인한다. 자기 `application-dev.yml`·`application-prod.yml`에 같은 고정값을 다시 넣지 않는다 | `5786126c` · `src/app-bootstrap/src/main/resources/application-{dev,prod}.yml`, `src/adapter/outbound/persistence-jpa/.../module-defaults/persistence-jpa.yml` | diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java index 24e4f6ef..2e51e6e1 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java @@ -459,43 +459,70 @@ class ApplicationBoundaryArchitectureTest { }; /** - * What makes a class a way in for a user request: a user-transport adapter package or the - * framework types an endpoint is built from. {@code org.springframework.messaging} is named only - * for STOMP ({@code simp}, {@code @MessageMapping}): a broker listener's {@code @Payload} and - * {@code @Header} live beside them and are a system consumer's, not a user's. + * The framework packages user-transport endpoints are built from, each with its subpackages. + * {@code org.springframework.messaging} is named only for STOMP ({@code simp}, {@code + * MessageMapping} in {@link #USER_TRANSPORT_TYPE_NAMES}): a broker listener's {@code @Payload} + * and {@code @Header} live beside them and are a system consumer's, not a user's. * - *

The framework half is a list, unlike the package allowlist above: a transport library - * missing from it is not recognised as one. A service that brings in a new transport library adds - * its packages here (review 2026-11-04 RR3-01-02). + *

This is a list, unlike the package allowlist above: a transport library missing from it is + * not recognised as one. A service that brings in a new transport library adds its packages here + * (review 2026-11-04 RR3-01-02). + */ + static final List USER_TRANSPORT_FRAMEWORK_PACKAGES = + List.of( + "org.springframework.web", + "org.springframework.graphql", + "org.springframework.messaging.simp", + "io.grpc", + "jakarta.servlet", + "jakarta.websocket", + "jakarta.ws.rs", + "graphql"); + + /** The single user-transport types named beside the framework packages. */ + static final Set USER_TRANSPORT_TYPE_NAMES = + Set.of( + "org.springframework.stereotype.Controller", + "org.springframework.messaging.handler.annotation.MessageMapping"); + + /** + * What makes a class a way in for a user request: a user-transport adapter package, or the + * framework types an endpoint is built from ({@link #USER_TRANSPORT_FRAMEWORK_PACKAGES}, {@link + * #USER_TRANSPORT_TYPE_NAMES}). */ private static final DescribedPredicate ARE_USER_TRANSPORT_TYPES = JavaClass.Predicates.resideInAnyPackage( "..adapter.inbound.web..", "..adapter.inbound.graphql..", "..adapter.inbound.grpc..", - "..adapter.inbound.websocket..", - "org.springframework.web..", - "org.springframework.graphql..", - "org.springframework.messaging.simp..", - "io.grpc..", - "jakarta.servlet..", - "jakarta.websocket..", - "jakarta.ws.rs..", - "graphql..") + "..adapter.inbound.websocket..") .or( - com.tngtech.archunit.core.domain.properties.HasName.Predicates.name( - "org.springframework.stereotype.Controller")) - .or( - com.tngtech.archunit.core.domain.properties.HasName.Predicates.name( - "org.springframework.messaging.handler.annotation.MessageMapping")) + JavaClass.Predicates.resideInAnyPackage( + withSubpackages(USER_TRANSPORT_FRAMEWORK_PACKAGES))) + .or(namedAnyOf("user-transport annotations", USER_TRANSPORT_TYPE_NAMES)) .as("user-transport types (web, JAX-RS, GraphQL, gRPC, WebSocket/STOMP endpoints)"); /** Spring's configuration stereotype, which {@code @AutoConfiguration} carries as well. */ private static final String CONFIGURATION = "org.springframework.context.annotation.Configuration"; + /** + * The packages, with their subpackages, of the framework types request-handling code is written + * against or registered with. {@link #ARE_REQUEST_HANDLER_TYPES} names them. + */ + static final List REQUEST_HANDLER_PACKAGES = + List.of( + "org.springframework.web.bind.annotation", + "org.springframework.web.servlet.function", + "org.springframework.web.reactive.function.server", + "org.springframework.web.socket.handler", + "org.springframework.graphql.data.method.annotation", + "org.springframework.graphql.server", + "jakarta.servlet.http", + "graphql.schema"); + /** The single request-handler types {@code ARE_REQUEST_HANDLER_TYPES} names beside packages. */ - private static final Set REQUEST_HANDLER_TYPE_NAMES = + static final Set REQUEST_HANDLER_TYPE_NAMES = Set.of( "org.springframework.stereotype.Controller", "org.springframework.messaging.handler.annotation.MessageMapping", @@ -519,74 +546,134 @@ class ApplicationBoundaryArchitectureTest { "io.grpc.stub.StreamObserver"); /** - * The framework types request-handling code is written against: an annotated controller, a - * functional route or handler function, a servlet, filter or handler interceptor, a WebSocket - * handler, a GraphQL data fetcher, runtime wiring or request interceptor, a gRPC service, call - * handler or server interceptor. A configuration names one only when request-handling code is in - * it — a route or data fetcher written as a lambda compiles into a method of the configuration - * itself — and then the configuration is an endpoint (review 2026-11-05 RR6-01-01). The types a - * configuration names to set a transport up — {@code WebMvcConfigurer}, {@code CorsRegistry}, the - * controller beans it builds — are not here (RR4-01-02). + * The framework types request-handling code is written against or registered with: an annotated + * controller, a functional route or handler function, a servlet, filter or handler interceptor, a + * WebSocket handler, a GraphQL data fetcher, runtime wiring or request interceptor, a gRPC + * service, call handler or server interceptor. A configuration that names one holds or registers + * request-handling code, and then the configuration is an endpoint: a route or data fetcher + * written as a lambda compiles into a method of the configuration itself (review 2026-11-05 + * RR6-01-01), and a route registered by method reference names the same route builder although + * its handling code is in another class (review 2026-11-06 RR7-01-02). Class dependencies cannot + * tell that registration from handling code, so routes are registered in a configuration apart + * from the one that builds a system caller. The types a configuration names to set a transport up + * — {@link #ARE_TRANSPORT_SETUP_TYPES}, the controller beans it builds — do not count + * (RR4-01-02). * - *

Like the type list above, this is a list: a request-handler type missing from it is not - * recognised in a configuration (manual 07 「규칙이 못 보는 길」). + *

Only a configuration itself is read with this list; a class nested in one is read with the + * wider user-transport list (RR7-01-01). Like that list, this one is a list: a request-handler + * type missing from it is not recognised in a configuration (manual 07 「규칙이 못 보는 길」). Every entry + * is a user-transport type too, so an endpoint moved from a configuration into a class nested in + * it is still caught ({@code UserTransportTypeListsTest}). */ private static final DescribedPredicate ARE_REQUEST_HANDLER_TYPES = - JavaClass.Predicates.resideInAnyPackage( - "org.springframework.web.bind.annotation..", - "org.springframework.web.servlet.function..", - "org.springframework.web.reactive.function.server..", - "org.springframework.web.socket.handler..", - "org.springframework.graphql.data.method.annotation..", - "org.springframework.graphql.server..", - "jakarta.servlet.http..", - "graphql.schema..") - .or( - DescribedPredicate.describe( - "request-handler interfaces", - type -> REQUEST_HANDLER_TYPE_NAMES.contains(type.getName()))) + JavaClass.Predicates.resideInAnyPackage(withSubpackages(REQUEST_HANDLER_PACKAGES)) + .or(namedAnyOf("request-handler interfaces", REQUEST_HANDLER_TYPE_NAMES)) .as("request-handler types (controllers, routes, servlets, filters, interceptors, ...)"); + /** + * The packages, with their subpackages, of the types a configuration names to set a transport up + * rather than to handle a request: Spring MVC's, WebFlux's and WebSocket's configurers and + * registries, the STOMP broker registry, and CORS settings. Their code runs while the application + * starts. A class that implements one of them for a request — a CORS source, a CORS processor — + * takes the request as a parameter, and that type counts. + */ + static final List TRANSPORT_SETUP_PACKAGES = + List.of( + "org.springframework.web.servlet.config.annotation", + "org.springframework.web.reactive.config", + "org.springframework.web.socket.config.annotation", + "org.springframework.messaging.simp.config", + "org.springframework.web.cors"); + + /** + * The single setup types: the HTTP method values a CORS mapping lists, which live among the + * controller annotations (review 2026-11-06 RR7-01-02). + */ + static final Set TRANSPORT_SETUP_TYPE_NAMES = + Set.of("org.springframework.web.bind.annotation.RequestMethod"); + + /** + * The types a configuration names to set a transport up: they make neither a configuration nor a + * class nested in one a way in. An anonymous {@code WebMvcConfigurer} that reads the + * configuration's field is part of the configuration (review 2026-11-05 RR6-01-02). + * + *

A setup type missing from here fails the build: the configurer naming it is read as a + * transport. A request-handler type added here would hide an endpoint instead, so no entry may + * cover one ({@code UserTransportTypeListsTest}). + */ + private static final DescribedPredicate ARE_TRANSPORT_SETUP_TYPES = + JavaClass.Predicates.resideInAnyPackage(withSubpackages(TRANSPORT_SETUP_PACKAGES)) + .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. */ + private static final DescribedPredicate MAKE_A_CONFIGURATION_A_WAY_IN = + ARE_REQUEST_HANDLER_TYPES.and(DescribedPredicate.not(ARE_TRANSPORT_SETUP_TYPES)); + + /** 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 = + ARE_USER_TRANSPORT_TYPES.and(DescribedPredicate.not(ARE_TRANSPORT_SETUP_TYPES)); + /** * A class a user request comes in through: it lives in a user-transport package; or it is a - * configuration, or nested in one, that is built from a request-handler type; or it is any other - * class built from a user-transport type. + * configuration built from a request-handler type; or it is nested in a configuration and built + * from a user-transport type other than a setup type; or it is any other class built from a + * user-transport type. * *

A configuration is the composition root, and naming a web type does not make it a way in: a * feature's configuration registers its message handler beside a {@code WebMvcConfigurer} or its * controller without any request passing through it (review 2026-11-04 RR4-01-02). A controller * it builds is checked itself, by its package or its own transport types. What does make it a way - * in is request-handling code written in it: a functional route or a data fetcher is a lambda, - * compiled into the configuration's own method, so the configuration that holds one is the - * endpoint (review 2026-11-05 RR6-01-01). A class nested in a configuration — an anonymous {@code - * WebMvcConfigurer} reading the configuration's field — is read the same way, request handlers - * nested there included (RR6-01-02). + * in is request-handling code it holds or registers: a functional route or a data fetcher written + * as a lambda compiles into the configuration's own method (review 2026-11-05 RR6-01-01), and a + * route registered by method reference names the route builder (review 2026-11-06 RR7-01-02). + * + *

A class nested in a configuration is read like any other class, with the full user-transport + * list, so an endpoint of any transport library kept there is caught — a JAX-RS resource or an + * annotated JSR-356 endpoint as much as a handler function — and so is one that runs the job + * through the configuration that holds it (review 2026-11-06 RR7-01-01). Only setup types are + * left out: an anonymous {@code WebMvcConfigurer} reading the configuration's field is part of + * the configuration (RR6-01-02). */ private static final DescribedPredicate ARE_USER_TRANSPORTS = new DescribedPredicate<>( - "are user transports (in a user-transport package, a configuration with request-handling" - + " code, or another class built from a user-transport type)") { + "are user transports (in a user-transport package, a configuration that holds or registers" + + " request-handling code, or another class built from a user-transport type)") { @Override public boolean test(JavaClass candidate) { if (ARE_USER_TRANSPORT_TYPES.test(candidate)) { return true; } - DescribedPredicate wayIn = - isOrIsNestedInAConfiguration(candidate) - ? ARE_REQUEST_HANDLER_TYPES - : ARE_USER_TRANSPORT_TYPES; + DescribedPredicate wayIn = waysInFor(candidate); return candidate.getDirectDependenciesFromSelf().stream() .anyMatch(dependency -> wayIn.test(dependency.getTargetClass())); } }; - private static boolean isOrIsNestedInAConfiguration(JavaClass candidate) { - for (JavaClass type = candidate; type != null; type = type.getEnclosingClass().orElse(null)) { - if (type.isAnnotatedWith(CONFIGURATION) || type.isMetaAnnotatedWith(CONFIGURATION)) { - return true; + private static DescribedPredicate waysInFor(JavaClass candidate) { + if (isAConfiguration(candidate)) { + return MAKE_A_CONFIGURATION_A_WAY_IN; + } + for (JavaClass type = candidate.getEnclosingClass().orElse(null); + type != null; + type = type.getEnclosingClass().orElse(null)) { + if (isAConfiguration(type)) { + return MAKE_A_NESTED_CLASS_A_WAY_IN; } } - return false; + return ARE_USER_TRANSPORT_TYPES; + } + + private static boolean isAConfiguration(JavaClass type) { + return type.isAnnotatedWith(CONFIGURATION) || type.isMetaAnnotatedWith(CONFIGURATION); + } + + private static String[] withSubpackages(List packages) { + return packages.stream().map(name -> name + "..").toArray(String[]::new); + } + + private static DescribedPredicate namedAnyOf(String description, Set names) { + return DescribedPredicate.describe(description, type -> names.contains(type.getName())); } /** @@ -692,16 +779,17 @@ class ApplicationBoundaryArchitectureTest { * no permission guards (review 2026-11-04 RR3-01-01). Reaching the job's own interface, or any * project type the job extends or implements, counts as reaching the job: that is the type the * endpoint is handed when it injects by interface (RR4-01-01). A configuration may register the - * handler beside web beans (RR4-01-02), but not beside request-handling code of its own, such as - * a functional route (RR6-01-01). + * handler beside web beans (RR4-01-02), but not beside request-handling code it holds or + * registers, such as a functional route, whether written as a lambda (RR6-01-01) or a method + * reference (review 2026-11-06 RR7-01-02). * *

It reads class dependencies, so it sees every typed path, including {@code * ObjectProvider} and {@code getBean(TheJob.class)}: both name the type. It cannot see a * path that names no type the job is handed as — a lookup by bean name or by {@code Object}, or a * configuration that passes a user transport a function wrapping the job ({@code job::run} as a - * {@code Runnable}) — nor request-handling code in a configuration written against a type {@code - * ARE_REQUEST_HANDLER_TYPES} does not list. Manual 07 「시스템이 부르는 쓰기」 lists those paths and what - * holds them. + * {@code Runnable}) — nor request-handling code in a configuration itself written against a type + * {@code ARE_REQUEST_HANDLER_TYPES} does not list. Manual 07 「시스템이 부르는 쓰기」 lists those paths and + * what holds them. */ @ArchTest static final ArchRule USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS = @@ -711,13 +799,16 @@ class ApplicationBoundaryArchitectureTest { .transitivelyDependOnClassesThat(ARE_TYPES_A_SYSTEM_CALLER_IS_HANDED_AS) .as( "USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS: a class a user request comes in " - + "through (a user-transport package; a configuration, or a class nested in one, " - + "with request-handling code such as a functional route or a data fetcher; any " - + "other class built from a web, JAX-RS, GraphQL, gRPC or WebSocket type) does " - + "not reach a @SystemCaller or a " + + "through (a user-transport package; a configuration that holds or registers " + + "request-handling code such as a functional route, a data fetcher or an " + + "interceptor; a class nested in a configuration built from a web, JAX-RS, " + + "GraphQL, gRPC or WebSocket type other than a setup type such as " + + "WebMvcConfigurer; any other class built from one of those types) does not " + + "reach a @SystemCaller or a " + "project type one extends or implements, directly or through other classes — " - + "the system caller runs a @SystemInvoked write with no permission check. A " - + "user-triggered run of the same work is its own use case with " + + "the system caller runs a @SystemInvoked write with no permission check. " + + "Register routes in a configuration apart from the one that builds the system " + + "caller. A user-triggered run of the same work is its own use case with " + "@RequiresPermission (manual 07 「시스템이 부르는 쓰기」)") .allowEmptyShould(true); diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java index 0b82c1e1..aa1b5913 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java @@ -13,7 +13,11 @@ import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.S import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerWithNestedValueTypesFixture; import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.web.PingControllerFixture; import dev.caskeleton.bootstrap.architecture.allowed.application.CleanProjectionQueryPort; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.OrderHandlerFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.OrderRoutesConfigurationFixture; import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideControllerRegistrationFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideCorsMappingFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideCorsSourceFixture; import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideFieldReadingWebMvcConfigurerFixture; import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideWebMvcRegistrationFixture; import dev.caskeleton.bootstrap.architecture.fixtures.application.RootWriteTransactionBoundaryUseCase; @@ -44,6 +48,7 @@ import dev.caskeleton.bootstrap.architecture.violations.application.OutboundWith import dev.caskeleton.bootstrap.architecture.violations.application.RawLeakQueryPort; import dev.caskeleton.bootstrap.architecture.violations.application.ReadOnlyRepositoryWriteUseCase; import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; +import dev.caskeleton.bootstrap.architecture.violations.configuration.RoutesBesideASystemCallerConfigurationFixture; import dev.caskeleton.bootstrap.architecture.violations.configuration.RunNowHandlerFunctionConfigurationFixture; import dev.caskeleton.bootstrap.architecture.violations.configuration.RunNowRouteConfigurationFixture; import dev.caskeleton.bootstrap.architecture.violations.domain.AnnotatedPublicNoArgValueObjectFixture; @@ -322,9 +327,8 @@ class ArchitectureViolationFixtureTest { "dev.caskeleton.bootstrap.architecture.violations.configuration.graphqljava", "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging"); - // RR6-01-02: a class nested in a configuration is read as the configuration is — a request - // handler - // nested there is still a transport, a configurer reading the configuration's field is not. + // RR6-01-02: a request handler nested in a configuration is still a transport; a configurer + // reading the configuration's field names only setup types and is not. private static final JavaClasses HANDLER_FUNCTION_NESTED_IN_A_CONFIGURATION_FIXTURE_ONLY = new ClassFileImporter() .importClasses( @@ -345,6 +349,63 @@ class ArchitectureViolationFixtureTest { SystemCallerBesideFieldReadingWebMvcConfigurerFixture.class, SystemCallerHandlerFixture.class)); + // Review 2026-11-06 RR7-01-01: endpoints a configuration keeps nested in it, built from types the + // request-handler list does not name — a JAX-RS resource, one that runs the job through its + // configuration, an annotated JSR-356 endpoint. importPackages, so the compile-only JAX-RS and + // WebSocket types are never linked. + private static final String NESTED_JAXRS_FIXTURES = + "dev.caskeleton.bootstrap.architecture.violations.configuration.jaxrs"; + + private static final JavaClasses JAXRS_RESOURCES_IN_A_CONFIGURATION_FIXTURE_ONLY = + new ClassFileImporter() + .importPackages( + NESTED_JAXRS_FIXTURES, + "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging"); + + private static final JavaClasses SERVER_ENDPOINT_IN_A_CONFIGURATION_FIXTURE_ONLY = + new ClassFileImporter() + .importPackages( + "dev.caskeleton.bootstrap.architecture.violations.configuration.jsr356", + "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging"); + + // RR7-01-02: routes registered by method reference make their configuration an endpoint, so the + // configuration that also builds a system caller is caught and the same routes in a configuration + // of their own pass. A CORS setup naming RequestMethod is setup, in the configuration and in its + // configurer alike. + private static final JavaClasses ROUTES_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + RoutesBesideASystemCallerConfigurationFixture.class, + OrderHandlerFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + private static final JavaClasses ROUTES_APART_FROM_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + OrderRoutesConfigurationFixture.class, + OrderHandlerFixture.class, + SystemCallerHandlerRegistrationFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + private static final JavaClasses CORS_SOURCE_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + SystemCallerBesideCorsSourceFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + // The anonymous configurer has no class literal, as above. + private static final JavaClasses CORS_MAPPING_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importPackages( + "dev.caskeleton.bootstrap.architecture.allowed.configuration", + "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging") + .that( + JavaClass.Predicates.belongToAnyOf( + SystemCallerBesideCorsMappingFixture.class, SystemCallerHandlerFixture.class)); + // RR6-01-03: a system caller's nested record, enum and exception, and a system caller that is a // record — none of them a type an endpoint injects it as. private static final JavaClasses SYSTEM_CALLER_WITH_NESTED_VALUE_TYPES_FIXTURE_ONLY = @@ -626,6 +687,112 @@ class ArchitectureViolationFixtureTest { assertThat(result.getFailureReport().getDetails()).isEmpty(); } + @Test + void aJaxRsResourceNestedInAConfigurationThatCallsASystemCallerIsCaught() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + JAXRS_RESOURCES_IN_A_CONFIGURATION_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains( + "<" + + NESTED_JAXRS_FIXTURES + + ".RunNowResourceConfigurationFixture$RunNowResource>") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @Test + void aNestedEndpointThatRunsASystemCallerThroughItsConfigurationIsCaught() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + JAXRS_RESOURCES_IN_A_CONFIGURATION_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains( + "<" + + NESTED_JAXRS_FIXTURES + + ".RunNowThroughTheConfigurationFixture$RunNowResource>") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @Test + void anAnnotatedWebSocketEndpointNestedInAConfigurationThatCallsASystemCallerIsCaught() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + SERVER_ENDPOINT_IN_A_CONFIGURATION_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains( + "") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @Test + void aConfigurationThatRegistersMethodReferenceRoutesBesideASystemCallerIsCaught() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + ROUTES_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains( + "<" + RoutesBesideASystemCallerConfigurationFixture.class.getName() + ">") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @Test + void routesRegisteredApartFromTheSystemCallersConfigurationPass() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + ROUTES_APART_FROM_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + + @Test + void aConfigurationNamingRequestMethodForCorsMayRegisterASystemCaller() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + CORS_SOURCE_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + + @Test + void aCorsConfigurerNestedInAConfigurationMayNameRequestMethodAndReadTheConfigurationsField() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + CORS_MAPPING_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + @Test void aSystemCallersNestedRecordEnumAndExceptionPassTheSupertypeRule() { // when diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/UserTransportTypeListsTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/UserTransportTypeListsTest.java new file mode 100644 index 00000000..766ce6fc --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/UserTransportTypeListsTest.java @@ -0,0 +1,81 @@ +package dev.caskeleton.bootstrap.architecture; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collection; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + +/** + * The three type lists {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} reads a class with stay + * in the shape that keeps the rule closed. + * + *

A configuration is read with the request-handler list, a class nested in one with the full + * user-transport list, and both leave out setup types. The two lists drifted apart once: the + * request-handler list named no JAX-RS type, and while nested classes were read with it, a JAX-RS + * resource kept in a configuration passed (review 2026-11-06 RR7-01-01). So every request-handler + * entry has to be a user-transport type too — then moving an endpoint from a configuration into a + * class nested in it cannot hide it — and no setup entry may cover a request-handler type, or it + * would hide that endpoint in both places. + */ +class UserTransportTypeListsTest { + + @Test + void everyRequestHandlerAndSetupEntryIsAUserTransportType() { + // given + List entries = + Stream.>of( + ApplicationBoundaryArchitectureTest.REQUEST_HANDLER_PACKAGES, + ApplicationBoundaryArchitectureTest.REQUEST_HANDLER_TYPE_NAMES, + ApplicationBoundaryArchitectureTest.TRANSPORT_SETUP_PACKAGES, + ApplicationBoundaryArchitectureTest.TRANSPORT_SETUP_TYPE_NAMES) + .flatMap(Collection::stream) + .toList(); + + // when + List outsideTheUserTransportTypes = + entries.stream() + .filter( + entry -> + !ApplicationBoundaryArchitectureTest.USER_TRANSPORT_TYPE_NAMES.contains(entry) + && !isInAnyOf( + entry, + ApplicationBoundaryArchitectureTest.USER_TRANSPORT_FRAMEWORK_PACKAGES)) + .toList(); + + // then + assertThat(outsideTheUserTransportTypes).isEmpty(); + } + + @Test + void noSetupEntryCoversARequestHandlerType() { + // given + List setupPackages = ApplicationBoundaryArchitectureTest.TRANSPORT_SETUP_PACKAGES; + List handlerPackages = ApplicationBoundaryArchitectureTest.REQUEST_HANDLER_PACKAGES; + + // when + List handlerNamesTreatedAsSetup = + ApplicationBoundaryArchitectureTest.REQUEST_HANDLER_TYPE_NAMES.stream() + .filter( + name -> + ApplicationBoundaryArchitectureTest.TRANSPORT_SETUP_TYPE_NAMES.contains(name) + || isInAnyOf(name, setupPackages)) + .toList(); + List overlappingPackages = + Stream.concat( + setupPackages.stream().filter(setup -> isInAnyOf(setup, handlerPackages)), + handlerPackages.stream().filter(handler -> isInAnyOf(handler, setupPackages))) + .toList(); + + // then + assertThat(handlerNamesTreatedAsSetup).isEmpty(); + assertThat(overlappingPackages).isEmpty(); + } + + /** Whether a type or package name is one of the packages or inside one of them. */ + private static boolean isInAnyOf(String name, List packages) { + return packages.stream() + .anyMatch(container -> name.equals(container) || name.startsWith(container + ".")); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderHandlerFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderHandlerFixture.java new file mode 100644 index 00000000..e120ae40 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderHandlerFixture.java @@ -0,0 +1,12 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import org.springframework.web.servlet.function.ServerRequest; +import org.springframework.web.servlet.function.ServerResponse; + +/** A feature's functional-endpoint handler, which reaches no system caller. */ +public final class OrderHandlerFixture { + + public ServerResponse list(ServerRequest request) { + return ServerResponse.ok().build(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderRoutesConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderRoutesConfigurationFixture.java new file mode 100644 index 00000000..0297ace6 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderRoutesConfigurationFixture.java @@ -0,0 +1,21 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.RouterFunctions; +import org.springframework.web.servlet.function.ServerResponse; + +/** + * A feature's route registration in a configuration of its own, apart from the configuration that + * builds the feature's message handler ({@code SystemCallerHandlerRegistrationFixture}). This + * configuration is an endpoint, and it reaches no system caller (review 2026-11-06 RR7-01-02). + */ +@Configuration(proxyBeanMethods = false) +public class OrderRoutesConfigurationFixture { + + @Bean + RouterFunction orderRoutes(OrderHandlerFixture orders) { + return RouterFunctions.route().GET("/orders", orders::list).build(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsMappingFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsMappingFixture.java new file mode 100644 index 00000000..2ba2e538 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsMappingFixture.java @@ -0,0 +1,42 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * One feature configuration: a CORS mapping that reads the configuration's own max age, and the + * feature's message handler. The anonymous configurer names only setup types — the configurer, the + * registry and {@code RequestMethod} — so it is part of the configuration, not a way in, although + * it reaches the handler through the field it reads (review 2026-11-06 RR7-01-02). + */ +@Configuration(proxyBeanMethods = false) +public class SystemCallerBesideCorsMappingFixture { + + private final long corsMaxAgeSeconds; + + public SystemCallerBesideCorsMappingFixture(long corsMaxAgeSeconds) { + this.corsMaxAgeSeconds = corsMaxAgeSeconds; + } + + @Bean + WebMvcConfigurer featureCorsMapping() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry + .addMapping("/features/**") + .allowedMethods(RequestMethod.GET.name(), RequestMethod.HEAD.name()) + .maxAge(corsMaxAgeSeconds); + } + }; + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsSourceFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsSourceFixture.java new file mode 100644 index 00000000..4b15f3f6 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsSourceFixture.java @@ -0,0 +1,33 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import java.util.List; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +/** + * One feature configuration: its CORS source and its message handler. The configuration names + * {@code RequestMethod} for the methods it allows. That enum lives among the controller annotations + * but is a setup value, not request-handling code (review 2026-11-06 RR7-01-02). + */ +@Configuration(proxyBeanMethods = false) +public class SystemCallerBesideCorsSourceFixture { + + @Bean + CorsConfigurationSource featureCorsSource() { + CorsConfiguration cors = new CorsConfiguration(); + cors.setAllowedMethods(List.of(RequestMethod.GET.name(), RequestMethod.HEAD.name())); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/features/**", cors); + return source; + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/package-info.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/package-info.java index dd3860fc..1e1a0f07 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/package-info.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/package-info.java @@ -1,9 +1,10 @@ /** * "Allowed-as-data" composition for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a * feature's configuration that registers its message handler beside its web beans — a {@code - * WebMvcConfigurer}, or the feature's controller. A configuration is the composition root, not a - * way a user request comes in, so naming a web type does not make it a user transport (review - * 2026-11-04 RR4-01-02). Manual 09 「소비」 step 4 registers the handler in "this leaf's configuration - * class", which is where both kinds of bean meet. + * WebMvcConfigurer}, a CORS setup, or the feature's controller. A configuration is the composition + * root, not a way a user request comes in, so naming a web type does not make it a user transport + * (review 2026-11-04 RR4-01-02); registering routes does, so the feature's routes sit in a + * configuration of their own (review 2026-11-06 RR7-01-02). Manual 09 「소비」 step 4 registers the + * handler in "this leaf's configuration class", which is where both kinds of bean meet. */ package dev.caskeleton.bootstrap.architecture.allowed.configuration; diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RoutesBesideASystemCallerConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RoutesBesideASystemCallerConfigurationFixture.java new file mode 100644 index 00000000..4b7a6dbe --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RoutesBesideASystemCallerConfigurationFixture.java @@ -0,0 +1,32 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.OrderHandlerFixture; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.RouterFunctions; +import org.springframework.web.servlet.function.ServerResponse; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: one feature + * configuration registers its functional routes and builds its message handler. The handling code + * is in {@link OrderHandlerFixture}, referenced by method, so no request runs through this class. + * Registering the route still names the route builder, a request-handler type, and class + * dependencies cannot tell the registration from handling code: the configuration is read as an + * endpoint that reaches the handler. The routes go in a configuration of their own ({@code + * OrderRoutesConfigurationFixture}) (review 2026-11-06 RR7-01-02). + */ +@Configuration(proxyBeanMethods = false) +public class RoutesBesideASystemCallerConfigurationFixture { + + @Bean + RouterFunction orderRoutes(OrderHandlerFixture orders) { + return RouterFunctions.route().GET("/orders", orders::list).build(); + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RunNowHandlerFunctionConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RunNowHandlerFunctionConfigurationFixture.java index 46b43112..05036900 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RunNowHandlerFunctionConfigurationFixture.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RunNowHandlerFunctionConfigurationFixture.java @@ -10,8 +10,9 @@ import org.springframework.web.servlet.function.ServerResponse; /** * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: the configuration * itself names no request-handler type, but the handler function it registers is a class nested in - * it. A class nested in a configuration is read as the configuration is, request handlers included, - * so the nested endpoint is still a user transport (review 2026-11-05 RR6-01-02). + * it. A class nested in a configuration is a user transport when it is built from a user-transport + * type other than a setup type, so the nested endpoint is caught (review 2026-11-05 RR6-01-02, + * 2026-11-06 RR7-01-01). */ @Configuration(proxyBeanMethods = false) public class RunNowHandlerFunctionConfigurationFixture { diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowResourceConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowResourceConfigurationFixture.java new file mode 100644 index 00000000..609d6c2f --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowResourceConfigurationFixture.java @@ -0,0 +1,33 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.jaxrs; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import org.springframework.context.annotation.Configuration; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a JAX-RS "run now" + * resource kept in the feature configuration. The request-handler list a configuration is read with + * names no JAX-RS type; a class nested in a configuration is read with the full user-transport + * list, so the resource is still a transport (review 2026-11-06 RR7-01-01). Loaded with {@code + * importPackages}: {@code jakarta.ws.rs-api} is compile-only here, so JUnit must never link it. + */ +@Configuration(proxyBeanMethods = false) +public class RunNowResourceConfigurationFixture { + + /** The resource, kept beside the configuration. */ + @Path("/admin/nightly/run-now") + public static final class RunNowResource { + + private final SystemCallerHandlerFixture handler; + + public RunNowResource(SystemCallerHandlerFixture handler) { + this.handler = handler; + } + + @POST + public void runNow() { + handler.handle(); + } + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowThroughTheConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowThroughTheConfigurationFixture.java new file mode 100644 index 00000000..6aa24dd7 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowThroughTheConfigurationFixture.java @@ -0,0 +1,34 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.jaxrs; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import org.springframework.context.annotation.Configuration; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a "run now" resource + * nested in the configuration that holds the system caller. The resource never names the caller; it + * asks the configuration to run it. The path through the enclosing configuration is followed like + * any other, so the resource is caught — which is why a configurer reading the configuration's + * field is let through by its setup types, not by skipping that path (review 2026-11-06 RR7-01-01). + * Loaded with {@code importPackages}: {@code jakarta.ws.rs-api} is compile-only here. + */ +@Configuration(proxyBeanMethods = false) +public class RunNowThroughTheConfigurationFixture { + + private final SystemCallerHandlerFixture handler = new SystemCallerHandlerFixture(); + + void runNightly() { + handler.handle(); + } + + /** The resource, an inner class that runs the job through its configuration. */ + @Path("/admin/nightly/run-now") + public final class RunNowResource { + + @POST + public void runNow() { + runNightly(); + } + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jsr356/RunNowEndpointConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jsr356/RunNowEndpointConfigurationFixture.java new file mode 100644 index 00000000..219b2b64 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jsr356/RunNowEndpointConfigurationFixture.java @@ -0,0 +1,29 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.jsr356; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import jakarta.websocket.OnMessage; +import jakarta.websocket.server.ServerEndpoint; +import org.springframework.context.annotation.Configuration; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: an annotated JSR-356 + * "run now" endpoint kept in the feature configuration. Like the JAX-RS resource beside it, it is + * built from types only the full user-transport list names (review 2026-11-06 RR7-01-01). Loaded + * with {@code importPackages}: {@code jakarta.websocket-api} is compile-only here. + */ +@Configuration(proxyBeanMethods = false) +public class RunNowEndpointConfigurationFixture { + + /** The endpoint, kept beside the configuration. */ + @ServerEndpoint("/admin/nightly/run-now") + public static final class RunNowEndpoint { + + private final SystemCallerHandlerFixture handler = new SystemCallerHandlerFixture(); + + @OnMessage + public String onMessage(String message) { + handler.handle(); + return message; + } + } +}