From 346f8be8372ab2d13ee72334e59d2a14b5f11633 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 19:14:47 +0900 Subject: [PATCH] =?UTF-8?q?test(grpc):=20handler=EA=B0=80=20=EB=B6=80?= =?UTF-8?q?=EB=A5=B8=20@RequiresPermission=20=EA=B1=B0=EB=B6=80=EB=A5=BC?= =?UTF-8?q?=20wire=EC=97=90=EC=84=9C=20=ED=99=95=EC=9D=B8=ED=95=9C?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit gRPC handler가 부른 @RequiresPermission 유스케이스가 권한 없는 호출자를 PERMISSION_DENIED로 돌려보내는지는 조각마다의 단위 시험으로만 본다. 인터셉터가 SecurityContext에 호출자를 두는 것, web method security가 그것을 읽는 것, 거부가 AUTHZ_INSUFFICIENT_PERMISSION carrier인 것, 예외 인터셉터가 그것을 PERMISSION_DENIED로 바꾸는 것이 따로 시험되고, 한 서버에서 함께 돌려 본 시험이 없다. GrpcRequiresPermissionWireTest가 실제 loopback Netty 서버를 띄우고 web 어댑터의 MethodSecurityConfig·AuthorizationAdapter로 order:close 권한을 판정한다. 권한 없는 호출자는 PERMISSION_DENIED와 trailer error-code=AUTHZ_INSUFFICIENT_PERMISSION을, 권한 있는 호출자는 같은 유스케이스의 응답을 받는다. 시험에만 :adapter:inbound:web· :application-core를 testImplementation으로 더하고 lockfile을 다시 만든다. grpcTransportQualificationTest lane이 이 시험을 반드시 돌린다. 버린 안: app-bootstrap integrationTest에 두기. grpc 자동 설정은 모듈이 classpath에 있으면 켜지므로, app-bootstrap 시험 classpath에 grpc를 넣으면 그 leaf의 모든 시험에서 gRPC 서버 설정이 돈다. 운영 의존 (api·implementation)은 그대로라 registry edge는 바뀌지 않는다(의존 방향 검사는 운영 configuration만 본다). 위험: 시험 classpath만 커진다. gRPC lockfile을 자기 쪽에서 고친 파생 서비스는 upgrade 문서 7행대로 lockfile을 다시 만든다. 검증: desktop :adapter:inbound:grpc:check :adapter:inbound:grpc:grpcTransportQualificationTest :adapter:inbound:grpc:verifyDependencyLocks, scripts/verify.sh pr. Refs: round9 그룹 A 범위 밖 후속 5 --- docs/upgrade/2026-11-round9-followups.md | 5 +- src/adapter/inbound/grpc/AGENTS.md | 3 + src/adapter/inbound/grpc/README.md | 1 + src/adapter/inbound/grpc/build.gradle | 7 +- src/adapter/inbound/grpc/gradle.lockfile | 42 +++- .../grpc/GrpcRequiresPermissionWireTest.java | 216 ++++++++++++++++++ 6 files changed, 271 insertions(+), 3 deletions(-) create mode 100644 src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcRequiresPermissionWireTest.java diff --git a/docs/upgrade/2026-11-round9-followups.md b/docs/upgrade/2026-11-round9-followups.md index 2350d249..3c02b0e7 100644 --- a/docs/upgrade/2026-11-round9-followups.md +++ b/docs/upgrade/2026-11-round9-followups.md @@ -1,6 +1,6 @@ # 업그레이드 안내 — 2026-11 GraphQL 관측 tag·안 쓰는 헤더 상수·인증 설정 runbook 이름 -- 범위: 2026-11-12 전체 리뷰를 고친 뒤 남은 후속. GraphQL resolver·DataLoader 지표가 플랫폼 tag를 달고, GraphQL 지표가 요청마다 같은 tag key를 달고, 쓰는 곳 없는 `ApiHeaders` 상수 둘을 지웠고, `INTERNAL_AUTH_MISCONFIGURATION`의 runbook 이름을 내용에 맞췄다. +- 범위: 2026-11-12 전체 리뷰를 고친 뒤 남은 후속. GraphQL resolver·DataLoader 지표가 플랫폼 tag를 달고, GraphQL 지표가 요청마다 같은 tag key를 달고, 쓰는 곳 없는 `ApiHeaders` 상수 둘을 지웠고, `INTERNAL_AUTH_MISCONFIGURATION`의 runbook 이름을 내용에 맞췄다. gRPC 권한 거부를 wire에서 확인하는 시험을 더했다. - 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 관측·인증 묶음을 고칠 때 범위 밖으로 남긴 후속 ## 1. 누가 읽나 @@ -18,7 +18,10 @@ web `ApiHeaders` 상수를 부르는 서비스, 오류 코드의 runbook 링크 | 4 | `GraphQlResolverObservationConvention`이 내는 무게 tag 이름이 `graphql.operation.type`에서 `graphql.resolver.weight`로, `GraphQlDataLoaderObservationConvention`의 batch 크기 tag가 `graphql.complexity.bucket`에서 `graphql.batch.size.bucket`으로 바뀌었다. 두 convention은 이제 `DataFetcherObservationConvention`·`DataLoaderObservationConvention` bean(adapter)으로 Spring observation에 붙는다 | 두 convention의 `tags(...)`를 직접 불러 옛 key를 읽던 코드를 새 key로 바꾼다. 자기 `DataFetcherObservationConvention`·`DataLoaderObservationConvention` bean을 둔 서비스는 그 bean이 쓰이고 위 2·3번 tag가 붙지 않는다 | 옛 key를 찾는 코드가 빈 값을 본다 | 두 convention을 직접 쓰거나 바꾼 서비스 | | 5 | web `ApiHeaders.DEPRECATION`·`ApiHeaders.DATE` 상수를 지웠다. 운영 코드가 쓰지 않았다 | 그 상수를 부르던 코드는 자기 상수나 Spring `HttpHeaders.DATE`로 바꾼다(마지막으로 있던 커밋은 `docs/capability-status.md` 제거 표) | 컴파일이 실패한다 | 그 상수를 부르던 서비스 | | 6 | `INTERNAL_AUTH_MISCONFIGURATION`의 `runbook_link`가 `runbook://auth/public-path-misconfiguration`에서 `runbook://auth/decoder-misconfiguration`으로, 파일이 `docs/runbooks/auth-public-path-misconfiguration.md`에서 `docs/runbooks/auth-decoder-misconfiguration.md`로 바뀌었다. 그 runbook은 `status: 운영`이라 `RunbookCoverageContractTest`의 `LEGACY_STUB_DEBT`(초안 runbook 목록)에서 빠졌다 | 옛 링크·파일 이름을 가리키는 경보·대시보드·문서를 새 이름으로 바꾼다. 옛 파일을 자기 쪽에서 고쳐 두었으면 그 내용을 새 파일로 옮기고 옛 파일을 지운다 | 경보의 runbook 링크가 없는 파일을 가리킨다. 옛 파일이 `status: 초안`으로 남으면 목록과 맞지 않아 `RunbookCoverageContractTest`가 실패한다 | 그 runbook을 쓰거나 고친 서비스 | +| 7 | gRPC leaf의 시험 classpath에 `:adapter:inbound:web`·`:application-core`가 더해졌다(`testImplementation`, 운영 의존은 그대로). `grpcTransportQualificationTest` lane이 `GrpcRequiresPermissionWireTest`를 반드시 돌린다 | gRPC `build.gradle`이나 그 lockfile을 자기 쪽에서 고친 서비스는 merge 뒤 lockfile을 다시 만든다(`./gradlew :adapter:inbound:grpc:resolveAndLockAll --write-locks`) | lockfile 검사가 실패한다 | gRPC leaf를 고친 서비스 | ## 3. 바뀌지 않은 것 - 지표 이름(`graphql.request`, `graphql.datafetcher`, `graphql.dataloader`)과 GraphQL 응답 모양은 그대로다. +- gRPC 권한 거부의 wire 응답(`PERMISSION_DENIED`, `error-code=AUTHZ_INSUFFICIENT_PERMISSION`)도 그대로다. 이번에 더한 시험이 + 그것을 확인한다. diff --git a/src/adapter/inbound/grpc/AGENTS.md b/src/adapter/inbound/grpc/AGENTS.md index 22e0f893..6110e583 100644 --- a/src/adapter/inbound/grpc/AGENTS.md +++ b/src/adapter/inbound/grpc/AGENTS.md @@ -107,6 +107,9 @@ listener 시작이 실패한다. 정책은 `Optional authenticate(Met - `GrpcP1BoundaryWireTest`: 실제 loopback ephemeral Netty unary service의 auth 성공/실패, reflection-off, handler/listener/observer/raw-status 오류 sanitization과 sentinel redaction. 서버 한도(메시지 크기, 기본 deadline, 연결당 동시 호출, executor 포화)도 같은 wire 에서 검증한다. +- `GrpcRequiresPermissionWireTest`: handler가 부른 `@RequiresPermission` 유스케이스를 web 어댑터의 method + security와 권한 port가 판정하고, 권한 없는 호출자는 wire에서 `PERMISSION_DENIED` + (`AUTHZ_INSUFFICIENT_PERMISSION`)를 받는다. web 어댑터는 이 시험에만 쓰는 `testImplementation`이다. 이 증거는 local insecure unary qualification일 뿐 production-ready 근거가 아니다. TLS/mTLS, external bind, 메서드별 deadline, streaming/backpressure, generated protobuf 호환성은 P2로 남아 있다. diff --git a/src/adapter/inbound/grpc/README.md b/src/adapter/inbound/grpc/README.md index 1fc4b102..2d85b064 100644 --- a/src/adapter/inbound/grpc/README.md +++ b/src/adapter/inbound/grpc/README.md @@ -136,6 +136,7 @@ handler가 metadata를 다시 해석하지 않는다. 빈 값·`null` 반환과 gRPC가 어느 executor thread에서 돌리든 넣고, 끝나면 그 thread에 먼저 있던 context로 되돌린다(없었으면 지운다). `@RequiresPermission`이 읽는 곳이 거기라서, gRPC handler가 부른 유스케이스도 web 요청과 같은 방식으로 권한을 판정한다. 권한이 없으면 `AuthorizationDeniedException`(`AUTHZ_INSUFFICIENT_PERMISSION`)이 아래 표대로 `PERMISSION_DENIED`가 된다. +`GrpcRequiresPermissionWireTest`가 실제 서버와 wire에서 web 어댑터의 method security로 이 흐름 전체를 확인한다. - 호출자가 Spring Security `Authentication`이면 그대로 둔다. 역할은 그 principal이 web의 `AuthenticatedPrincipal`일 때만 읽힌다. 정책이 web의 JWT decoder로 token을 검증하고 `JwtToAuthenticatedPrincipalConverter`로 바꾸면 그렇다. diff --git a/src/adapter/inbound/grpc/build.gradle b/src/adapter/inbound/grpc/build.gradle index f19ade05..473018ad 100644 --- a/src/adapter/inbound/grpc/build.gradle +++ b/src/adapter/inbound/grpc/build.gradle @@ -47,13 +47,18 @@ dependencies { testImplementation "io.grpc:grpc-protobuf:${grpcVersion}" // Wire qualification directly uses ClientCalls/ServerCalls/MetadataUtils without generated stubs. testImplementation "io.grpc:grpc-stub:${grpcVersion}" + // Test-only: the web adapter's method security and port judge a @RequiresPermission use case a + // gRPC handler calls (GrpcRequiresPermissionWireTest), as an application that has both does. + testImplementation project(':adapter:inbound:web') + testImplementation project(':application-core') } strictTestLanes { lane('grpcTransportQualificationTest') { description = 'Runs exact no-skip gRPC conditional transport wire evidence.' requires 'dev.caskeleton.adapter.inbound.grpc.GrpcSafeActivationTest', - 'dev.caskeleton.adapter.inbound.grpc.GrpcP1BoundaryWireTest' + 'dev.caskeleton.adapter.inbound.grpc.GrpcP1BoundaryWireTest', + 'dev.caskeleton.adapter.inbound.grpc.GrpcRequiresPermissionWireTest' rejectSkipped = true } } diff --git a/src/adapter/inbound/grpc/gradle.lockfile b/src/adapter/inbound/grpc/gradle.lockfile index e26967bd..4cf03176 100644 --- a/src/adapter/inbound/grpc/gradle.lockfile +++ b/src/adapter/inbound/grpc/gradle.lockfile @@ -4,6 +4,12 @@ biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=compileClasspath,testCompileClasspath ch.qos.logback:logback-classic:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath ch.qos.logback:logback-core:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.7=testRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.7=testRuntimeClasspath +com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.21.7=testRuntimeClasspath +com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.7=testRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.7=testRuntimeClasspath com.fasterxml:classmate:1.7.3=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor @@ -31,6 +37,7 @@ com.google.protobuf:protobuf-java-util:3.25.8=runtimeClasspath,testRuntimeClassp com.google.protobuf:protobuf-java:3.25.8=annotationProcessor,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath +com.nimbusds:nimbus-jose-jwt:10.4=testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle @@ -52,6 +59,9 @@ io.grpc:grpc-util:1.75.0=runtimeClasspath,testRuntimeClasspath io.micrometer:micrometer-commons:1.16.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.perfmark:perfmark-api:0.27.0=runtimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=testRuntimeClasspath +io.swagger.core.v3:swagger-core-jakarta:2.2.38=testRuntimeClasspath +io.swagger.core.v3:swagger-models-jakarta:2.2.38=testRuntimeClasspath jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath jakarta.validation:jakarta.validation-api:3.1.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -65,7 +75,7 @@ net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs +org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs,testRuntimeClasspath org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle org.apache.httpcomponents:httpclient:4.5.13=checkstyle @@ -77,7 +87,9 @@ org.apache.maven.doxia:doxia-core:1.12.0=checkstyle org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle +org.apache.tomcat.embed:tomcat-embed-core:11.0.27=testRuntimeClasspath org.apache.tomcat.embed:tomcat-embed-el:11.0.27=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-websocket:11.0.27=testRuntimeClasspath org.apache.xbean:xbean-reflect:3.7=checkstyle org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath @@ -105,6 +117,7 @@ org.junit:junit-bom:6.1.0=spotbugs org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath org.objenesis:objenesis:3.3=testRuntimeClasspath +org.openapitools:jackson-databind-nullable:0.2.6=testRuntimeClasspath org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath org.osgi:org.osgi.annotation.bundle:2.0.0=compileClasspath,testCompileClasspath org.osgi:org.osgi.annotation.versioning:1.1.2=compileClasspath,testCompileClasspath @@ -123,25 +136,52 @@ org.slf4j:jul-to-slf4j:2.0.20=compileClasspath,runtimeClasspath,testCompileClass org.slf4j:slf4j-api:2.0.20=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.20=checkstyle +org.springdoc:springdoc-openapi-starter-common:3.0.0=testRuntimeClasspath +org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.0=testRuntimeClasspath org.springframework.boot:spring-boot-autoconfigure:4.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.9=annotationProcessor +org.springframework.boot:spring-boot-http-converter:4.0.9=testRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.9=testRuntimeClasspath +org.springframework.boot:spring-boot-security-oauth2-resource-server:4.0.9=testRuntimeClasspath +org.springframework.boot:spring-boot-security:4.0.9=testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.9=testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson:4.0.9=testRuntimeClasspath org.springframework.boot:spring-boot-starter-logging:4.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-oauth2-resource-server:4.0.9=testRuntimeClasspath +org.springframework.boot:spring-boot-starter-security:4.0.9=testRuntimeClasspath org.springframework.boot:spring-boot-starter-test:4.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.9=testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat:4.0.9=testRuntimeClasspath org.springframework.boot:spring-boot-starter-validation:4.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-web:4.0.9=testRuntimeClasspath org.springframework.boot:spring-boot-starter:4.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-test-autoconfigure:4.0.9=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-test:4.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-tomcat:4.0.9=testRuntimeClasspath org.springframework.boot:spring-boot-validation:4.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-web-server:4.0.9=testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc:4.0.9=testRuntimeClasspath org.springframework.boot:spring-boot:4.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-config:7.0.8=testRuntimeClasspath org.springframework.security:spring-security-core:7.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.security:spring-security-crypto:7.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-core:7.0.8=testRuntimeClasspath +org.springframework.security:spring-security-oauth2-jose:7.0.8=testRuntimeClasspath +org.springframework.security:spring-security-oauth2-resource-server:7.0.8=testRuntimeClasspath +org.springframework.security:spring-security-web:7.0.8=testRuntimeClasspath +org.springframework.session:spring-session-core:4.0.5=testRuntimeClasspath org.springframework:spring-aop:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-beans:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-context:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-core:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-expression:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.10=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.10=testRuntimeClasspath +org.springframework:spring-webmvc:7.0.10=testRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath org.yaml:snakeyaml:2.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-core:3.1.7=testRuntimeClasspath +tools.jackson.core:jackson-databind:3.1.7=testRuntimeClasspath +tools.jackson:jackson-bom:3.1.7=testRuntimeClasspath empty= diff --git a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcRequiresPermissionWireTest.java b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcRequiresPermissionWireTest.java new file mode 100644 index 00000000..83b97e32 --- /dev/null +++ b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcRequiresPermissionWireTest.java @@ -0,0 +1,216 @@ +package dev.caskeleton.adapter.inbound.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowableOfType; + +import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; +import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter; +import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig; +import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy; +import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry; +import dev.caskeleton.application.security.AuthorizationPort; +import dev.caskeleton.application.security.RequiresPermission; +import io.grpc.BindableService; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientInterceptors; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.ClientCalls; +import io.grpc.stub.MetadataUtils; +import io.grpc.stub.ServerCalls; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; + +/** + * A {@code @RequiresPermission} use case a gRPC handler calls is judged as the caller the + * authentication policy returned, and a denial reaches the client as {@code PERMISSION_DENIED}. + * + *

