From f3fd10f17cdb0959f4f52bbb0044412803683005 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:51:51 +0900 Subject: [PATCH] =?UTF-8?q?docs(manual):=20=EC=A7=9D=20=EB=B0=B1=EC=97=94?= =?UTF-8?q?=EB=93=9C=EC=97=90=20=EC=B2=98=EC=9D=8C=20=EB=B6=99=EC=9D=B4?= =?UTF-8?q?=EA=B8=B0=20=EC=A0=88=EC=9D=84=20=EB=8D=94=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 제품이 짝 백엔드에 처음 붙을 때 볼 문서가 없다. owner 작성자는 SessionGateway 주석, subject·scope fence 규칙, R-3.2, recover 규약을 여러 파일에서 모아야 하고, 백엔드가 무엇을 주고 무엇을 안 주는지(realm의 브라우저 client, 로그인·로그아웃·세션 엔드포인트)는 백엔드 코드를 읽어야 안다. 고른 방법: docs/manual/04-paired-backend-session.md를 새로 둔다. - 두 모드 비교표와 근거 위치(백엔드 bbe944bd의 SecurityConfig, security.yml, application-local.yml, realm JSON). - 공통 준비: AUTH_MODE external, 백엔드 local CORS 출처 http://localhost:3000에 맞춘 dev 포트, owner context 필드, recipe는 복사(import 금지). - jwt: 흐름도, realm에 더할 public client JSON(audience mapper 포함), 제품 설정 키 OIDC_ISSUER·OIDC_CLIENT_ID, product-composition 예시, 하지 않는 것(새로고침 로그아웃, ID token 서명, id_token_hint). - redis-session: 흐름도, 제품이 더할 엔드포인트 셋과 CSRF 토큰 읽기, 프로필을 product-contracts.ts에 옮겨 적는 이유, 예시, 같은 host 조건. - 상태 전이 표, 확인 방법(실제 백엔드 e2e는 아직 없음), 증상별 원인. 매뉴얼 README·02 §5, starter-experience·foundation·optional-adapter- recipes에는 위치만 가리키는 줄을 더했다. 백엔드 표는 복사하지 않고 위치만 적었다(매뉴얼 README 규칙). 위험·한계: 백엔드 설정이 바뀌면 이 문서가 낡는다. 기준 커밋을 문서 첫머리에 적었다. Keycloak client JSON은 실제 Keycloak에 넣어 보지 않았다. 검증: verify:documentation PASS_SCOPED(새 문서와 고친 문서 모두 경로· 명령·게이트 ID 누락 0). Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-03 --- .../frontend-application-foundation.md | 5 +- docs/architecture/optional-adapter-recipes.md | 1 + docs/architecture/starter-experience.md | 12 + docs/manual/02-decision-tables.md | 1 + docs/manual/04-paired-backend-session.md | 298 ++++++++++++++++++ docs/manual/README.md | 2 + 6 files changed, 318 insertions(+), 1 deletion(-) create mode 100644 docs/manual/04-paired-backend-session.md diff --git a/docs/architecture/frontend-application-foundation.md b/docs/architecture/frontend-application-foundation.md index d9fe275e..428774e1 100644 --- a/docs/architecture/frontend-application-foundation.md +++ b/docs/architecture/frontend-application-foundation.md @@ -181,7 +181,10 @@ the session itself (a BFF whose session is an httpOnly cookie) returns its session owner from `composeProductSessionOwner` in the same file. It is asked first, before `http` exists, only when `AUTH_MODE` is `external`, and it comes before the host's `__CA_FRONTEND_AUTH_OWNER__`; `null` leaves the session to -that global. Product auth profiles, runtime-config keys and the keys' +that global. Its context (`src/bootstrap/product-session-owner-context.ts`) +carries a `fetch` with one deadline over the whole exchange, the page for a +sign-in redirect, the page's session storage for that redirect only, and +`readCookie`. Product auth profiles, runtime-config keys and the keys' FE-REG-ENV rows go in `src/contracts/product-contracts.ts`; each joins the template's registry under the same checks (`tests/unit/product-composition-fixture.test.ts`). diff --git a/docs/architecture/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index 4281ddba..3760bad9 100644 --- a/docs/architecture/optional-adapter-recipes.md +++ b/docs/architecture/optional-adapter-recipes.md @@ -22,6 +22,7 @@ production readiness를 뜻하지 않는다. | file/IndexedDB/OPFS/Cache 심층 계약. reference runtime이 있는 port는 복사하지 않고 `src/application/ports`의 port를 다시 내보낸다([0929] 05-03) | `recipes/frontend-capabilities/browser-file-storage-contracts.ts` | 아니오 | | 심층 deterministic fake. file·storage durability·OPFS fake는 `src` port를 `implements`한다 | `recipes/frontend-capabilities/browser-file-storage-fakes.ts` | 아니오 | | 심층 contract test | `tests/recipes/browser-file-storage-contracts.test.ts` | 아니오 | +| 짝 백엔드 세션 owner(JWT·Keycloak PKCE, Redis session 쿠키+CSRF). catalog 밖이고 복사해서 쓴다. src가 import하면 `PRODUCTION_IMPORTS_RECIPE` | `recipes/session-owners/`, 테스트 `tests/recipes/oidc-pkce-session-owner.test.ts`, `tests/recipes/cookie-session-owner.test.ts`, `tests/recipes/session-owners-runtime.test.ts`, 절차 `docs/manual/04-paired-backend-session.md` | 아니오 | | browser data current-status ledger | `docs/architecture/browser-data-capability-completion-ledger.md` | 문서만 | | 심층 설계/ADR | `docs/architecture/browser-file-and-origin-storage.md`, `decisions/VD-11-browser-file-and-origin-storage.md` | 문서만 | | client cache scope/persistence 설계 | `docs/architecture/client-cache-and-storage.md`, `decisions/VD-13-client-cache-scope-and-persistence.md` | 문서만 | diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index 0a4512dc..af25901e 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -51,6 +51,18 @@ An external owner implements `readState`, `readSubject`, `subscribe`, lacks any of these methods is rejected, and the session fails closed as `integration-failed`. +The state transitions an owner makes, and what `recover()` leaves behind for +each answer, are written on `SessionState` and `SessionGateway.recover` in +`src/application/ports/auth-session-port.ts`. For the paired backend's two +authentication modes there are owners to copy, not to write: +`recipes/session-owners/oidc-pkce-session-owner.ts` (JWT mode: Keycloak, +authorization code with PKCE, `EXTERNAL_BEARER`) and +`recipes/session-owners/cookie-session-owner.ts` (Redis session mode: the +session cookie, plus `SESSION_COOKIE_*` profiles and the `X-XSRF-TOKEN` +provider). `docs/manual/04-paired-backend-session.md` wires them and lists +what the backend template does not ship (a browser client in its realm; the +sign-in, sign-out and session endpoints). + `readSubject()` is required. The server-state cache is cleared only when the session state or the subject changes, so a token refresh for the same user keeps cached data. `readSubject()` must return: diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 96fe6213..b4bfb867 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -191,6 +191,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 - `REFERENCE_EXTERNAL_BEARER`는 `EXTERNAL_BEARER`의 옛 이름이다. `@deprecated`이고 한 릴리스 뒤 지운다. 새 코드는 쓰지 않는다. - 제품 프로필 ID는 템플릿 프로필 ID와 겹치면 안 된다. - 쿠키 인증과 CSRF 헤더는 인증 프로필의 헤더 집합으로 표현한다. 예제: `tests/unit/product-composition-fixture.test.ts`. +- 짝 백엔드에 붙일 때 세션 owner와 프로필은 [04 문서](04-paired-backend-session.md)가 모드별로 정한다. JWT 모드는 `EXTERNAL_BEARER`, Redis session 모드는 `SESSION_COOKIE_READ`·`SESSION_COOKIE_WRITE`다. **기준**: 백엔드가 그 API에 요구하는 인증을 따른다. 새 프로필은 템플릿 파일이 아니라 제품 소유 파일 두 곳에만 더한다. diff --git a/docs/manual/04-paired-backend-session.md b/docs/manual/04-paired-backend-session.md new file mode 100644 index 00000000..c9a6c965 --- /dev/null +++ b/docs/manual/04-paired-backend-session.md @@ -0,0 +1,298 @@ +# 04. 짝 백엔드에 처음 붙이기 — 세션 owner + +핵심: 짝 백엔드(`clean-architecture-backend-template`)는 인증 방식이 둘이다. 한 배포는 하나만 쓴다. +프론트는 그 방식에 맞는 세션 owner를 `recipes/session-owners/`에서 골라 복사하고, `composeProductSessionOwner`에서 돌려준다. + +- 세션 owner: 지금 누가 로그인했는지 알고, 요청에 붙일 자격 증명을 주는 객체다. 계약은 `src/adapters/auth/external-session-adapter.ts`의 `ExternalSessionOwner`다. +- 템플릿에는 demo owner만 있다. demo는 `APP_ENV=local`에서만 켜지고, 그 표식 토큰은 백엔드 JWT 검증을 통과하지 못한다. +- `AUTH_MODE: "external"`인데 owner가 없으면 세션은 `integration-failed`로 닫히고, 인증이 필요한 화면은 "로그인 연동이 필요합니다"를 보인다. + +이 문서의 백엔드 사실은 백엔드 `bbe944bd` 기준이다. 백엔드가 인증 설정을 바꾸면 이 문서와 recipe를 함께 맞춘다. + +--- + +## 1. 어느 쪽인가 + +백엔드의 `APP_SECURITY_AUTH_MODE`가 정한다. 기본값은 `jwt`다. + +| | `jwt` | `redis-session` | +|---|---|---| +| 백엔드가 받는 것 | `Authorization: Bearer ` | `CA_SESSION` 쿠키. 쓰기에는 `X-XSRF-TOKEN` 헤더도 | +| 프론트 recipe | `recipes/session-owners/oidc-pkce-session-owner.ts` | `recipes/session-owners/cookie-session-owner.ts` | +| operation 인증 프로필 | `EXTERNAL_BEARER` (템플릿. 생성 뼈대 기본값) | `SESSION_COOKIE_READ`, `SESSION_COOKIE_WRITE` (제품 프로필. recipe에 있다) | +| 백엔드 템플릿에 없어서 제품이 더하는 것 | Keycloak realm의 브라우저용 public client, 사용자 | 로그인·로그아웃·세션 조회 엔드포인트 | +| 브라우저에 남는 것 | 없음. 토큰은 메모리에만 | httpOnly 쿠키. 스크립트는 못 읽는다 | + +백엔드 근거 위치: + +- 두 모드의 보안 체인: `clean-architecture-backend-template/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java` +- 쿠키·CSRF 이름과 모드 기본값: `clean-architecture-backend-template/src/app-bootstrap/src/main/resources/config/security.yml` +- local issuer·audience·CORS: `clean-architecture-backend-template/src/app-bootstrap/src/main/resources/application-local.yml` +- realm: `clean-architecture-backend-template/infra/keycloak/realms/ca-skeleton-realm.json` + +--- + +## 2. 공통 준비 + +1. `config/runtime/local.json`의 `AUTH_MODE`를 `"external"`로 바꾼다. + - `demo`로 두면 owner를 묻지 않는다. 백엔드에 실제로 붙지 않는다. +2. 백엔드 local 프로필의 CORS 허용 출처는 `http://localhost:3000`이다. 프론트를 그 포트로 띄운다. + - `corepack pnpm dev --port 3000` + - 다른 포트를 쓰면 백엔드의 CORS 허용 출처를 그 출처로 바꾼다. +3. owner는 `ProductSessionOwnerContext`(`src/bootstrap/product-composition-contract.ts`)에서 만든다. + - `fetch`: 요청 하나에 마감이 있다(`REQUEST_TIMEOUT_MS`가 상한). 본문은 64 KiB까지 읽는다. redirect는 따라가지 않는다. + - `fetcher`는 마감이 없다. owner에서 쓰지 않는다. 응답하지 않는 호출 하나가 세션을 "복구 중"에 영원히 둔다. + - `page`: 지금 URL, URL 바꾸기, 다른 페이지로 이동. 로그인 리다이렉트에 쓴다. + - `redirectStorage`: 페이지의 sessionStorage. 리다이렉트 한 번 동안의 상태만 둔다. 토큰은 두지 않는다(`AUTH_TOKEN`은 `src/contracts/storage-keys.ts`에서 `forbidden`이다). + - `readCookie`: 페이지 쿠키 읽기. +4. recipe는 `src/bootstrap/` 아래로 **복사**한다. import하지 않는다. + - `src`가 `recipes/`를 import하면 `check:optional-recipes`가 `PRODUCTION_IMPORTS_RECIPE`로 막는다. + - 복사한 파일의 import 경로에서 `../../src/`를 `../`로 바꾼다. + - 템플릿이 recipe를 고치면 CHANGELOG에 적는다. 복사본에 같은 diff를 옮긴다. + +--- + +## 3. `jwt` 모드 — OIDC PKCE owner + +```text +로그인 버튼 → beginSignIn(returnTo) + → owner가 verifier·state·nonce를 만들어 redirectStorage에 둔다 (10분) + → Keycloak 로그인 화면 (code_challenge = SHA-256(verifier)) + → 앱 기본 주소로 돌아온다 (?code=…&state=…&iss=…) + → owner가 저장한 거래를 지우고, URL에서 code를 지우고 returnTo로 바꾼다 [recovery-pending] + → 토큰 엔드포인트에서 code + verifier를 토큰으로 바꾼다 + → ID token의 iss·aud·nonce·exp·sub를 확인한다 [authenticated, subject = sub] + +요청 → attachCredential → Authorization: Bearer (API origin에만) +만료 30초 전 → refresh token으로 한 번 갱신. 상태 알림이 없어 서버 상태 캐시가 남는다 +서버 401 → refresh로 한 번 복구 → 새 토큰도 401이면 로그아웃 [unauthenticated] +``` + +- PKCE: 로그인 시작 때 만든 비밀값(verifier)의 해시를 보내고, 토큰을 받을 때 원래 값을 보내는 방식이다. 중간에서 code를 가로채도 토큰으로 바꾸지 못한다. +- 라이브러리는 없다. WebCrypto와 context `fetch`만 쓴다. + +### 3.1 Keycloak에 브라우저용 client를 더한다 + +백엔드 realm에는 서비스용 confidential client `ca-skeleton-api` 하나뿐이다. 그 client는 브라우저 로그인(standard flow)이 꺼져 있다. 그래서 브라우저가 로그인할 public client를 제품이 더한다. + +realm JSON의 `clients`에 넣거나 Keycloak 관리 화면에서 같은 값으로 만든다. + +```json +{ + "clientId": "ca-frontend", + "enabled": true, + "protocol": "openid-connect", + "publicClient": true, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "redirectUris": ["http://localhost:3000/*"], + "webOrigins": ["http://localhost:3000"], + "attributes": { + "pkce.code.challenge.method": "S256", + "post.logout.redirect.uris": "http://localhost:3000/*" + }, + "protocolMappers": [ + { + "name": "ca-skeleton-api-audience", + "protocol": "openid-connect", + "protocolMapper": "oidc-audience-mapper", + "config": { + "included.client.audience": "ca-skeleton-api", + "id.token.claim": "false", + "access.token.claim": "true" + } + } + ] +} +``` + +- audience mapper가 꼭 있어야 한다. 백엔드는 access token의 `aud`에 `APP_SECURITY_JWT_AUDIENCE`(local 기본 `ca-skeleton-api`)가 없으면 401 `AUTH_AUDIENCE_MISMATCH`로 거부한다. +- `webOrigins`는 브라우저가 토큰 엔드포인트를 부를 때의 CORS 허용이다. +- realm에는 사람 사용자가 없다. local에서는 관리 화면에서 사용자를 하나 만들고 realm role `user`를 준다. +- 백엔드 권한은 `realm_access.roles`와 `resource_access.ca-skeleton-api.roles`에서 온다. 쓰기 권한이 필요하면 그 사용자에게 `ca-skeleton-api`의 client role을 준다(`clean-architecture-backend-template/docs/manual/07-authorization.md`). + +### 3.2 제품 설정 키를 더한다 + +issuer와 client id는 환경마다 다르다. 그래서 런타임 설정 키로 둔다. `src/contracts/product-contracts.ts`: + +```ts +import { z } from "./zod.ts"; + +export const PRODUCT_RUNTIME_CONFIG_FIELDS = Object.freeze({ + OIDC_ISSUER: z.url().optional(), + OIDC_CLIENT_ID: z.string().min(1).optional(), +}); + +export const PRODUCT_ENV_REGISTRY = Object.freeze({ + OIDC_ISSUER: { phase: "runtime", classification: "public", required: false }, + OIDC_CLIENT_ID: { phase: "runtime", classification: "public", required: false }, +} as const); +``` + +- `.optional()`로 둔다. 값이 비면 owner는 `integration-failed`로 닫힌다. 잘못된 곳으로 로그인하지 않는다. +- `config/runtime/local.json`에 `"OIDC_ISSUER": "http://localhost:8081/realms/ca-skeleton"`, `"OIDC_CLIENT_ID": "ca-frontend"`를 더한다. +- `OIDC_ISSUER`는 백엔드 `APP_SECURITY_JWT_ISSUER`와 글자 하나까지 같아야 한다. 끝의 `/`도 같아야 한다. +- 원격 issuer는 HTTPS만 받는다. HTTP는 `localhost`, `127.0.0.1`, `[::1]`에서만 받는다. + +### 3.3 owner를 돌려준다 + +recipe를 `src/bootstrap/` 아래로 복사한 뒤(예: 같은 이름 oidc-pkce-session-owner.ts) `src/bootstrap/product-composition.ts`: + +```ts +import { createOidcPkceSessionOwner } from "./oidc-pkce-session-owner.ts"; + +export function composeProductSessionOwner( + context: ProductSessionOwnerContext, +): ProductSessionOwner { + const app = new URL(context.page.href()); + return createOidcPkceSessionOwner({ + issuer: context.config.OIDC_ISSUER ?? "", + clientId: context.config.OIDC_CLIENT_ID ?? "", + // 앱 기본 주소: origin + 라우터 base path. client의 redirect URI와 같아야 한다. + redirectUri: new URL("/", app.origin).href, + postLogoutRedirectUri: new URL("/", app.origin).href, + apiOrigins: [new URL(context.config.API_BASE_URL).origin], + fetch: context.fetch, + page: context.page, + redirectStorage: context.redirectStorage, + }); +} +``` + +- 라우터 base path가 `/`가 아니면 `redirectUri`에 그 경로를 넣는다. 돌아온 뒤 owner가 그 경로 아래의 `returnTo`로 URL을 바꾼다. +- operation은 `EXTERNAL_BEARER` 그대로 둔다. 바꿀 것이 없다. +- 배포 CSP `connect-src 'self' https:`는 HTTPS Keycloak을 이미 허용한다(`config/hosting/security-headers.json`). + +### 3.4 이 owner가 하지 않는 것 + +- **새로고침하면 로그아웃된다.** 토큰이 메모리에만 있기 때문이다. Keycloak SSO 세션이 살아 있으면 로그인 버튼 한 번이 비밀번호 없이 돌아온다. + - 새로고침에도 로그인을 유지하려면 `prompt=none` 리다이렉트를 더하는 것은 제품의 결정이다. 토큰을 storage에 두는 방법은 쓰지 않는다. +- **ID token 서명은 보지 않는다.** 토큰 엔드포인트에서 직접 받은 응답이라 TLS가 출처를 보증한다(OIDC Core 3.1.3.7 (6)). access token 서명은 백엔드가 확인한다. +- **로그아웃 URL에 ID token을 넣지 않는다.** 그래서 Keycloak이 "로그아웃할까요?"를 한 번 묻는다. + +--- + +## 4. `redis-session` 모드 — 쿠키 owner와 CSRF provider + +```text +부팅 → owner가 세션 엔드포인트를 묻는다 (GET, 쿠키 포함) [recovery-pending] + → 200 + subject → [authenticated] + → 401 → [unauthenticated] + → 그 밖·시간 초과 → 그대로 recovery-pending. "세션 복구" 버튼이 다시 묻는다 + +읽기 요청 (SESSION_COOKIE_READ) → 쿠키만 +쓰기 요청 (SESSION_COOKIE_WRITE) → 쿠키 + X-XSRF-TOKEN: +서버 401 → [unauthenticated] +``` + +- CSRF: 다른 사이트가 사용자의 쿠키로 쓰기를 보내는 공격이다. 백엔드는 스크립트가 읽을 수 있는 `XSRF-TOKEN` 쿠키를 주고, 쓰기 요청의 `X-XSRF-TOKEN` 헤더가 그 값과 같은지 본다. 다른 사이트의 스크립트는 이 쿠키를 읽지 못한다. +- 백엔드는 plain 방식이다(`CsrfTokenRequestAttributeHandler`). 쿠키 값을 그대로 헤더에 넣는다. + +### 4.1 백엔드에 엔드포인트 셋을 더한다 + +백엔드 템플릿의 운영 코드에는 로그인·로그아웃·세션 조회 엔드포인트가 없다. 테스트 픽스처(`SecurityModeWebContractTest.java`의 `/csrf`, `/login-test`, `/whoami`)만 있다. 그래서 recipe는 이 셋의 주소를 기본값 없이 받는다. + +- **세션 조회 (GET)**: 로그인했으면 200과 subject, 아니면 401. + - subject: 사용자마다 다르고 바뀌지 않는 불투명한 id다. 토큰이나 이메일을 쓰지 않는다. + - 이 엔드포인트가 CSRF 토큰을 읽어야 한다(Spring이면 `CsrfToken.getToken()`). Spring Security는 6부터 GET 요청에서 토큰을 읽을 때까지 `XSRF-TOKEN` 쿠키를 쓰지 않는다. +- **로그아웃 (POST)**: 세션을 끝낸다. CSRF 헤더가 필요하다. +- **로그인**: 로그인 화면 POST든 `oauth2Login` 리다이렉트든 제품이 정한다. 끝나면 페이지가 `recover()`를 불러 owner가 세션을 다시 묻게 한다. + +### 4.2 인증 프로필 두 개를 더한다 + +`cookie-session-owner.ts`의 `SESSION_COOKIE_AUTH_PROFILES` 두 행을 `src/contracts/product-contracts.ts`의 `PRODUCT_REST_AUTH_PROFILES`에 그대로 옮겨 적는다. + +- import하지 않고 옮겨 적는 이유: `src/contracts`는 `src/bootstrap`을 import하지 못한다(`check:architecture`의 `contracts-do-not-know-presentation-or-bootstrap`). +- 읽기 operation은 `SESSION_COOKIE_READ`, 쓰기 operation은 `SESSION_COOKIE_WRITE`를 `frontend.authProfileId`에 적는다. +- `SESSION_COOKIE_WRITE`는 `x-xsrf-token`을 요구한다. 쿠키가 없으면 executor가 요청을 하나도 보내지 않고 `AUTH_INTEGRATION_FAILURE`로 닫는다. + +### 4.3 owner와 provider를 돌려준다 + +recipe를 `src/bootstrap/` 아래로 복사한 뒤 `src/bootstrap/product-composition.ts`: + +```ts +import { + createCookieSessionOwner, + createSessionCookieCredentialProviders, +} from "./cookie-session-owner.ts"; + +export function composeProductSessionOwner( + context: ProductSessionOwnerContext, +): ProductSessionOwner { + const api = new URL(context.config.API_BASE_URL); + return createCookieSessionOwner({ + sessionUrl: new URL("api/session", api).href, + signOutUrl: new URL("api/session/sign-out", api).href, + // 백엔드 Envelope: { success: true, data: { subject } } + subjectFrom: (body) => { + const data = (body as { data?: { subject?: unknown } } | null)?.data; + return typeof data?.subject === "string" ? data.subject : null; + }, + beginSignIn: async () => context.page.assign(new URL("/login", context.page.href()).href), + fetch: context.fetch, + readCookie: context.readCookie, + }); +} + +export function composeProduct(context: ProductCompositionContext) { + return { + capabilities: {}, + credentialProviders: createSessionCookieCredentialProviders({ + readCookie: context.readCookie, + }), + } satisfies ProductComposition; +} +``` + +- 위 경로(`api/session` 등)는 예시다. 4.1에서 만든 엔드포인트 주소를 쓴다. +- provider는 세션 상태를 묻지 않는다. 쿠키가 증명이고 서버가 판정한다. 서버의 401은 owner에게 간다. + +### 4.4 페이지와 API는 같은 host여야 한다 + +- `XSRF-TOKEN` 쿠키는 그 쿠키를 준 host에서만 스크립트가 읽는다. 페이지 host와 API host가 다르면 쓰기가 늘 실패한다. +- 운영: 프록시 하나 뒤에 페이지와 API를 같은 origin으로 둔다. +- local: 쿠키는 포트를 가리지 않는다. 그래서 `localhost:3000`의 페이지가 `localhost:8080`이 준 쿠키를 읽는다. 백엔드 local 프로필은 CORS `allow-credentials: true`다. +- 백엔드는 세션 쿠키를 `Secure`로만 준다. 브라우저가 `http://localhost`를 안전한 출처로 볼 때만 저장된다. 저장되지 않으면 https 개발 서버를 쓴다. + +--- + +## 5. owner가 지킬 상태 전이 + +정본: `src/application/ports/auth-session-port.ts`의 `SessionState`와 `SessionGateway.recover` 주석. 두 recipe 모두 이를 따른다. + +| `recover()` 답 | 답할 때의 상태 | +|---|---| +| `"restored"` | `authenticated`, subject 있음 | +| `"no-session"` | `unauthenticated` (또는 `integration-failed`). `recovery-pending`이 아니다 | +| reject | 바꾸지 않는다. 사용자가 다시 시도한다 | + +- 같은 사용자의 토큰 갱신은 상태도 subject도 바꾸지 않는다. 바꾸면 서버 상태 캐시가 비워진다. +- 계약을 어기고 `"no-session"` 뒤에도 `recovery-pending`이면 화면은 owner가 다시 알릴 때까지 로그인 버튼을 보인다. + +--- + +## 6. 확인 + +- `corepack pnpm test:recipes`: 두 recipe의 단위 테스트와, 템플릿 조립 루트에 실제로 붙인 테스트(`tests/recipes/session-owners-runtime.test.ts`). +- 아직 없는 것: 실제 Keycloak·Redis session 백엔드에 붙인 e2e. 처음 붙일 때 손으로 확인한다. + - `jwt`: 로그인 한 번, `EXTERNAL_BEARER` operation 한 번이 200. + - `redis-session`: 로그인 한 번, `SESSION_COOKIE_WRITE` operation 한 번이 성공하고 요청에 `X-XSRF-TOKEN`이 있다. + +--- + +## 7. 틀리면 + +- **"로그인 연동이 필요합니다"** (`integration-failed`) + - `AUTH_MODE`가 `external`인데 `composeProductSessionOwner`가 `null`을 돌려준다. + - OIDC 설정이 틀렸다: `OIDC_ISSUER`·`OIDC_CLIENT_ID`가 비었다, 원격 issuer가 HTTP다, `apiOrigins`가 origin이 아니다, `redirectStorage`가 없다. +- **Keycloak이 `Invalid parameter: redirect_uri`를 보인다**: client `redirectUris`에 앱 기본 주소가 없다. +- **토큰 교환에서 CORS 오류**: client `webOrigins`에 앱 origin이 없다. +- **로그인했는데 API가 401**: 백엔드 응답의 `error.code`를 본다(목록: `clean-architecture-backend-template/src/adapter/inbound/web/README.md`의 `SecurityErrorClassifier`). + - `AUTH_AUDIENCE_MISMATCH`: 3.1의 audience mapper가 없다. + - `AUTH_ISSUER_MISMATCH`: `OIDC_ISSUER`와 `APP_SECURITY_JWT_ISSUER`가 다르다. 컨테이너 안의 백엔드는 `localhost`로 Keycloak에 닿지 못한다는 점도 본다(백엔드 `application-local.yml` 주석). + - `AUTH_JWKS_UNAVAILABLE` (503): 백엔드가 Keycloak에 닿지 못한다. +- **401 뒤 바로 로그아웃된다**: refresh token이 없거나(client 설정), 갱신한 토큰도 401이다. 후자는 갱신으로 풀리지 않는 거부(audience, issuer)다. +- **부팅 뒤 계속 "세션을 복구하고 있습니다"** (쿠키 모드): 세션 엔드포인트가 응답하지 않거나 200·401 말고 다른 status를 준다. +- **쓰기가 `AUTH_INTEGRATION_FAILURE`이고 요청이 0번** (쿠키 모드): `XSRF-TOKEN` 쿠키가 없다. 세션 엔드포인트가 CSRF 토큰을 읽지 않았거나, 페이지와 API host가 다르다. +- **쓰기가 403** (쿠키 모드): 헤더 값이 쿠키와 다르거나, 백엔드가 `APP_SESSION_CSRF_HEADER_NAME`을 바꿨다. 바꿨다면 프로필과 provider의 헤더 이름을 같이 바꾼다. 템플릿이 허용하는 이름은 `x-xsrf-token`, `x-csrf-token`이다(`src/contracts/rest-profiles.ts`의 `CREDENTIAL_HEADER_NAMES`). diff --git a/docs/manual/README.md b/docs/manual/README.md index 5c61e1be..8550e843 100644 --- a/docs/manual/README.md +++ b/docs/manual/README.md @@ -21,6 +21,7 @@ README (이 문서) → 01 작업 순서 (처음부터 끝까지 한 번) → 02 결정표 (단계 중 "무엇을 고를지" 막힐 때) → 03 기능 폴더 밖 파일 (폴더 밖을 고쳐야 할 때) + → 04 짝 백엔드에 처음 붙이기 (로그인이 필요한 API를 처음 부를 때) → reference/ (명령 인자, 전역 ID, 패턴, 오류 메시지를 찾아볼 때) ``` @@ -29,6 +30,7 @@ README (이 문서) | [`01-add-a-feature.md`](01-add-a-feature.md) | 0~11단계. 단계마다 정할 것, 판단 기준, 잡는 검사와 못 잡는 것, 쓸 스킬 | | [`02-decision-tables.md`](02-decision-tables.md) | context 경계, 계약 출처, 재시도 의미, 결과 불명, 인증, 페이지 템플릿 | | [`03-outside-feature-folder.md`](03-outside-feature-folder.md) | 기능 폴더 밖 파일. 생성 명령이 하는 것과 사람이 하는 것 | +| [`04-paired-backend-session.md`](04-paired-backend-session.md) | 짝 백엔드의 두 인증 모드(JWT·Keycloak, Redis session)에 맞는 세션 owner를 붙이는 법 | | [`reference/create-feature.md`](reference/create-feature.md) | `create:feature`의 인자, 만드는 파일, 거부 조건, 출력 | | [`reference/global-ids.md`](reference/global-ids.md) | 전역 ID 종류, 생성 명령이 만드는 값, 유일성 검사 | | [`reference/patterns.md`](reference/patterns.md) | 기능 개발 패턴과 예제 위치. 예제가 없는 패턴은 "없음" |