diff --git a/.claude/skills/be-security/SKILL.md b/.claude/skills/be-security/SKILL.md index 1a2fa06b..9f49deeb 100644 --- a/.claude/skills/be-security/SKILL.md +++ b/.claude/skills/be-security/SKILL.md @@ -95,4 +95,4 @@ Gradle·Docker는 desktop에서 돈다(`docs/work/operate.md` 4.1절). 명령은 - `docs/jpa/security.md`, `docs/httpclient/security.md`, `docs/fileserver/security.md`, `docs/notification/security-privacy.md` - `.github/dependency-vulnerability-policy.md` — 심각도별 처리와 기한, KEV 대조. - `docs/work/reference/decisions.md` 2.6절(JWT audience·role, `fixture-` 거부, 파일 서버 인가, redirect 헤더, 오류 디스패치)·2.7절(취약 의존성). -- runbook: `docs/runbooks/auth-public-path-misconfiguration.md`, `docs/runbooks/management-actuator-forbidden.md`, `docs/runbooks/authz-cross-tenant-violation.md` +- runbook: `docs/runbooks/auth-decoder-misconfiguration.md`, `docs/runbooks/management-actuator-forbidden.md`, `docs/runbooks/authz-cross-tenant-violation.md` diff --git a/docs/architecture/graphql-api-surface.txt b/docs/architecture/graphql-api-surface.txt index 5857b247..97635895 100644 --- a/docs/architecture/graphql-api-surface.txt +++ b/docs/architecture/graphql-api-surface.txt @@ -5,7 +5,7 @@ # capability artifacts. # Update only after review with: # ./gradlew :adapter:inbound:graphql:updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange -# types: 161 +# types: 163 dev.caskeleton.adapter.inbound.graphql.HealthGraphqlController dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationId @@ -130,6 +130,7 @@ dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBatchLoaderRegistrar dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlCostBudgetHandler dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDataFetcherExceptionResolver +dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDataLoaderObservationConventionAdapter dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDeadlineInstrumentation dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDocumentAuthorizationHandler dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionChain @@ -143,6 +144,7 @@ dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformWebInterceptor dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPreparsedDocumentAdapter dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPrincipalResolver dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlRequestObservationConventionAdapter +dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlResolverObservationConventionAdapter dev.caskeleton.adapter.inbound.graphql.runtime.servlet.GraphQlRequestBodyLimitFilter dev.caskeleton.adapter.inbound.graphql.scalar.BigDecimalScalar dev.caskeleton.adapter.inbound.graphql.scalar.DateScalar diff --git a/docs/capability-status.md b/docs/capability-status.md index d774e82d..2eaaf912 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -530,3 +530,4 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap | Redis ACL `+@pubsub`·`&prod:*`(application 계정 2개) | `infra/redis-sdk/acl/*.acl` | `0ebb77b5` | P22-new-2 | | 시험 `ComposeMergeCharacterizationTest` | `src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java` | `ca1fbfde`(지운 커밋 `23139722`의 부모) | 어느 lane도 고르지 않아 한 번도 돌지 않았다(`integrationTest` lane은 `requires`로 적은 클래스만 고른다). 보던 것(기본·dev 조합 렌더링, 계약 스크립트)은 PR 단계 `verifyComposeProfiles`가 모든 lane으로 본다(2026-11-12 리뷰) | | `HeaderSanitizer`(로그용 헤더 가림)와 시험 `HeaderSanitizerTest` | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/HeaderSanitizer.java`, `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/HeaderSanitizerTest.java` | `e6c3b159` | 운영 코드가 부르지 않았다. 요청 로그는 헤더를 싣지 않는다 | +| `ApiHeaders.DEPRECATION`·`ApiHeaders.DATE` 상수 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java` | `c7a18ec7` | 쓰는 코드가 없었다. `Date`는 서버가, `Deprecation`은 그 헤더를 내는 서비스가 정한다 | diff --git a/docs/ledger/estimates.jsonl b/docs/ledger/estimates.jsonl index a56ba0ad..3bc0f619 100644 --- a/docs/ledger/estimates.jsonl +++ b/docs/ledger/estimates.jsonl @@ -16,3 +16,4 @@ {"schema": 1, "kind": "actual", "task": "w2-be-ci-perf", "correction": true, "transcript": "a6b6b25f-a4f7-46c2-a746-5ab20a588c78", "minutes": 1266, "active_minutes": 555, "calls": 556, "output_tokens": 534063, "cache_read_tokens": 301335415, "max_context": 963079, "within": "over", "result": "partial", "commits": ["ecc14004", "6325b518", "86488256", "c7aff0f4", "7054d179", "575aa1f7", "deeb1126", "96caf997", "cfc80ae8", "000a59ed", "5a95db45", "d237bacc", "7284b581", "14053060", "7dbf11ca", "2c180b90", "24dde586", "aeb60339", "083c6910", "335fc967", "9682c52c", "3e06a809", "d17f8bcf", "7db40c9b"], "why": "앞 actual 줄을 고친다. 그 뒤 총괄 지시 둘(새 main 위로, main.yml concurrency와 취소 증거)과 main 두 번 병합으로 작업 중 138분·호출 92가 더 들었다. 대부분 runner 대기열(PR run이 한 번에 2~4시간 뒤로 밀림)과 desktop 공유 잠금 대기였다. 결과는 여전히 partial: runner PR 130 초록·release gate 125 초록, NFS는 소유자 sudo, 속도 목표 넷은 미달(PR 13.5→12.0분/목표 8, release gate 45.6→32.5분/목표 35는 이미지 job 포함), 캐시 효과는 병합 뒤 측정.", "recorded_at": "2026-11-12T18:36+09:00"} {"schema": 1, "kind": "estimate", "task": "w2-be-ci-perf-2", "transcript": "a6b6b25f-a4f7-46c2-a746-5ab20a588c78", "started_at": "2026-11-12T18:45+09:00", "base": "e7be517e", "task_kind": "improve", "size": "large", "minutes": {"p30": 150, "p50": 240, "p80": 400}, "calls": {"p30": 120, "p50": 200, "p80": 320}, "output_tokens": {"p30": 100000, "p50": 170000, "p80": 280000}, "basis": "직전 라운드 w2-be-ci-perf 실측 555분(p50 144의 3.9배, 대부분 runner·desktop 잠금 대기). 이번 판단 5개(B2·NFS·C2·job 합치기·main 줄 순서), desktop main 측정 1회(30분)+pr 1회, runner nightly 1회(2시간)+release 1회+PR 2회. 대기가 시간을 정한다", "recorded_at": "2026-11-12T18:58+09:00"} {"schema": 1, "kind": "estimate", "task": "r9-group-a", "transcript": "70449164-6ab3-49a9-9bcd-a4281e2a0759", "started_at": "2026-11-13T07:00+09:00", "base": "d3a90479", "task_kind": "improve", "size": "large", "minutes": {"p30": 160, "p50": 240, "p80": 370}, "calls": {"p30": 250, "p50": 380, "p80": 570}, "output_tokens": {"p30": 200000, "p50": 320000, "p80": 490000}, "basis": "발견 31건·PR 3개, 손 판단 결정 약 8(전송별 인가 전달, graphql 하위 좌표, test profile 기동 거부, broadcaster 목적지, metrics registry 맞추기 등), desktop 검증 약 8회(leaf·pr 단계); 원값 300/450/700분·400/600/900호출·350k/550k/850k에 보정 0.53·0.63·0.58을 곱함", "recorded_at": "2026-11-13T06:52+09:00"} +{"schema": 1, "kind": "actual", "task": "r9-group-a", "transcript": "70449164-6ab3-49a9-9bcd-a4281e2a0759", "minutes": 383, "active_minutes": 215, "calls": 2295, "output_tokens": 1973586, "within": "p50", "result": "done", "commits": ["0fded57c", "2f0aefad", "01caee3c", "75df7615", "a7f44d8a", "354b7fc9"], "why": "시간은 p50 안이고 호출·출력은 p80을 넘었다. 새 눈 리뷰 4라운드(발견 약 90건 모두 고침), main 두 번 이동(rebase·재검증), desktop 잠금 대기 중 실행 교체가 호출을 늘렸다", "recorded_at": "2026-11-13T19:15+09:00"} diff --git a/docs/registries/error-codes.yaml b/docs/registries/error-codes.yaml index 1b72892a..d999e811 100644 --- a/docs/registries/error-codes.yaml +++ b/docs/registries/error-codes.yaml @@ -192,7 +192,7 @@ errors: # source: feature-security-operational-baseline L93 — "public path misconfiguration ... | 500 + P1 alert | INTERNAL_AUTH_MISCONFIGURATION | INTERNAL" # 지금 이 코드는 JWT decoder를 만들지 못할 때(issuer discovery 4xx·issuer 불일치·jwks_uri 없음) 나온다. 공개 경로 - # 설정 오류는 이 코드를 내지 않는다(runbook auth-public-path-misconfiguration.md). + # 설정 오류는 이 코드를 내지 않는다(runbook auth-decoder-misconfiguration.md). - code: INTERNAL_AUTH_MISCONFIGURATION category: INTERNAL http_status: 500 @@ -201,7 +201,7 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: crosscut client_safe_message: "요청을 처리할 수 없습니다." - runbook_link: "runbook://auth/public-path-misconfiguration" + runbook_link: "runbook://auth/decoder-misconfiguration" compatibility_impact: none required_test: contract-verification:auth-category diff --git a/docs/registries/metrics.yaml b/docs/registries/metrics.yaml index 4722c3ba..bb399bc6 100644 --- a/docs/registries/metrics.yaml +++ b/docs/registries/metrics.yaml @@ -622,13 +622,17 @@ metrics: - name: graphql.outcome cardinality_limit: 5 - name: error.type - # 오류가 있을 때만 붙는다. + # 오류 분류(REQUEST·INTERNAL), 오류가 없으면 NONE. 요청마다 같은 key 셋을 단다(Prometheus는 key 묶음이 + # 다른 meter를 버린다). cardinality_limit: 10 - name: graphql.complexity.bucket - # 복잡도를 셌을 때만 붙는다. + # 복잡도 구간, 복잡도를 세기 전에 끝난 요청은 unknown. cardinality_limit: 6 - name: graphql.depth.bucket cardinality_limit: 6 + - name: error + # Micrometer가 observation timer마다 단다: 예외 클래스의 단순 이름, 없으면 none. + cardinality_limit: 50 percentiles: null histogram_buckets: null alert_severity_thresholds: {} @@ -640,21 +644,26 @@ metrics: constant: GraphQlObservationNames.REQUEST registered_by: "src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlRequestObservationConvention.java" - # Spring for GraphQL 기본 observation. tag는 Spring 기본 convention(DefaultDataFetcherObservationConvention) - # 그대로다. 이 저장소의 convention bean은 이 두 observation에 붙지 않는다. + # resolver·DataLoader observation. Spring for GraphQL이 내고, tag는 플랫폼 convention이 정한다 + # (GraphQlResolverObservationConventionAdapter·GraphQlDataLoaderObservationConventionAdapter, 상한은 + # GraphQlMetricCardinalityPolicy 허용 목록). response path와 batch key는 싣지 않는다. - name: graphql.datafetcher type: timer unit: seconds tags: + - name: graphql.schema.coordinate + # schema 좌표(Type.field). schema의 field 수가 상한이다. 좌표로 이름 붙일 수 없는 field는 unnamed. + cardinality_limit: 500 - name: graphql.outcome cardinality_limit: 2 allowed_values: [SUCCESS, ERROR] - - name: graphql.field.name - # schema의 field 이름. schema의 field 수가 상한이다. - cardinality_limit: 500 - - name: graphql.error.type - # 예외 클래스의 단순 이름, 없으면 NONE. - cardinality_limit: 20 + - name: graphql.resolver.weight + # cost 단계가 매긴 resolver 무게(등록 안 한 field는 EXTERNAL_BATCH). + cardinality_limit: 6 + allowed_values: [PROPERTY, INDEXED_LOOKUP, BATCHED_RELATION, BOUNDED_AGGREGATION, EXTERNAL_BATCH, EXTERNAL_PER_OBJECT] + - name: error + # Micrometer가 observation timer마다 단다: 예외 클래스의 단순 이름, 없으면 none. + cardinality_limit: 50 percentiles: null histogram_buckets: null alert_severity_thresholds: {} @@ -662,21 +671,27 @@ metrics: log_field_mapping: [] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - source: "framework: Spring for GraphQL observation(이름은 GraphQlObservationNames와 같다)" + source: "src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlObservationNames.java" + constant: GraphQlObservationNames.RESOLVER + registered_by: "src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlResolverObservationConvention.java" - name: graphql.dataloader type: timer unit: seconds tags: + - name: graphql.dataloader.name + # 등록한 loader 이름, 또는 Spring이 @BatchMapping loader에 붙이는 schema 좌표(Book.author). + # 둘 다 아니면(클래스 이름 등) unknown. 등록한 loader와 schema field 수가 상한이다. + cardinality_limit: 500 - name: graphql.outcome cardinality_limit: 2 allowed_values: [SUCCESS, ERROR] - - name: graphql.loader.name - # 등록한 DataLoader 이름, 모르면 unknown. + - name: graphql.batch.size.bucket + cardinality_limit: 4 + allowed_values: ["1", "2-10", "11-100", "100+"] + - name: error + # Micrometer가 observation timer마다 단다: 예외 클래스의 단순 이름, 없으면 none. cardinality_limit: 50 - - name: graphql.error.type - # 예외 클래스의 단순 이름, 없으면 NONE. - cardinality_limit: 20 percentiles: null histogram_buckets: null alert_severity_thresholds: {} @@ -684,7 +699,9 @@ metrics: log_field_mapping: [] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - source: "framework: Spring for GraphQL observation(이름은 GraphQlObservationNames와 같다)" + source: "src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlObservationNames.java" + constant: GraphQlObservationNames.DATA_LOADER + registered_by: "src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlDataLoaderObservationConvention.java" # DataLoader 없이 부모마다 풀린 field. 임계를 넘은 요청에 한 번 기록한다(GraphQlPerParentFetchInstrumentation). - name: graphql.per.parent.fetch @@ -693,6 +710,9 @@ metrics: tags: - name: graphql.schema.coordinate cardinality_limit: 200 + - name: error + # Micrometer가 observation timer마다 단다: 예외 클래스의 단순 이름, 없으면 none. + cardinality_limit: 50 percentiles: null histogram_buckets: null alert_severity_thresholds: {} diff --git a/docs/runbooks/auth-public-path-misconfiguration.md b/docs/runbooks/auth-decoder-misconfiguration.md similarity index 67% rename from docs/runbooks/auth-public-path-misconfiguration.md rename to docs/runbooks/auth-decoder-misconfiguration.md index 92a14795..7c4e9101 100644 --- a/docs/runbooks/auth-public-path-misconfiguration.md +++ b/docs/runbooks/auth-decoder-misconfiguration.md @@ -5,10 +5,10 @@ error_codes: [INTERNAL_AUTH_MISCONFIGURATION] severity: P1 owner: oncall last_updated: 2026-11-13 -status: 초안 +status: 운영 --- -# Runbook: INTERNAL_AUTH_MISCONFIGURATION (`runbook://auth/public-path-misconfiguration`) +# Runbook: INTERNAL_AUTH_MISCONFIGURATION (`runbook://auth/decoder-misconfiguration`) ## 증상 @@ -16,23 +16,23 @@ status: 초안 - ERROR 로그 줄 `security failure: code=INTERNAL_AUTH_MISCONFIGURATION category=INTERNAL method=… path=…` (logger `AuthErrorResponseWriter`). - 이 코드는 JWT decoder를 만들 수 없을 때 나온다: issuer metadata가 망가졌거나 네트워크 문제가 아닌 이유로 decoder 초기화가 실패했다(`JwtDecoderConfig` → `SecurityErrorClassifier`). decoder는 첫 token을 검증할 때 만들어지므로 기동은 성공하고, token을 실은 요청마다 이 500이 난다. -- 공개 경로 설정 오류는 이 코드를 내지 않는다. 잘못 연 공개 경로는 오류 없이 열리므로 스냅숏 검사(아래)로만 잡힌다. +- 공개 경로 설정 오류는 이 코드를 내지 않는다. 잘못 연 공개 경로는 오류 없이 열리므로 CI의 `verifyPublicPathSnapshot` + (공개 경로 목록을 스냅숏과 비교하는 검사)으로만 잡힌다. 이 runbook의 대상이 아니다. ## 진단 - 먼저 issuer 설정을 본다. 앱이 도는 곳에서 `/.well-known/openid-configuration`을 받는다. 이 500은 discovery 후보 주소가 모두 4xx(없는 realm, 틀린 경로)이거나, 응답의 `issuer`가 `APP_SECURITY_JWT_ISSUER`와 글자까지 다르거나(끝의 `/` 포함), `jwks_uri`가 없을 때다. - 연결 실패·5xx·JSON이 아닌 응답이면 이 코드가 아니라 503 `AUTH_JWKS_UNAVAILABLE`이다(`docs/runbooks/auth-jwks-unavailable.md`). -- 공개 경로를 의심하면 CI의 `verifyPublicPathSnapshot` 결과와 공개 경로 목록(`config/security.yml`의 `public-paths`, `SECURITY_PUBLIC_PATHS`)의 최근 변경을 본다. ## 조치 - `APP_SECURITY_JWT_ISSUER`를 IdP discovery의 `issuer`와 같게 고쳐 다시 배포한다. 설정은 기동 때 읽는다. -- 잘못된 공개 경로 변경을 되돌린다. 저장소 루트에서 `./gradlew verifyPublicPathSnapshot`을 돌려 스냅숏과 비교한다. ## 에스컬레이션 -- P1 즉시: token을 싣는 모든 요청이 500이다. 공개 경로를 잘못 열어 인증을 건너뛸 수 있을 때도 P1이다. +- P1 즉시: token을 싣는 모든 요청이 500이다. --- -> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. +이 runbook은 템플릿의 JWT decoder(`JwtDecoderConfig`)가 내는 신호만 다룬다. 서비스가 decoder를 바꾸면 진단 절을 그 decoder에 +맞춘다. diff --git a/docs/runbooks/auth-issuer-mismatch.md b/docs/runbooks/auth-issuer-mismatch.md index 07e6f169..791ae996 100644 --- a/docs/runbooks/auth-issuer-mismatch.md +++ b/docs/runbooks/auth-issuer-mismatch.md @@ -18,7 +18,7 @@ status: 초안 ## 진단 - 검증기가 비교하는 값은 `app.security.issuer-uri`(env `APP_SECURITY_JWT_ISSUER`)다(`config/security.yml` → `JwtDecoderConfig`). 같은 env가 `spring.security.oauth2.resourceserver.jwt.issuer-uri`도 채우지만 decoder는 그 키를 읽지 않는다. -- 거부된 token의 `iss`를 클라이언트 쪽에서 디코딩해 `APP_SECURITY_JWT_ISSUER`와 견준다. 흔한 원인은 hostname(내부·외부 주소), realm 이름, 끝의 `/` 차이다. IdP discovery의 `issuer`와 설정값이 다르면 이 401이 아니라 decoder를 만들지 못한 500 `INTERNAL_AUTH_MISCONFIGURATION`이다(`docs/runbooks/auth-public-path-misconfiguration.md`). +- 거부된 token의 `iss`를 클라이언트 쪽에서 디코딩해 `APP_SECURITY_JWT_ISSUER`와 견준다. 흔한 원인은 hostname(내부·외부 주소), realm 이름, 끝의 `/` 차이다. IdP discovery의 `issuer`와 설정값이 다르면 이 401이 아니라 decoder를 만들지 못한 500 `INTERNAL_AUTH_MISCONFIGURATION`이다(`docs/runbooks/auth-decoder-misconfiguration.md`). - 토큰, `Authorization` 헤더, JWT payload는 로그에 남지 않고 남겨서도 안 된다. ## 조치 diff --git a/docs/runbooks/internal-error-spike.md b/docs/runbooks/internal-error-spike.md index bab656ea..778f4909 100644 --- a/docs/runbooks/internal-error-spike.md +++ b/docs/runbooks/internal-error-spike.md @@ -39,7 +39,7 @@ status: 초안 - 가능한 원인: - 직전 deploy의 회귀 버그 → rollback - JVM OOM (메모리 leak 또는 부하 증가) → heap dump 분석(`runtime-jvm-oom.md`) - - JWT decoder 설정 오류 (`INTERNAL_AUTH_MISCONFIGURATION`) → issuer 설정과 discovery(`auth-public-path-misconfiguration.md`) + - JWT decoder 설정 오류 (`INTERNAL_AUTH_MISCONFIGURATION`) → issuer 설정과 discovery(`auth-decoder-misconfiguration.md`) - thread starvation (pool 고갈) → thread dump (`jstack `) ## 4. Mitigation @@ -66,7 +66,6 @@ status: 초안 - error-codes.yaml rows: `INTERNAL_ERROR`, `INTERNAL_AUTH_MISCONFIGURATION`, `JVM_OOM` - metrics.yaml: `jvm_memory_used_bytes`, `jvm_gc_pause_seconds`, `http_server_requests_seconds_count` -- 관련 branch: [[feature-operational-error-observability-foundation]], [[feature-container-runtime-contract]] --- diff --git a/docs/runbooks/job-dead-letter.md b/docs/runbooks/job-dead-letter.md index 3da9bd71..dc9289cd 100644 --- a/docs/runbooks/job-dead-letter.md +++ b/docs/runbooks/job-dead-letter.md @@ -38,7 +38,7 @@ status: 초안 - 최종 실패 원인 분류: - poison input(직렬화/계약 위반) → 입력 결함, 재처리해도 실패 — 수정 후 재처리 또는 폐기 - 외부 의존성 장기 outage 중 attempts 소진 → 의존성 회복 후 재처리로 해결 가능 - - non-transient error(권한/도메인/스키마)인데 retry된 경우 → 분류기 보강 필요(WAF-REL05-C3: 즉시 DLQ가 정답) + - non-transient error(권한/도메인/스키마)인데 retry된 경우 → 분류기 보강 필요(다시 해도 같은 결과인 오류는 retry 없이 곧바로 DLQ로 보내야 한다) ## 4. Mitigation (수동 처분 — 둘 중 하나) @@ -60,9 +60,8 @@ status: 초안 - error-codes.yaml rows: `JOB_DEAD_LETTER` (INTERNAL, 500, retryable=false) - metrics.yaml: `job.dlq.total{job_name}`, `job.retry.total{job_name, outcome=DLQ}` -- 코드: `app-bootstrap` `async/BackgroundJobMetrics`(retry/DLQ vocabulary 기록 seam — D2/D4) -- 관련 runbook: [[job-executor-rejected]], [[job-timeout]], [[outbox-dead-letter]] -- 관련 branch: [[feature-background-job-async-contract]] (D4 retry/DLQ vocabulary SSOT — outbox/outbound가 consume) +- 코드: `app-bootstrap` `async/BackgroundJobMetrics`(`job.retry.total`·`job.dlq.total`을 남기는 곳) +- 관련 runbook: [job-executor-rejected.md](job-executor-rejected.md), [job-timeout.md](job-timeout.md), [outbox-dead-letter.md](outbox-dead-letter.md) --- diff --git a/docs/runbooks/job-executor-rejected.md b/docs/runbooks/job-executor-rejected.md index e2920811..cea9e5c5 100644 --- a/docs/runbooks/job-executor-rejected.md +++ b/docs/runbooks/job-executor-rejected.md @@ -43,8 +43,8 @@ status: 초안 - 단기: 유입 감속(상위 rate-limit / 스케줄러 interval 확대) 또는 다운스트림 의존성 회복 - pool 재조정(restart-only): `APP_ASYNC_EXECUTOR_CORE_SIZE` / `APP_ASYNC_EXECUTOR_MAX_SIZE` / `APP_ASYNC_EXECUTOR_QUEUE_CAPACITY` - — ⚠ queue를 무한정 키우지 말 것(unbounded 금지, D7). 부하테스트로 수치 검증 후 변경 -- CallerRunsPolicy로의 전환은 use-case 차원의 명시적 결정 필요(request thread latency 침식 — TPE-JDK21-C6) + — ⚠ queue를 무한정 키우지 말 것(한도 없는 queue는 거부 대신 메모리를 다 쓰고 무너진다). 부하테스트로 수치 검증 후 변경 +- CallerRunsPolicy로의 전환은 use-case 차원의 명시적 결정 필요(넘친 작업을 부른 요청 스레드가 직접 돌려서 그 요청의 지연이 늘어난다) ## 5. Escalation @@ -62,8 +62,7 @@ status: 초안 - metrics.yaml: `executor.rejected.total{executor_name, policy}`, `executor.saturation{executor_name}` - 코드: `app-bootstrap` `async/AsyncExecutorConfig`(bounded executor), `async/LoggingAbortPolicy`(reject log+metric), `async/BackgroundJobMetrics` - env: `APP_ASYNC_EXECUTOR_CORE_SIZE` / `APP_ASYNC_EXECUTOR_MAX_SIZE` / `APP_ASYNC_EXECUTOR_QUEUE_CAPACITY` -- 관련 runbook: [[job-timeout]], [[job-dead-letter]] -- 관련 branch: [[feature-background-job-async-contract]] (D7 saturation policy) +- 관련 runbook: [job-timeout.md](job-timeout.md), [job-dead-letter.md](job-dead-letter.md) --- diff --git a/docs/runbooks/job-timeout.md b/docs/runbooks/job-timeout.md index 048b2a2f..4aeabaa8 100644 --- a/docs/runbooks/job-timeout.md +++ b/docs/runbooks/job-timeout.md @@ -39,13 +39,13 @@ status: 초안 - metric panel: `job.retry.total{job_name, outcome}` - 가능한 원인 우선순위: - 외부 의존성(DB lock / 느린 HTTP) 지연으로 job p99 상승 - - job 작업량 증가로 단일 cycle이 19s 예산 초과 (D8 — interrupt 노출) - - interrupt 미반응 blocking call(JDBC 등) → awaitTermination 초과 (K8S-POD-LC-C2 SIGKILL 경로) + - job 작업량 증가로 한 cycle이 종료 대기 19s를 넘김(종료할 때 executor가 실행 중인 작업을 기다리는 시간) + - interrupt 미반응 blocking call(JDBC 등) → awaitTermination 초과(그 사이 k8s grace period가 끝나면 SIGKILL로 죽는다) ## 4. Mitigation - 단기: 의존성 회복 / job 입력 배치 크기 축소 -- job p99가 구조적으로 19s를 넘으면: 작업을 분할하거나, grace period 연장 검토(parent project 운영 계약 소유자 승인 필요 — OUT_OF_BRANCH_SCOPE) +- job p99가 구조적으로 19s를 넘으면: 작업을 분할하거나, grace period 연장 검토(grace period는 배포 설정이 정하므로 그 설정을 가진 팀과 정한다) - 비멱등 job이 재시도로 중복 부작용을 내면 멱등키/dedupe 도입 우선 ## 5. Escalation @@ -65,10 +65,9 @@ status: 초안 - error-codes.yaml rows: `JOB_TIMEOUT` (TRANSIENT_DEPENDENCY, 500, retryable=true, retry_after 10s) - metrics.yaml: `job.retry.total{job_name, outcome}` -- 코드: `app-bootstrap` `async/AsyncExecutorConfig`(awaitTermination 19s — D8 graceful shutdown) -- env: `APP_SERVER_SHUTDOWN_TIMEOUT`(owner: feature-env-driven-runtime-configuration D2) -- 관련 runbook: [[job-executor-rejected]], [[job-dead-letter]] -- 관련 branch: [[feature-background-job-async-contract]] (D4 retry / D8 shutdown) +- 코드: `app-bootstrap` `async/AsyncExecutorConfig`(종료 때 실행 중인 작업을 최대 19s 기다린다, `AWAIT_TERMINATION_SECONDS`) +- env: `APP_SERVER_SHUTDOWN_TIMEOUT`(웹 요청 drain 시간, 정의는 `docs/registries/env-keys.yaml`) +- 관련 runbook: [job-executor-rejected.md](job-executor-rejected.md), [job-dead-letter.md](job-dead-letter.md) --- diff --git a/docs/runbooks/outbox-dead-letter.md b/docs/runbooks/outbox-dead-letter.md index 552e0eb9..aeb99105 100644 --- a/docs/runbooks/outbox-dead-letter.md +++ b/docs/runbooks/outbox-dead-letter.md @@ -98,8 +98,7 @@ UPDATE outbox_event SET status = 'PUBLISHED' WHERE event_id = '' AND status - §4의 SQL 블록은 문서에서 그대로 읽어 실제 PostgreSQL에서 실행하는 테스트가 있다 (`PostgreSqlOutboxDispositionRunbookIntegrationTest`, lane `postgresqlOutboxDispositionRunbookIntegrationTest`). 블록을 고치면 그 lane을 다시 돌린다 -- 관련 runbook: [[outbox-publish-failed]] -- 관련 branch: [[feature-domain-event-outbox-contract]], [[feature-background-job-async-contract]] (max attempts/DLQ vocabulary SSOT) +- 관련 runbook: [outbox-publish-failed.md](outbox-publish-failed.md) ## 8. 배포 전 확인 — V21 순서 키 중복 diff --git a/docs/runbooks/outbox-publish-failed.md b/docs/runbooks/outbox-publish-failed.md index 21275c88..0b68a5ec 100644 --- a/docs/runbooks/outbox-publish-failed.md +++ b/docs/runbooks/outbox-publish-failed.md @@ -114,7 +114,7 @@ UPDATE outbox_event SET status = 'PARKED' WHERE event_id = '' AND status = ' `UPDATE 0`이면 그 사이 relay가 행을 claim해 IN_FLIGHT다. `next_attempt_at`이 지난 뒤 다시 실행한다. 보류된 행 수는 `outbox.pending.size{status=PARKED}`로 보인다. -**롤백 전에 보류를 푼다.** `PARKED`는 이 버전(`bbe944bd` 이후)에 생긴 상태다. 그보다 옛 버전은 이 이름을 몰라 +**롤백 전에 보류를 푼다.** `PARKED`는 V22 migration(`V22__outbox_event_last_failure_code.sql`)과 함께 생긴 상태다. V22 전 버전은 이 이름을 몰라 상태별 집계 전체가 실패하고, `outbox.pending.size` 게이지가 PENDING까지 통째로 꺼진다 — `PENDING size growing` 경보의 입력이 사라진다. 옛 버전으로 롤백해야 하면 그 전에 보류한 행을 모두 Step 3으로 재개하거나 버린다. 이 버전부터는 모르는 상태가 있어도 그 상태만 빼고 세고 WARN 한 번으로 이름을 @@ -155,8 +155,7 @@ UPDATE outbox_event SET status = 'PUBLISHED' WHERE event_id = '' AND status - error-codes.yaml rows: `OUTBOX_PUBLISH_FAILED` (TRANSIENT_DEPENDENCY, retryable=true, retry_after 30s) - metrics.yaml: `outbox.publisher.published.total`, `outbox.publisher.lag`, `outbox.pending.size`, `outbox.retry.long.size`, `outbox.retry.long.age` - 코드: `application-core` `PublishPendingOutboxEventsUseCase`(상태머신), `adapter:outbound:persistence-jpa` `outbox/postgresql/PostgreSqlOutboxClaimRepository`(SKIP LOCKED claim + FIFO 게이트), `adapter:outbound:messaging` `outbox/OutboxMessagePublishAdapter`·`platformbridge/PlatformIntegrationEventPublishAdapter`(fail-closed, 원인 코드 번역) -- 관련 runbook: [[outbox-dead-letter]] -- 관련 branch: [[feature-domain-event-outbox-contract]], [[feature-background-job-async-contract]] (retry/DLQ vocabulary SSOT) +- 관련 runbook: [outbox-dead-letter.md](outbox-dead-letter.md) --- diff --git a/docs/upgrade/2026-11-round9-followups.md b/docs/upgrade/2026-11-round9-followups.md new file mode 100644 index 00000000..bc7e8279 --- /dev/null +++ b/docs/upgrade/2026-11-round9-followups.md @@ -0,0 +1,31 @@ +# 업그레이드 안내 — 2026-11 GraphQL 관측 tag·안 쓰는 헤더 상수·인증 설정 runbook 이름 + +- 범위: 2026-11-12 전체 리뷰를 고친 뒤 남은 후속 다섯 건. GraphQL resolver·DataLoader 지표가 플랫폼 tag를 달고, GraphQL 지표가 + 요청마다 같은 tag key를 달고, 쓰는 곳 없는 `ApiHeaders` 상수 둘을 지웠고, `INTERNAL_AUTH_MISCONFIGURATION`의 runbook 이름을 + 내용에 맞췄다. gRPC 권한 거부를 wire에서 확인하는 시험을 더했고, runbook 본문의 옛 설계 번호·커밋 sha를 평범한 설명으로 바꿨다. +- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 관측·인증 묶음을 고칠 때 범위 밖으로 남긴 후속 + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 GraphQL을 켜고 그 지표로 대시보드를 만든 서비스, +web `ApiHeaders` 상수를 부르는 서비스, 오류 코드의 runbook 링크로 경보를 만든 서비스다. + +## 2. 할 일 + +| # | 바뀐 것 | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | --- | +| 1 | `graphql.request` timer는 모든 요청에 `error.type`·`graphql.complexity.bucket`을 단다. 오류가 없으면 `error.type=NONE`, 복잡도를 세기 전에 끝난 요청은 `graphql.complexity.bucket=unknown`이다. 전에는 두 tag가 빠진 series가 따로 있었고, Prometheus registry는 이름이 같고 key 묶음이 다른 meter를 버리므로 성공이나 실패 한쪽이 `/actuator/prometheus`에 나오지 않았다 | `error.type`이 없는 series로 성공을 세던 질의를 `error.type="NONE"`으로 바꾼다 | 그 질의가 빈 값을 본다 | GraphQL을 켠 서비스 | +| 2 | `graphql.datafetcher` timer의 tag가 Spring 기본값(`graphql.field.name`, `graphql.error.type`, `graphql.outcome`)에서 `graphql.schema.coordinate`(`Type.field`, 좌표로 이름 붙일 수 없는 field는 `unnamed`), `graphql.outcome`, `graphql.resolver.weight`(cost 단계의 resolver 무게, 등록 안 한 field는 `EXTERNAL_BATCH`)로 바뀌었다. Micrometer가 다는 `error` tag(예외 클래스의 단순 이름, 없으면 `none`)는 그대로 있다. 지표 이름은 그대로다 | `graphql.field.name`으로 거른 패널·경보를 `graphql.schema.coordinate`로, `graphql.error.type`으로 거른 것을 `error`로 바꾼다 | 그 패널이 비고 경보가 울리지 않는다 | GraphQL을 켠 서비스 | +| 3 | `graphql.dataloader` timer의 tag가 Spring 기본값(`graphql.loader.name`, `graphql.error.type`, `graphql.outcome`)에서 `graphql.dataloader.name`, `graphql.outcome`, `graphql.batch.size.bucket`(`1`·`2-10`·`11-100`·`100+`)으로 바뀌었다. loader 이름은 등록한 이름이거나 Spring이 `@BatchMapping` loader에 붙이는 schema 좌표(`Book.author`)다. 클래스 이름으로 등록한 loader(`forTypePair`)와 이름 문법 밖의 loader는 `unknown` 하나로 묶인다. `error` tag는 그대로 있다 | `graphql.loader.name`으로 거른 패널·경보를 `graphql.dataloader.name`으로 바꾼다. 클래스 이름 loader를 따로 보려면 이름을 주어 등록한다(`BatchLoaderRegistry`의 `forName(…)`이나 `forTypePair(…).withName(…)`) | 그 패널이 비고, 클래스 이름 loader가 `unknown`에 섞인다 | DataLoader를 쓰는 GraphQL 서비스 | +| 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`)도 그대로다. 이번에 더한 시험이 + 그것을 확인한다. +- runbook 본문은 옛 설계 번호·브랜치 이름·커밋 sha를 평범한 설명으로 바꿨을 뿐 절차는 그대로다. 관련 runbook 링크는 + 상대 링크(`[job-timeout.md](job-timeout.md)`)다. diff --git a/src/adapter/inbound/graphql/README.md b/src/adapter/inbound/graphql/README.md index 5688b224..0ae3569a 100644 --- a/src/adapter/inbound/graphql/README.md +++ b/src/adapter/inbound/graphql/README.md @@ -400,7 +400,7 @@ feature GraphQL schema/resolver 는 여전히 이 leaf 밖이다(스켈레톤은 | preparsed document cache (`execution/`) | `wired` | `GraphQlPreparsedDocumentAdapter` + 같은 테스트의 캐시 hit 케이스 | | 커스텀 scalar (`scalar/`) | `wired` | 같은 테스트의 scalar coercion 케이스 | | 요청 크기 (`http/`, body limit filter) | `wired` | `runtime/GraphQlPlatformWebInterceptorRequestBoundsTest`(auto-configured interceptor 로 byte·shape·extension 거부), `http/GraphQlRequestBoundsTest` | -| 관측 tag cardinality (`observation/`) | `wired` | `runtime/GraphQlRequestObservationConventionAdapter` 가 Spring 의 `ExecutionRequestObservationConvention` 을 구현해 Boot 의 `GraphQlObservationAutoConfiguration` 이 이 컨벤션을 가져간다. `autoconfigure/GraphQlObservationWiringTest`(프레임워크가 실제로 해석), `runtime/GraphQlRequestObservationConventionAdapterTest`(실제 `MeterRegistry` 에 임의 이름 10,000개 → series 1개) | +| 관측 tag cardinality (`observation/`) | `wired` | `runtime/GraphQlRequestObservationConventionAdapter`·`GraphQlResolverObservationConventionAdapter`·`GraphQlDataLoaderObservationConventionAdapter` 가 Spring 의 `ExecutionRequestObservationConvention`·`DataFetcherObservationConvention`·`DataLoaderObservationConvention` 을 구현해 Boot 의 `GraphQlObservationAutoConfiguration` 이 세 컨벤션을 가져간다(`graphql.request`·`graphql.datafetcher`·`graphql.dataloader`). `autoconfigure/GraphQlObservationWiringTest`(프레임워크가 실제로 해석), `runtime/GraphQlRequestObservationConventionAdapterTest`(실제 `MeterRegistry` 에 임의 이름 10,000개 → series 1개), resolver·DataLoader 어댑터 시험(좌표·무게·batch 구간 tag) | | object 인가 (`security/`) | `modelled` | 답하는 계약은 중립 `dev.caskeleton.application.security.ObjectAccessPolicy` 가 소유하고 이 leaf 는 `ApplicationObjectAuthorization` 매핑만 가진다. 실행 경로에 연결하는 configuration 은 없다 | | DataLoader/batching (`dataloader/`) | `wired` | `runtime/GraphQlBatchLoaderRegistrationTest` (실제 graphql-java 실행 + Spring `BatchLoaderRegistry`, 50 parent → 3 downstream 호출), `dataloader/GraphQlBatchContractTest` | | 요청 deadline (`maxExecutionTime`) | `wired` | `systemTest/runtime/GraphQlRequestDeadlineTest`(virtual thread: deadline 근처 `REQUEST_TIMEOUT`, 하위 필드 미실행), `GraphQlRequestDeadlineOnRequestThreadTest`(요청 스레드: 느린 resolver 가 끝난 뒤 응답 — 한계). 이미 도는 resolver 는 끊지 않는다(README 「요청 deadline」) | diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationConfiguration.java index 2503c234..4f03909f 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationConfiguration.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationConfiguration.java @@ -1,15 +1,21 @@ package dev.caskeleton.adapter.inbound.graphql.autoconfigure; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlDataLoaderObservationConvention; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlMetricCardinalityPolicy; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlOperationNameCardinality; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlRequestObservationConvention; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlResolverObservationConvention; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlSensitiveAttributeFilter; +import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDataLoaderObservationConventionAdapter; import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlRequestObservationConventionAdapter; +import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlResolverObservationConventionAdapter; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.graphql.observation.DataFetcherObservationConvention; +import org.springframework.graphql.observation.DataLoaderObservationConvention; import org.springframework.graphql.observation.ExecutionRequestObservationConvention; /** Bounded-cardinality observation conventions for requests, resolvers and DataLoaders. */ @@ -77,6 +83,22 @@ class GraphQlObservationConfiguration { return new GraphQlResolverObservationConvention(filter); } + /** + * Hands the bounded resolver tags to Spring for GraphQL's {@code graphql.datafetcher} + * observation, as the request adapter above does for {@code graphql.request}. + * + * @param convention the platform's bounded resolver tags + * @param costs the registered resolver weights; none registered means every field is charged the + * default weight + */ + @Bean + @ConditionalOnMissingBean(DataFetcherObservationConvention.class) + GraphQlResolverObservationConventionAdapter graphQlDataFetcherObservationConvention( + GraphQlResolverObservationConvention convention, ObjectProvider costs) { + return new GraphQlResolverObservationConventionAdapter( + convention, costs.getIfAvailable(() -> GraphQlCostCatalog.of())); + } + /** The DataLoader observation convention. */ @Bean @ConditionalOnMissingBean @@ -84,4 +106,16 @@ class GraphQlObservationConfiguration { GraphQlSensitiveAttributeFilter filter) { return new GraphQlDataLoaderObservationConvention(filter); } + + /** + * Hands the bounded loader tags to Spring for GraphQL's {@code graphql.dataloader} observation. + * + * @param convention the platform's bounded loader tags + */ + @Bean + @ConditionalOnMissingBean(DataLoaderObservationConvention.class) + GraphQlDataLoaderObservationConventionAdapter graphQlDataLoaderObservationConventionAdapter( + GraphQlDataLoaderObservationConvention convention) { + return new GraphQlDataLoaderObservationConventionAdapter(convention); + } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlDataLoaderObservationConvention.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlDataLoaderObservationConvention.java index 87582f3b..cd4ea0d5 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlDataLoaderObservationConvention.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlDataLoaderObservationConvention.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.inbound.graphql.observation; +import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchObservation; import java.util.LinkedHashMap; import java.util.Map; @@ -44,10 +45,27 @@ public final class GraphQlDataLoaderObservationConvention { * @param outcome bounded outcome name */ public Map tags(GraphQlBatchObservation observation, String outcome) { + return tags(observation.loaderName().value(), observation.batchSize(), outcome); + } + + /** + * Builds the tags of the loader Spring registers for a {@code @BatchMapping} field. Spring names + * that loader after the field's schema coordinate, which is as static as a registered name. + * + * @param batchMappedField the field the loader batches + * @param batchSize keys in the batch + * @param outcome bounded outcome name + */ + public Map tags( + GraphQlSchemaCoordinate batchMappedField, int batchSize, String outcome) { + return tags(batchMappedField.value(), batchSize, outcome); + } + + private Map tags(String loaderName, int batchSize, String outcome) { Map tags = new LinkedHashMap<>(); - tags.put("graphql.dataloader.name", observation.loaderName().value()); + tags.put("graphql.dataloader.name", loaderName); tags.put("graphql.outcome", outcome); - tags.put("graphql.complexity.bucket", batchSizeBucket(observation.batchSize())); + tags.put("graphql.batch.size.bucket", batchSizeBucket(batchSize)); return filter.filter(tags); } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicy.java index 81b48d75..e9cabeba 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicy.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicy.java @@ -24,6 +24,8 @@ public final class GraphQlMetricCardinalityPolicy { "graphql.outcome", "graphql.complexity.bucket", "graphql.depth.bucket", + "graphql.resolver.weight", + "graphql.batch.size.bucket", "error.type"); /** Attributes that must never become metric tags or general trace attributes. */ diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlRequestObservationConvention.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlRequestObservationConvention.java index cdd5263b..89bdc82b 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlRequestObservationConvention.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlRequestObservationConvention.java @@ -18,9 +18,20 @@ import java.util.Map; *