The whole chain on a real server and wire: the interceptor puts the caller on the {@code + * SecurityContext} of the thread the handler runs on, the web adapter's method security reads it, + * the denial is the {@code AUTHZ_INSUFFICIENT_PERMISSION} carrier, and the exception interceptor + * maps it. Each piece had its own unit test; nothing ran them together (review 2026-11-13). + */ +class GrpcRequiresPermissionWireTest { + + private static final String SERVICE_NAME = "test.authz.Orders"; + private static final Metadata.Key AUTHORIZATION = + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); + private static final MethodDescriptor CLOSE_ORDER = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(MethodDescriptor.generateFullMethodName(SERVICE_NAME, "CloseOrder")) + .setRequestMarshaller(StringMarshaller.INSTANCE) + .setResponseMarshaller(StringMarshaller.INSTANCE) + .build(); + + private final ApplicationContextRunner contextRunner = + new ApplicationContextRunner() + .withUserConfiguration( + GrpcServerConfig.class, MethodSecurityConfig.class, OrdersConfiguration.class) + .withPropertyValues( + "app.grpc.server.enabled=true", + "app.grpc.server.port=0", + "app.grpc.server.bind-address=127.0.0.1", + "app.grpc.server.allow-insecure-local=true", + "app.grpc.server.reflection-enabled=false"); + + @Test + @DisplayName( + "권한 없는 호출자가 gRPC handler 로 부른 @RequiresPermission 유스케이스는 wire 에서 PERMISSION_DENIED 다") + void aCallerWithoutThePermissionIsDeniedOnTheWire() { + // when + StatusRuntimeException failure = + call( + channel -> + catchThrowableOfType( + StatusRuntimeException.class, () -> closeOrder(channel, "reader", "o-1"))); + + // then + assertThat(failure).isNotNull(); + assertThat( + List.of( + failure.getStatus().getCode(), + String.valueOf(failure.getTrailers().get(GrpcStatusMapper.CODE_KEY)))) + .containsExactly(Status.Code.PERMISSION_DENIED, "AUTHZ_INSUFFICIENT_PERMISSION"); + } + + @Test + @DisplayName("권한이 있는 호출자는 같은 유스케이스를 통과한다 — 거부는 판정이지 빈 context 가 아니다") + void aCallerWithThePermissionPasses() { + // when + String answer = call(channel -> closeOrder(channel, "writer", "o-1")); + + // then + assertThat(answer).isEqualTo("closed o-1"); + } + + private T call(Function action) { + Object[] result = new Object[1]; + contextRunner.run( + context -> { + assertThat(context.getStartupFailure()).isNull(); + int port = context.getBean(GrpcServerRunner.class).getListeningPort(); + ManagedChannel channel = + ManagedChannelBuilder.forAddress("127.0.0.1", port).usePlaintext().build(); + try { + result[0] = action.apply(channel); + } finally { + channel.shutdownNow(); + channel.awaitTermination(5, TimeUnit.SECONDS); + } + }); + @SuppressWarnings("unchecked") // the single value action.apply returned + T value = (T) result[0]; + return value; + } + + private static String closeOrder(Channel channel, String token, String orderId) { + Metadata headers = new Metadata(); + headers.put(AUTHORIZATION, "Bearer " + token); + Channel authenticated = + ClientInterceptors.intercept(channel, MetadataUtils.newAttachHeadersInterceptor(headers)); + return ClientCalls.blockingUnaryCall( + authenticated, + CLOSE_ORDER, + CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS), + orderId); + } + + /** + * A use case guarded the way an application guards one. Not final: method security proxies it. + */ + static class CloseOrderUseCase { + + @RequiresPermission("order:close") + public String close(String orderId) { + return "closed " + orderId; + } + } + + @Configuration(proxyBeanMethods = false) + static class OrdersConfiguration { + + /** The web adapter's real port: roles to permissions, `writer` may close orders. */ + @Bean + AuthorizationPort authorizationPort() { + return new AuthorizationAdapter( + new RolePermissionRegistry( + new RolePermissionPolicy(Map.of("writer", List.of("order:close"))))); + } + + /** A token names the caller and its role, as a policy built on the web JWT converter would. */ + @Bean + GrpcAuthenticationPolicy grpcAuthenticationPolicy() { + return metadata -> { + String header = metadata.get(AUTHORIZATION); + if (header == null || !header.startsWith("Bearer ")) { + return Optional.empty(); + } + String role = header.substring("Bearer ".length()); + AuthenticatedPrincipal principal = + new AuthenticatedPrincipal(role + "-user", role + "@example.test", Set.of(role)); + return Optional.of( + UsernamePasswordAuthenticationToken.authenticated(principal, null, List.of())); + }; + } + + @Bean + CloseOrderUseCase closeOrderUseCase() { + return new CloseOrderUseCase(); + } + + @Bean + @GrpcExposedService + BindableService ordersService(CloseOrderUseCase useCase) { + return () -> + ServerServiceDefinition.builder(SERVICE_NAME) + .addMethod( + CLOSE_ORDER, + ServerCalls.asyncUnaryCall( + (String orderId, StreamObserver observer) -> { + observer.onNext(useCase.close(orderId)); + observer.onCompleted(); + })) + .build(); + } + } + + private enum StringMarshaller implements MethodDescriptor.Marshaller { + INSTANCE; + + @Override + public InputStream stream(String value) { + return new ByteArrayInputStream(value.getBytes(StandardCharsets.UTF_8)); + } + + @Override + public String parse(InputStream stream) { + try { + return new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new IllegalStateException("failed to decode test response", e); + } + } + } +}