The operation name was the exception, and it was the one that mattered: it was tagged raw, on * the strength of a regular expression that bounds its syntax and says nothing about how many * distinct names a client may invent. {@link GraphQlOperationNameCardinality} closes it. + * + *

Every request carries the same tag keys. A request without errors reports {@link #NO_ERROR} + * and one that never reached costing reports {@link #NOT_SCORED}, rather than leaving the tag out: + * the Prometheus registry keeps the first key set registered under a meter name and drops every + * meter whose keys differ, so an absent tag would make the failures (or the successes) vanish. */ public final class GraphQlRequestObservationConvention { + /** The {@code error.type} of a request that produced no error. */ + public static final String NO_ERROR = "NONE"; + + /** The {@code graphql.complexity.bucket} of a request that never reached costing. */ + public static final String NOT_SCORED = "unknown"; + private final GraphQlSensitiveAttributeFilter filter; private final GraphQlOperationNameCardinality operationNames; @@ -75,8 +86,8 @@ public final class GraphQlRequestObservationConvention { * @param clientProfile bounded client profile * @param persisted whether the operation came from the persisted registry * @param outcome bounded outcome name - * @param errorCategory bounded error category, or {@code null} - * @param complexity computed complexity, or {@code null} when the request never reached costing + * @param errorCategory bounded error category, or {@code null} for {@link #NO_ERROR} + * @param complexity computed complexity, or {@code null} for {@link #NOT_SCORED} * @param depth measured selection depth */ public Map tags( @@ -113,8 +124,8 @@ public final class GraphQlRequestObservationConvention { * @param clientProfile bounded client profile * @param persisted whether the operation came from the persisted registry * @param outcome bounded outcome name - * @param errorCategory bounded error category, or {@code null} - * @param complexity computed complexity, or {@code null} when the request never reached costing + * @param errorCategory bounded error category, or {@code null} for {@link #NO_ERROR} + * @param complexity computed complexity, or {@code null} for {@link #NOT_SCORED} * @param depth measured selection depth */ public Map tagsForWireName( @@ -154,12 +165,8 @@ public final class GraphQlRequestObservationConvention { tags.put("graphql.client.profile", clientProfile.value()); tags.put("graphql.persisted", Boolean.toString(persisted)); tags.put("graphql.outcome", outcome); - if (errorCategory != null) { - tags.put("error.type", errorCategory); - } - if (complexity != null) { - tags.put("graphql.complexity.bucket", complexity.bucket()); - } + tags.put("error.type", errorCategory == null ? NO_ERROR : errorCategory); + tags.put("graphql.complexity.bucket", complexity == null ? NOT_SCORED : complexity.bucket()); tags.put("graphql.depth.bucket", depthBucket(depth)); return filter.filter(tags); } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlResolverObservationConvention.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlResolverObservationConvention.java index 111986d9..1b9f064c 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlResolverObservationConvention.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlResolverObservationConvention.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.inbound.graphql.observation; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog; import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlResolverWeight; import java.util.LinkedHashMap; import java.util.Map; @@ -10,9 +11,16 @@ import java.util.Map; * *

Tagged by schema coordinate, not by response path. The coordinate is a static position in the * schema; a response path contains list indices and therefore grows without bound with the data. + * + *

A field no coordinate can name (a federation field such as {@code _Service.sdl}) is tagged + * {@link #UNNAMED_COORDINATE} with the same keys: the Prometheus registry drops a meter whose tag + * keys differ from the first one registered under its name. */ public final class GraphQlResolverObservationConvention { + /** The {@code graphql.schema.coordinate} of a field no schema coordinate can name. */ + public static final String UNNAMED_COORDINATE = "unnamed"; + private final GraphQlSensitiveAttributeFilter filter; /** @@ -41,17 +49,33 @@ public final class GraphQlResolverObservationConvention { * Builds the resolver tags. * * @param coordinate the resolved field - * @param weight the resolver's registered cost class + * @param weight the resolver's registered cost class, or {@code null} for the default weight * @param outcome bounded outcome name */ public Map tags( GraphQlSchemaCoordinate coordinate, GraphQlResolverWeight weight, String outcome) { + return tags(coordinate.value(), weight, outcome); + } + + /** + * Builds the tags of a resolver whose field no schema coordinate can name. + * + * @param weight the resolver's cost class, or {@code null} for the default weight + * @param outcome bounded outcome name + */ + public Map tagsForUnnamedField(GraphQlResolverWeight weight, String outcome) { + return tags(UNNAMED_COORDINATE, weight, outcome); + } + + private Map tags( + String coordinate, GraphQlResolverWeight weight, String outcome) { Map tags = new LinkedHashMap<>(); - tags.put("graphql.schema.coordinate", coordinate.value()); + tags.put("graphql.schema.coordinate", coordinate); tags.put("graphql.outcome", outcome); - if (weight != null) { - tags.put("graphql.operation.type", weight.name()); - } + // A missing weight is the cost stage's default, never a missing key: see the class comment. + tags.put( + "graphql.resolver.weight", + (weight == null ? GraphQlCostCatalog.DEFAULT_WEIGHT : weight).name()); return filter.filter(tags); } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDataLoaderObservationConventionAdapter.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDataLoaderObservationConventionAdapter.java new file mode 100644 index 00000000..f67f91fa --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDataLoaderObservationConventionAdapter.java @@ -0,0 +1,116 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; +import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchObservation; +import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName; +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlDataLoaderObservationConvention; +import io.micrometer.common.KeyValue; +import io.micrometer.common.KeyValues; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.springframework.graphql.observation.DataLoaderObservationContext; +import org.springframework.graphql.observation.DataLoaderObservationConvention; + +/** + * Makes the platform's bounded DataLoader tags the ones the {@code graphql.dataloader} meter gets. + * + *

The same gap as {@link GraphQlResolverObservationConventionAdapter}: the platform's loader + * convention was not a {@link DataLoaderObservationConvention}, so the framework used its own tags + * and the bounded batch-size bucket was computed for nobody (review 2026-11-13). + * + *

The tags are the loader's name, the outcome ({@code SUCCESS} or {@code ERROR}) and the bucket + * of the batch size. The name is a registered, validated one; or the schema coordinate Spring names + * a {@code @BatchMapping} loader after ({@code Book.author}); or {@link #UNKNOWN_LOADER}. All three + * are static. The keys are never reported: they are object identifiers. + */ +public final class GraphQlDataLoaderObservationConventionAdapter + implements DataLoaderObservationConvention { + + /** The name reported for a loader registered without a valid name. */ + public static final String UNKNOWN_LOADER = "unknown"; + + private final GraphQlDataLoaderObservationConvention convention; + + /** + * Creates the adapter. + * + * @param convention the platform's bounded loader tags + */ + public GraphQlDataLoaderObservationConventionAdapter( + GraphQlDataLoaderObservationConvention convention) { + this.convention = Objects.requireNonNull(convention, "loader convention is required"); + } + + @Override + public String getName() { + return convention.name(); + } + + @Override + public String getContextualName(DataLoaderObservationContext context) { + String name = rawName(context); + return "graphql dataloader " + + batchMappedField(name) + .map(GraphQlSchemaCoordinate::value) + .orElseGet(() -> loaderName(name).value()); + } + + @Override + public KeyValues getLowCardinalityKeyValues(DataLoaderObservationContext context) { + List keys = context.getKeys(); + int batchSize = keys == null ? 0 : keys.size(); + String outcome = + context.getError() == null + ? GraphQlResolverObservationConventionAdapter.OUTCOME_SUCCESS + : GraphQlResolverObservationConventionAdapter.OUTCOME_ERROR; + String name = rawName(context); + Map tags = + batchMappedField(name) + .map(field -> convention.tags(field, batchSize, outcome)) + .orElseGet( + () -> + convention.tags( + new GraphQlBatchObservation( + loaderName(name), batchSize, batchSize, 0, Duration.ZERO), + outcome)); + KeyValues keyValues = KeyValues.empty(); + for (Map.Entry tag : tags.entrySet()) { + keyValues = keyValues.and(KeyValue.of(tag.getKey(), tag.getValue())); + } + return keyValues; + } + + private static String rawName(DataLoaderObservationContext context) { + return context.getDataLoader() == null ? null : context.getDataLoader().getName(); + } + + /** + * The {@code @BatchMapping} field a loader is named after. A coordinate starts with an upper-case + * type name and a registered loader name with a lower-case letter, so the two never overlap. + */ + private static Optional batchMappedField(String name) { + if (name == null) { + return Optional.empty(); + } + try { + return Optional.of(GraphQlSchemaCoordinate.parse(name)); + } catch (IllegalArgumentException notACoordinate) { + // A class name (Spring's forTypePair loaders) or anything else: not a tag value. + return Optional.empty(); + } + } + + private static GraphQlDataLoaderName loaderName(String name) { + if (name != null) { + try { + return new GraphQlDataLoaderName(name); + } catch (IllegalArgumentException outsideTheGrammar) { + // A loader name outside the bounded grammar is not a tag value. + } + } + return new GraphQlDataLoaderName(UNKNOWN_LOADER); + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapter.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapter.java index ae312f8c..d6d1346b 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapter.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapter.java @@ -158,8 +158,8 @@ public final class GraphQlRequestObservationConventionAdapter ExecutionResult result = context.getExecutionResult(); List errors = result == null ? null : result.getErrors(); if (errors == null || errors.isEmpty()) { - // Absent rather than a "none" label: an outcome tag already says the request succeeded, and a - // second tag saying the same thing doubles the series for no extra answer. + // No error category: the convention reports NONE, so a success has the same tag keys as a + // failure and one series shape survives the Prometheus registry. return null; } return internal(errors) diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlResolverObservationConventionAdapter.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlResolverObservationConventionAdapter.java new file mode 100644 index 00000000..72ea52af --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlResolverObservationConventionAdapter.java @@ -0,0 +1,105 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlResolverWeight; +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlResolverObservationConvention; +import graphql.schema.DataFetchingEnvironment; +import graphql.schema.GraphQLNamedType; +import io.micrometer.common.KeyValue; +import io.micrometer.common.KeyValues; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.springframework.graphql.observation.DataFetcherObservationContext; +import org.springframework.graphql.observation.DataFetcherObservationConvention; + +/** + * Makes the platform's bounded resolver tags the ones the {@code graphql.datafetcher} meter gets. + * + *

Spring for GraphQL emits the observation from its own instrumentation and asks a {@link + * DataFetcherObservationConvention} bean what to tag it with. The platform's resolver convention + * did not implement that interface, so the framework used its own field-name tags and the bounded + * coordinate tags were computed for nobody (review 2026-11-13). This class translates, as {@link + * GraphQlRequestObservationConventionAdapter} does for requests. + * + *

Every tag is bounded: the schema coordinate (a static schema position, never the response + * path), the outcome ({@code SUCCESS} or {@code ERROR}) and the resolver weight the cost stage + * charged — the registered one, or {@link GraphQlCostCatalog#DEFAULT_WEIGHT}. A field whose type or + * field name a coordinate cannot express gets the same keys, with the coordinate {@link + * GraphQlResolverObservationConvention#UNNAMED_COORDINATE} and the default weight. Nothing is + * reported at high cardinality: the field path is on the platform's forbidden list. + */ +public final class GraphQlResolverObservationConventionAdapter + implements DataFetcherObservationConvention { + + /** Outcome of a resolver that returned without an error. */ + public static final String OUTCOME_SUCCESS = "SUCCESS"; + + /** Outcome of a resolver that failed. */ + public static final String OUTCOME_ERROR = "ERROR"; + + private final GraphQlResolverObservationConvention convention; + private final GraphQlCostCatalog costs; + + /** + * Creates the adapter. + * + * @param convention the platform's bounded resolver tags + * @param costs the registered resolver weights + */ + public GraphQlResolverObservationConventionAdapter( + GraphQlResolverObservationConvention convention, GraphQlCostCatalog costs) { + this.convention = Objects.requireNonNull(convention, "resolver convention is required"); + this.costs = Objects.requireNonNull(costs, "cost catalog is required"); + } + + @Override + public String getName() { + return convention.name(); + } + + @Override + public String getContextualName(DataFetcherObservationContext context) { + return coordinate(context.getEnvironment()) + .map(coordinate -> "graphql field " + coordinate.value()) + .orElse("graphql field"); + } + + @Override + public KeyValues getLowCardinalityKeyValues(DataFetcherObservationContext context) { + String outcome = context.getError() == null ? OUTCOME_SUCCESS : OUTCOME_ERROR; + Optional coordinate = coordinate(context.getEnvironment()); + Map tags = + coordinate + .map(named -> convention.tags(named, weight(named), outcome)) + .orElseGet( + () -> convention.tagsForUnnamedField(GraphQlCostCatalog.DEFAULT_WEIGHT, outcome)); + KeyValues keyValues = KeyValues.empty(); + for (Map.Entry tag : tags.entrySet()) { + keyValues = keyValues.and(KeyValue.of(tag.getKey(), tag.getValue())); + } + return keyValues; + } + + private GraphQlResolverWeight weight(GraphQlSchemaCoordinate coordinate) { + return costs.registered(coordinate.value()) + ? costs.require(coordinate.value()).resolverWeight() + : GraphQlCostCatalog.DEFAULT_WEIGHT; + } + + private static Optional coordinate(DataFetchingEnvironment environment) { + if (environment == null + || !(environment.getParentType() instanceof GraphQLNamedType parent) + || environment.getField() == null) { + return Optional.empty(); + } + try { + return Optional.of( + new GraphQlSchemaCoordinate(parent.getName(), environment.getField().getName())); + } catch (IllegalArgumentException inexpressible) { + // `_Service.sdl` and the like: no bounded coordinate names it, so it is not a tag value. + return Optional.empty(); + } + } +} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationWiringTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationWiringTest.java index 54c3bf74..f036ad60 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationWiringTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationWiringTest.java @@ -2,12 +2,16 @@ package dev.caskeleton.adapter.inbound.graphql.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDataLoaderObservationConventionAdapter; import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlRequestObservationConventionAdapter; +import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlResolverObservationConventionAdapter; import io.micrometer.observation.ObservationRegistry; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.graphql.autoconfigure.observation.GraphQlObservationAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.graphql.observation.DataFetcherObservationConvention; +import org.springframework.graphql.observation.DataLoaderObservationConvention; import org.springframework.graphql.observation.ExecutionRequestObservationConvention; import org.springframework.graphql.observation.GraphQlObservationInstrumentation; @@ -39,6 +43,12 @@ class GraphQlObservationWiringTest { .getBean(ExecutionRequestObservationConvention.class) .as("the only convention the framework can resolve must be the bounded one") .isInstanceOf(GraphQlRequestObservationConventionAdapter.class); + assertThat(context) + .getBean(DataFetcherObservationConvention.class) + .isInstanceOf(GraphQlResolverObservationConventionAdapter.class); + assertThat(context) + .getBean(DataLoaderObservationConvention.class) + .isInstanceOf(GraphQlDataLoaderObservationConventionAdapter.class); }); } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicyTest.java index 976474dd..ddd7d10b 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicyTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicyTest.java @@ -7,6 +7,7 @@ import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationName; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlComplexityResult; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog; import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlResolverWeight; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchObservation; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName; @@ -14,6 +15,7 @@ import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType; import java.time.Duration; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** Observation naming and cardinality control (Stable plan Task 45). */ @@ -100,9 +102,21 @@ class GraphQlMetricCardinalityPolicyTest { "SUCCESS"); assertThat(tags).containsEntry("graphql.schema.coordinate", "Order.items"); + assertThat(tags).containsEntry("graphql.resolver.weight", "BATCHED_RELATION"); assertThat(tags).doesNotContainKey("graphql.field.path"); } + @Test + @DisplayName("무게 없이 만든 resolver tag 도 graphql.resolver.weight 를 기본 무게로 단다 — key 묶음이 같아야 한다") + void resolverTagsWithoutAWeightCarryTheDefaultWeight() { + Map tags = + GraphQlResolverObservationConvention.standard() + .tags(GraphQlSchemaCoordinate.parse("Order.items"), null, "SUCCESS"); + + assertThat(tags) + .containsEntry("graphql.resolver.weight", GraphQlCostCatalog.DEFAULT_WEIGHT.name()); + } + @Test void loaderTagsCarryTheLoaderNameAndABucketedBatchSize() { Map tags = @@ -114,7 +128,7 @@ class GraphQlMetricCardinalityPolicyTest { assertThat(tags) .containsEntry("graphql.dataloader.name", "order.customer") - .containsEntry("graphql.complexity.bucket", "11-100"); + .containsEntry("graphql.batch.size.bucket", "11-100"); } @Test diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDataLoaderObservationConventionAdapterTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDataLoaderObservationConventionAdapterTest.java new file mode 100644 index 00000000..abcc9aa9 --- /dev/null +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDataLoaderObservationConventionAdapterTest.java @@ -0,0 +1,124 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlDataLoaderObservationConvention; +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationNames; +import io.micrometer.common.KeyValue; +import io.micrometer.common.KeyValues; +import java.lang.reflect.Constructor; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.dataloader.BatchLoaderEnvironment; +import org.dataloader.DataLoader; +import org.dataloader.DataLoaderFactory; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.graphql.observation.DataLoaderObservationContext; + +class GraphQlDataLoaderObservationConventionAdapterTest { + + private final GraphQlDataLoaderObservationConventionAdapter adapter = + new GraphQlDataLoaderObservationConventionAdapter( + GraphQlDataLoaderObservationConvention.standard()); + + @Test + @DisplayName("graphql.dataloader 는 loader 이름·결과·batch 크기 구간으로 tag 를 단다 — key 는 싣지 않는다") + void aBatchIsTaggedByLoaderOutcomeAndSizeBucket() throws Exception { + // given + DataLoaderObservationContext context = + context(loader("order.customer"), IntStream.range(0, 42).boxed().toList()); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "graphql.dataloader.name", "order.customer", + "graphql.outcome", GraphQlResolverObservationConventionAdapter.OUTCOME_SUCCESS, + "graphql.batch.size.bucket", "11-100")); + } + + @Test + @DisplayName("이름 문법 밖의 loader 는 unknown 으로, 실패한 batch 는 ERROR 로 단다") + void aLoaderOutsideTheNameGrammarIsUnknownAndAFailureIsError() throws Exception { + // given + DataLoaderObservationContext context = context(loader("Bad Name!"), List.of(1)); + context.setError(new IllegalStateException("downstream")); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsEntry( + "graphql.dataloader.name", GraphQlDataLoaderObservationConventionAdapter.UNKNOWN_LOADER) + .containsEntry( + "graphql.outcome", GraphQlResolverObservationConventionAdapter.OUTCOME_ERROR); + } + + @Test + @DisplayName("Spring 이 @BatchMapping loader 에 붙이는 schema 좌표 이름(Book.author)은 그대로 loader 이름이다") + void aBatchMappingLoaderIsTaggedByItsFieldCoordinate() throws Exception { + // given + DataLoaderObservationContext context = context(loader("Book.author"), List.of(1, 2)); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "graphql.dataloader.name", "Book.author", + "graphql.outcome", GraphQlResolverObservationConventionAdapter.OUTCOME_SUCCESS, + "graphql.batch.size.bucket", "2-10")); + } + + @Test + @DisplayName("클래스 이름으로 등록한 loader(forTypePair)는 좌표가 아니므로 unknown 이다") + void aLoaderNamedAfterAClassIsUnknown() throws Exception { + // given + DataLoaderObservationContext context = context(loader("com.example.Book"), List.of(1)); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsEntry( + "graphql.dataloader.name", + GraphQlDataLoaderObservationConventionAdapter.UNKNOWN_LOADER); + } + + @Test + void theObservationNameMatchesTheOneSpringAlreadyEmits() { + assertThat(adapter.getName()).isEqualTo(GraphQlObservationNames.DATA_LOADER); + } + + private static Map tags(KeyValues keyValues) { + return keyValues.stream().collect(Collectors.toMap(KeyValue::getKey, KeyValue::getValue)); + } + + private static DataLoader loader(String name) { + return DataLoaderFactory.newDataLoader( + name, + keys -> CompletableFuture.completedFuture(keys.stream().map(String::valueOf).toList())); + } + + /** The framework builds this context; its constructor is package-private. */ + private static DataLoaderObservationContext context(DataLoader loader, List keys) + throws ReflectiveOperationException { + Constructor constructor = + DataLoaderObservationContext.class.getDeclaredConstructor( + DataLoader.class, List.class, BatchLoaderEnvironment.class); + constructor.setAccessible(true); + return constructor.newInstance( + loader, keys, BatchLoaderEnvironment.newBatchLoaderEnvironment().build()); + } +} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapterTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapterTest.java index 3501a98b..af04fdba 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapterTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapterTest.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.inbound.graphql.runtime; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationId; @@ -12,9 +13,12 @@ import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationName import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlOperationNameCardinality; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlRequestObservationConvention; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlSensitiveAttributeFilter; +import graphql.ErrorType; import graphql.ExecutionInput; import graphql.ExecutionResult; +import graphql.GraphqlErrorBuilder; import io.micrometer.core.instrument.Meter; +import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.observation.DefaultMeterObservationHandler; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import io.micrometer.observation.Observation; @@ -25,6 +29,9 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.graphql.observation.ExecutionRequestObservationContext; @@ -118,6 +125,55 @@ class GraphQlRequestObservationConventionAdapterTest { assertThat(requestSeries().get(0).getTag("graphql.client.profile")).isEqualTo("anonymous"); } + @Test + @DisplayName("성공한 요청과 오류가 난 요청은 같은 tag key 셋을 단다 — Prometheus 는 key 묶음이 다른 meter 를 버린다") + void aFailedRequestCarriesTheSameTagKeysAsASuccessfulOne() { + // given + var adapter = new GraphQlRequestObservationConventionAdapter(collapsingConvention()); + observe(adapter, "Anything", null); + + // when + observe( + adapter, + "Anything", + null, + ExecutionResult.newExecutionResult() + .addError( + GraphqlErrorBuilder.newError() + .message("refused") + .errorType(ErrorType.ValidationError) + .build()) + .build()); + + // then + Set keys = + new TreeSet<>( + List.of( + "error", + "error.type", + "graphql.client.profile", + "graphql.complexity.bucket", + "graphql.depth.bucket", + "graphql.operation.name", + "graphql.operation.type", + "graphql.outcome", + "graphql.persisted")); + assertThat(requestSeries()) + .extracting( + id -> id.getTag("error.type"), + id -> id.getTag("graphql.complexity.bucket"), + id -> + id.getTags().stream() + .map(Tag::getKey) + .collect(Collectors.toCollection(TreeSet::new))) + .containsExactlyInAnyOrder( + tuple( + GraphQlRequestObservationConvention.NO_ERROR, + GraphQlRequestObservationConvention.NOT_SCORED, + keys), + tuple("REQUEST", GraphQlRequestObservationConvention.NOT_SCORED, keys)); + } + @Test void theObservationNameMatchesTheOneSpringAlreadyEmits() { var adapter = new GraphQlRequestObservationConventionAdapter(collapsingConvention()); @@ -133,6 +189,18 @@ class GraphQlRequestObservationConventionAdapterTest { GraphQlRequestObservationConventionAdapter adapter, String operationName, GraphQlRequestContext requestContext) { + observe( + adapter, + operationName, + requestContext, + ExecutionResult.newExecutionResult().data(Map.of()).build()); + } + + private void observe( + GraphQlRequestObservationConventionAdapter adapter, + String operationName, + GraphQlRequestContext requestContext, + ExecutionResult result) { ExecutionInput input = ExecutionInput.newExecutionInput("{ __typename }").operationName(operationName).build(); @@ -140,7 +208,7 @@ class GraphQlRequestObservationConventionAdapterTest { input.getGraphQLContext().put(GraphQlRequestContext.CONTEXT_KEY, requestContext); } var context = new ExecutionRequestObservationContext(input); - context.setExecutionResult(ExecutionResult.newExecutionResult().data(Map.of()).build()); + context.setExecutionResult(result); Observation.createNotStarted(adapter, () -> context, observations).observe(() -> {}); } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlResolverObservationConventionAdapterTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlResolverObservationConventionAdapterTest.java new file mode 100644 index 00000000..24237e71 --- /dev/null +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlResolverObservationConventionAdapterTest.java @@ -0,0 +1,122 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlFieldCostDescriptor; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlResolverWeight; +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationNames; +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlResolverObservationConvention; +import graphql.Scalars; +import graphql.execution.MergedField; +import graphql.language.Field; +import graphql.schema.DataFetchingEnvironment; +import graphql.schema.DataFetchingEnvironmentImpl; +import graphql.schema.GraphQLFieldDefinition; +import graphql.schema.GraphQLObjectType; +import io.micrometer.common.KeyValue; +import io.micrometer.common.KeyValues; +import java.lang.reflect.Constructor; +import java.util.Map; +import java.util.stream.Collectors; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.graphql.observation.DataFetcherObservationContext; + +class GraphQlResolverObservationConventionAdapterTest { + + private final GraphQlResolverObservationConventionAdapter adapter = + new GraphQlResolverObservationConventionAdapter( + GraphQlResolverObservationConvention.standard(), + GraphQlCostCatalog.of( + new GraphQlFieldCostDescriptor( + "Order.items", 2, GraphQlResolverWeight.BATCHED_RELATION, true))); + + @Test + @DisplayName("graphql.datafetcher 는 schema 좌표·결과·등록한 resolver 무게로 tag 를 단다") + void aResolverIsTaggedByItsCoordinateOutcomeAndRegisteredWeight() throws Exception { + // given + DataFetcherObservationContext context = context(environment("Order", "items")); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "graphql.schema.coordinate", "Order.items", + "graphql.outcome", GraphQlResolverObservationConventionAdapter.OUTCOME_SUCCESS, + "graphql.resolver.weight", "BATCHED_RELATION")); + } + + @Test + @DisplayName("등록하지 않은 field 는 cost 단계가 매기는 기본 무게로, 실패는 ERROR 로 단다") + void anUnregisteredFailingResolverCarriesTheDefaultWeightAndError() throws Exception { + // given + DataFetcherObservationContext context = context(environment("Query", "orders")); + context.setError(new IllegalStateException("boom")); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsEntry("graphql.outcome", GraphQlResolverObservationConventionAdapter.OUTCOME_ERROR) + .containsEntry("graphql.resolver.weight", GraphQlCostCatalog.DEFAULT_WEIGHT.name()); + } + + @Test + @DisplayName( + "좌표로 이름 붙일 수 없는 field(_Service.sdl)도 같은 tag key 셋을 unnamed·기본 무게로 단다" + + " — Prometheus 는 key 묶음이 다른 meter 를 버린다") + void aFieldNoCoordinateCanNameKeepsTheSameTagKeys() throws Exception { + // given + DataFetcherObservationContext context = context(environment("_Service", "sdl")); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "graphql.schema.coordinate", + GraphQlResolverObservationConvention.UNNAMED_COORDINATE, + "graphql.outcome", + GraphQlResolverObservationConventionAdapter.OUTCOME_SUCCESS, + "graphql.resolver.weight", + GraphQlCostCatalog.DEFAULT_WEIGHT.name())); + } + + @Test + void theObservationNameMatchesTheOneSpringAlreadyEmits() { + assertThat(adapter.getName()).isEqualTo(GraphQlObservationNames.RESOLVER); + } + + private static Map tags(KeyValues keyValues) { + return keyValues.stream().collect(Collectors.toMap(KeyValue::getKey, KeyValue::getValue)); + } + + private static DataFetchingEnvironment environment(String type, String field) { + GraphQLObjectType parent = + GraphQLObjectType.newObject() + .name(type) + .field( + GraphQLFieldDefinition.newFieldDefinition().name(field).type(Scalars.GraphQLString)) + .build(); + return DataFetchingEnvironmentImpl.newDataFetchingEnvironment() + .parentType(parent) + .mergedField(MergedField.newMergedField(Field.newField(field).build()).build()) + .build(); + } + + /** The framework builds this context; its constructor is package-private. */ + private static DataFetcherObservationContext context(DataFetchingEnvironment environment) + throws ReflectiveOperationException { + Constructor constructor = + DataFetcherObservationContext.class.getDeclaredConstructor(DataFetchingEnvironment.class); + constructor.setAccessible(true); + return constructor.newInstance(environment); + } +} 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); + } + } + } +} diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 4c22ff95..d88f68f8 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -497,8 +497,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML - 템플릿 main 이 쓰는 상수: `Retry-After`, rate-limit 신호(`X-RateLimit-Limit`·`-Remaining` 은 숫자, `-Reset` 은 rfc3339 = fixed window 끝), `Cache-Control`·`Vary`, `ETag`·`Location`(CORS 노출 목록). - 서비스 controller 가 읽으라고 둔 상수: `Idempotency-Key`(이름만. key shape/scope/replay 정책은 application-core 소유), - `If-Match`·`If-None-Match`(조건부 요청, 비교는 `conditional.ETags`), `Allow`. `Deprecation`·`Date` 상수는 있지만 아무 - 코드도 쓰지 않는다. `X-Api-Version` 은 없다. + `If-Match`·`If-None-Match`(조건부 요청, 비교는 `conditional.ETags`), `Allow`. `X-Api-Version`·`Deprecation`·`Date` 상수는 + 없다. --- diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java index 52f2e717..9cc3a0d7 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java @@ -28,11 +28,5 @@ public final class ApiHeaders { public static final String X_RATELIMIT_REMAINING = "X-RateLimit-Remaining"; public static final String X_RATELIMIT_RESET = "X-RateLimit-Reset"; - // deep-offset deprecation marker - public static final String DEPRECATION = "Deprecation"; - - // always-emitted - public static final String DATE = "Date"; - private ApiHeaders() {} } diff --git a/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/contract/RunbookCoverageContractTest.java b/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/contract/RunbookCoverageContractTest.java index 658a602d..a650de92 100644 --- a/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/contract/RunbookCoverageContractTest.java +++ b/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/contract/RunbookCoverageContractTest.java @@ -82,7 +82,6 @@ class RunbookCoverageContractTest { "auth-issuer-mismatch.md", "auth-jwks-unavailable.md", "auth-kid-unknown.md", - "auth-public-path-misconfiguration.md", "auth-token-expired.md", "auth-token-invalid-signature.md", "auth-token-malformed.md", diff --git a/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/contract/support/MainSources.java b/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/contract/support/MainSources.java index d243c679..675753e6 100644 --- a/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/contract/support/MainSources.java +++ b/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/contract/support/MainSources.java @@ -15,9 +15,9 @@ import java.util.stream.Stream; * registry lists is really used by shipped code. * *

A registry row that points at a file holding its name only proves the name is declared. When - * the name sits in a constant ({@code DEPRECATION = "Deprecation"}), the row is backed only if - * something uses that constant: it appears again in its own file, or another main file names it as - * {@code DeclaringClass.CONSTANT}. + * the name sits in a constant ({@code NAME = "Some-Header"}), the row is backed only if something + * uses that constant: it appears again in its own file, or another main file names it as {@code + * DeclaringClass.CONSTANT}. */ public final class MainSources {