diff --git a/.dependency-cruiser.json b/.dependency-cruiser.json index 7621ddf7..60714add 100644 --- a/.dependency-cruiser.json +++ b/.dependency-cruiser.json @@ -300,7 +300,7 @@ }, { "name": "feature-and-app-roots-do-not-reach-adapters", - "comment": "12-03. The graph checks one edge at a time, so a module that presentation may import must not re-export a concrete adapter: presentation would then reach it with every direct rule passing. That covers every file under src/features outside a feature's adapters/ folder (the root files, and any folder that is not a layer, such as support/: 0929/12-03), src/contexts and src/apps. Inside a feature, only its adapters/ folder reaches src/adapters; the product composes adapters in bootstrap. Exception: src/features/feature-adapter-contribution.ts imports the InstalledHttpOperationExecutor type that bootstrap hands to feature adapters (type only). Owner: frontend-platform. Revisit when that type moves to an application port.", + "comment": "12-03. The graph checks one edge at a time, so a module that presentation may import must not re-export a concrete adapter: presentation would then reach it with every direct rule passing. That covers every file under src/features outside a feature's adapters/ folder (the root files, and any folder that is not a layer, such as support/: 0929/12-03), src/contexts and src/apps. Inside a feature, only its adapters/ folder reaches src/adapters; the product composes adapters in bootstrap. Exception: src/features/feature-adapter-contribution.ts imports the adapter types of the capabilities it declares, InstalledHttpOperationExecutor and the opt-in FileserverUploadClientDependencies (type only, 1112/09-01). Owner: frontend-platform. Revisit when that type moves to an application port.", "severity": "error", "from": { "path": "^src/(features/|contexts/|apps/)", diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 529fbabf..311349ba 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -445,77 +445,74 @@ export function mapInvoiceCreateProblem( - client는 스스로 다시 보내지 않는다. `retryable: true`이고 `retryAfterMs`가 있으면 그만큼 기다린 뒤 기능이 다시 부른다. 서버가 상한(`maxRetryAfterMs`, 기본 30초)보다 길게 기다리라고 하면 `retryable: false`다. - `MAYBE_APPLIED`는 언제나 `retryable: false`다. 백엔드가 Envelope에 `retryable: true`와 `Retry-After`를 붙여도(504 `TRANSFER_TIMEOUT`) 기능이 자동으로 다시 부르지 않는다. 아래 주의대로 먼저 확인한다. -**주의 — 멱등 키**: 짝 백엔드(`45d2a478`)의 `POST /v1/files`는 멱등 키를 읽지 않는다(업로드 use case가 `NOT_IDEMPOTENT`). +**주의 — 멱등 키**: 짝 백엔드(pin `d32b4b53`)의 `POST /v1/files`는 멱등 키를 읽지 않는다(업로드 use case가 `NOT_IDEMPOTENT`). - 그래서 `MAYBE_APPLIED` 뒤 다시 보내면 같은 파일이 두 개 생길 수 있다. - 같은 키 재전송이 중복을 막는 것은 배포가 업로드를 백엔드 멱등성 executor 뒤에 둘 때뿐이다. - 그 전에는 다시 보내기 전에 업무 데이터(파일 목록 등)로 먼저 확인한다. -**어디에 적나**: 두 곳이다. +**어디에 적나**: 두 곳이다. 템플릿 파일은 고치지 않는다. -1. `src/bootstrap/product-composition.ts`: client를 만들 재료(주소, 인증 프로필, 자격 증명, 크기 상한)를 capability로 넘긴다. client 코드는 넘기지 않는다. 기능 adapter는 기능 runtime과 함께 늦게 적재되므로, 업로드 코드가 boot 번들이 아니라 기능 chunk에 든다. -2. 기능 `adapters/create--feature-input.ts`: `needs`에 그 capability를 적고, 거기서 `createFileserverUploadClient`를 부른다. +1. `src/bootstrap/product-composition.ts`: client를 만들 재료(주소, 인증 프로필, 자격 증명, 크기 상한)를 capability `fileserverUpload`로 넘긴다. client 코드는 넘기지 않는다. 기능 adapter는 기능 runtime과 함께 늦게 적재되므로, 업로드 코드가 boot 번들이 아니라 기능 chunk에 든다. + - 그 타입은 템플릿이 `FeaturePlatformCapabilities`에 opt-in 키로 선언해 두었다(`src/features/feature-adapter-contribution.ts`, `indexedDb`와 같다). `declare module`로 보강하지 않는다. `check:types:node`가 그 보강을 보지 못한다(매뉴얼 03). + - 자격 증명은 `context.credentials`를 펼친다. V3 요청과 같은 주인(scope fence → ANONYMOUS 프로필 → `credentialProviders` → 템플릿 세션)이 헤더를 붙이고, 업로드의 401도 V3 401과 같은 곳(제품 provider의 자격 증명이면 `onCredentialRejected`, 템플릿 세션의 것이면 세션)으로 간다. +2. 기능 `adapters/`: `create--feature-input.ts`의 `needs`에 `fileserverUpload`를 더하고, 받은 값으로 `createFileserverUploadClient`를 부른다. + ```ts -// src/bootstrap/product-composition.ts (제품 소유). BACKEND_SESSION은 -// src/contracts/product-contracts.ts에 더한 쿠키 세션 프로필이다. -import type { FileserverUploadClientDependencies } from "../adapters/http/index.ts"; -import { PRODUCT_REST_AUTH_PROFILES } from "../contracts/product-contracts.ts"; -// 파일에 이미 있는 import에 ProductCredentialProvider를 더한다. -import type { ProductCredentialProvider } from "./product-composition-contract.ts"; +// JWT·Keycloak 모드(템플릿 세션의 bearer, EXTERNAL_BEARER)의 예다. +import { REST_AUTH_PROFILES } from "../contracts/rest-profiles.ts"; +import type { + ProductComposition, + ProductCompositionContext, + ProductSessionOwner, + ProductSessionOwnerContext, +} from "./product-composition-contract.ts"; -declare module "../features/feature-adapter-contribution.ts" { - interface FeaturePlatformCapabilities { - readonly fileserverUpload: FileserverUploadClientDependencies; - } +export function composeProductSessionOwner( + context: ProductSessionOwnerContext, +): ProductSessionOwner { + return null; } export function composeProduct(context: ProductCompositionContext) { - const sessionCredentials: ProductCredentialProvider = () => { - if (!context.isScopeReady()) return { kind: "SCOPE_FENCED" }; - const csrf = context.readCookie("XSRF-TOKEN"); - return csrf === undefined - ? { kind: "UNAUTHENTICATED" } - : { kind: "READY", headers: { "x-xsrf-token": csrf } }; - }; return { capabilities: { fileserverUpload: { + ...context.credentials, baseUrl: context.config.API_BASE_URL, - authProfile: PRODUCT_REST_AUTH_PROFILES.BACKEND_SESSION, - attachCredentials: sessionCredentials, + authProfile: REST_AUTH_PROFILES.EXTERNAL_BEARER, maxFileBytes: 20 * 1024 * 1024, ...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }), }, }, - credentialProviders: { BACKEND_SESSION: sessionCredentials }, - // BACKEND_SESSION은 세션 쿠키 그 자체다. 그 401은 세션을 로그아웃시킨다(5절). - onCredentialRejected: () => context.notifySessionUnauthenticated(), + credentialProviders: {}, } satisfies ProductComposition; } ``` + ```ts -// src/features//adapters/create--feature-input.ts -import { createFileserverUploadClient } from "../../../adapters/http/index.ts"; -import { defineFeatureAdapterContribution } from "../../feature-adapter-contribution.ts"; +import { + createFileserverUploadClient, + type FileserverUploadClient, +} from "../../../adapters/http/index.ts"; +import type { FeatureCapabilitySelection } from "../../feature-adapter-contribution.ts"; -export const createAttachmentFeatureInput = defineFeatureAdapterContribution({ - featureId: "attachment", - needs: ["http", "fileserverUpload"], - createInput: ({ http, fileserverUpload }) => { - const uploads = createFileserverUploadClient(fileserverUpload); - return { - featureId: "attachment", - // 기능 port 구현이 uploads.upload({ source, filename, mediaType, idempotencyKey, signal })를 부른다. - input: { /* … */ }, - }; - }, -}); +// create-invoice-feature-input.ts가 needs: ["http", "fileserverUpload"]로 받은 값을 넘긴다. +// 기능 port 구현이 uploads.upload({ source, filename, mediaType, idempotencyKey, signal })를 부른다. +export function createInvoiceAttachmentUploads({ + fileserverUpload, +}: FeatureCapabilitySelection<["fileserverUpload"]>): FileserverUploadClient { + return createFileserverUploadClient(fileserverUpload); +} ``` +- 이 두 조각도 `tests/unit/manual-code-blocks.test.ts`가 저장소 사본에 넣어 타입 검사한다. `product-composition.ts`는 제품 소유 파일이라 조각이 파일 전체를 바꾼다. +- 쿠키 세션 모드(Redis session, BFF)는 `authProfile`을 `src/contracts/product-contracts.ts`에 더한 쿠키 프로필(예: `BACKEND_SESSION`)로 바꾸고, `credentialProviders`에 그 프로필의 provider(XSRF 쿠키를 헤더로 붙이는 함수)를 둔다. `context.credentials`가 그 provider를 부른다. 그 provider는 세션 쿠키 자체를 보내므로 `onCredentialRejected: () => context.notifySessionUnauthenticated()`로 401을 세션에 알린다(5절). +- `context.credentials`를 펼치지 않고 `attachCredentials`만 직접 주면 업로드의 401이 아무에게도 가지 않는다. 화면은 로그인 상태로 남고 업로드만 `AUTH_REQUIRED`로 실패한다(매뉴얼 04). - `baseUrl`은 끝이 `/`여야 한다. `v1/files`를 그 아래에 붙인다. 경로가 base 밖으로 나가면 조립할 때 `TypeError`다. -- 자격 증명 함수는 V3 실행기의 `attachCredentials`와 계약이 같다. 같은 프로필의 `credentialProviders`를 그대로 쓴다. 프로필이 허락하지 않은 헤더를 주면 보내지 않고 `AUTH_INTEGRATION_FAILURE`다. +- 자격 증명 함수는 V3 실행기의 `attachCredentials`와 계약이 같다. 프로필이 허락하지 않은 헤더를 주면 보내지 않고 `AUTH_INTEGRATION_FAILURE`다. **틀리면** diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index 16e92bd7..18b69456 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -117,6 +117,7 @@ release admission refused for staging: - `tests/e2e/accessibility.spec.ts`: 기능마다 고치지 않는다. 경로 파라미터와 API 응답을 설치된 라우트·descriptor에서 만든다. 보호 페이지가 설치된 GET이 아닌 요청을 그리기 전에 보낼 때만 손본다. 자세한 동작은 [01 문서 6단계](01-add-a-feature.md#6단계-라우트). - `src/features/product-capabilities.ts`: `needs`에 템플릿이 만들지 않는 capability를 적었을 때. 그 capability의 타입을 `ProductFeaturePlatformCapabilities`에 적는다. - `product-composition.ts` 안에서 `FeaturePlatformCapabilities`를 보강(`declare module`)하면 `check:types:node`가 그 키를 보지 못한다. + - 템플릿이 타입만 선언한 opt-in 키(`indexedDb`, 짝 백엔드 업로드 `fileserverUpload`)는 여기 다시 적지 않는다. `product-composition.ts`에서 값만 돌려준다([02 결정표 7절](02-decision-tables.md#7-파일-업로드)). - `src/bootstrap/product-composition.ts`: 위 capability의 값을 돌려줄 때. 제품 인증 프로필의 자격 증명도 여기서 준다. - 로그아웃·계정 전환 때 닫아야 하는 것(파일 runtime 등)은 `scopeParticipants`로 돌려준다. 예제: `recipes/frontend-capabilities/browser-file-session-capability.ts`. - `label`은 `browser-files` 같은 소문자 kebab-case 토큰으로 쓴다. 다른 형식이면 조립이 `TypeError`로 멈춘다. diff --git a/docs/manual/04-paired-backend-session.md b/docs/manual/04-paired-backend-session.md index 9a9b6b2c..242125bc 100644 --- a/docs/manual/04-paired-backend-session.md +++ b/docs/manual/04-paired-backend-session.md @@ -189,6 +189,7 @@ export function composeProductSessionOwner( ``` - 서버 401이 세션에 닿는 길은 4.3의 `onCredentialRejected` 한 줄뿐이다. 템플릿은 제품 provider가 낸 자격 증명의 401을 제품에만 알린다([02 결정표](02-decision-tables.md) 5절). 이 줄을 빼면 서버 세션이 끝나도(Redis TTL 만료, 다른 탭·서버에서 로그아웃) 화면은 로그인 상태로 남고, 요청마다 `AUTH_REQUIRED` 실패 화면만 보인다. +- Fileserver 업로드처럼 제품이 직접 보내는 요청도 같은 길을 쓴다. 업로드 capability에 `context.credentials`를 펼치면 그 401도 `onCredentialRejected`로 간다([02 결정표](02-decision-tables.md) 7절). - CSRF: 다른 사이트가 사용자의 쿠키로 쓰기를 보내는 공격이다. 백엔드는 스크립트가 읽을 수 있는 `XSRF-TOKEN` 쿠키를 주고, 쓰기 요청의 `X-XSRF-TOKEN` 헤더가 그 값과 같은지 본다. 다른 사이트의 스크립트는 이 쿠키를 읽지 못한다. - 백엔드는 plain 방식이다(`CsrfTokenRequestAttributeHandler`). 쿠키 값을 그대로 헤더에 넣는다. diff --git a/src/adapters/http/fileserver-upload.ts b/src/adapters/http/fileserver-upload.ts index 5e21d39d..e89cf374 100644 --- a/src/adapters/http/fileserver-upload.ts +++ b/src/adapters/http/fileserver-upload.ts @@ -143,6 +143,16 @@ export type FileserverUploadClientDependencies = Readonly<{ }>, context: AuthOperationContext, ): Promise | CredentialPatchOutcome; + /** + * 1112/07-01. Called once when the server answers an upload 401, with the + * operation and the profile, before the `AUTH_REQUIRED` failure returns. + * The V3 executor's 401 goes to whoever supplied the credential; pass the + * composition's `credentials` (both fields) so the upload's goes the same + * way. A throw is ignored. + */ + onUnauthenticated?( + binding: Readonly<{ operationId: string; authProfileId: string }>, + ): void; /** A larger file is refused before it is read. */ maxFileBytes: number; fetcher?: typeof fetch; @@ -320,6 +330,7 @@ type Settings = Readonly<{ url: string; authProfile: RestAuthProfile; attachCredentials: FileserverUploadClientDependencies["attachCredentials"]; + onUnauthenticated: FileserverUploadClientDependencies["onUnauthenticated"]; maxFileBytes: number; timeoutMs: number; minTransferBytesPerSecond: number; @@ -363,6 +374,12 @@ function snapshotDependencies( if (typeof dependencies.attachCredentials !== "function") { invalid("attachCredentials"); } + if ( + dependencies.onUnauthenticated !== undefined && + typeof dependencies.onUnauthenticated !== "function" + ) { + invalid("onUnauthenticated"); + } const positive = (value: number | undefined, fallback: number, field: string) => { const resolved = value ?? fallback; return Number.isSafeInteger(resolved) && resolved > 0 @@ -377,6 +394,7 @@ function snapshotDependencies( requiredCredentialHeaders: Object.freeze([...profile.requiredCredentialHeaders]), }), attachCredentials: dependencies.attachCredentials, + onUnauthenticated: dependencies.onUnauthenticated, maxFileBytes: positive(dependencies.maxFileBytes, 0, "maxFileBytes"), timeoutMs: positive(dependencies.timeoutMs, DEFAULTS.timeoutMs, "timeoutMs"), minTransferBytesPerSecond: positive( @@ -608,6 +626,19 @@ async function credentialHeaders( } } +function reportUnauthenticated(settings: Settings): void { + try { + settings.onUnauthenticated?.( + Object.freeze({ + operationId: FILESERVER_UPLOAD_OPERATION_ID, + authProfileId: settings.authProfile.authProfileId, + }), + ); + } catch { + // A hook defect cannot change the upload's own outcome. + } +} + async function readAnswer( response: Response, attempt: AbortableOperation, @@ -616,6 +647,9 @@ async function readAnswer( sentBytes: number, ): Promise> { const status = response.status; + // 1112/07-01. The server's verdict on the credential this upload carried, + // whatever the body says, as a V3 401 is. + if (status === 401) reportUnauthenticated(settings); const created = status === 201 || status === 202; // A 2xx the contract does not list says something happened; what is unknown. const effect: FailureEffectCertainty = created diff --git a/src/bootstrap/product-composition-contract.ts b/src/bootstrap/product-composition-contract.ts index ac34414c..7d39f85c 100644 --- a/src/bootstrap/product-composition-contract.ts +++ b/src/bootstrap/product-composition-contract.ts @@ -78,6 +78,27 @@ export type TemplatePlatformCapabilityId = "http" | "telemetry"; export type ProductCredentialProvider = ContractHttpExecutorDependencies["attachCredentials"]; +/** + * 1112/07-01. The template's own credentials for a request the product sends + * itself rather than through `http`, such as a Fileserver upload + * (`FileserverUploadClientDependencies`): spread it into that capability. + * + * - `attachCredentials` decides as the V3 executor's does: the scope fence, + * then the ANONYMOUS profile, then `credentialProviders`, then the template + * session (an `EXTERNAL_BEARER` upload gets the session owner's bearer this + * way), then the fence again. + * - `onUnauthenticated` takes the server's 401 to that request the same way + * a V3 401 goes: to `onCredentialRejected` for a product provider's + * credential, to the template session for its own, to nobody for an + * ANONYMOUS one. + */ +export type ProductRequestCredentials = Readonly<{ + attachCredentials: ProductCredentialProvider; + onUnauthenticated( + binding: Readonly<{ operationId: string; authProfileId: string }>, + ): void; +}>; + export type ProductCompositionContext = Readonly<{ /** Validated runtime config, product keys included. */ config: RuntimeConfig; @@ -98,6 +119,11 @@ export type ProductCompositionContext = Readonly<{ * credential is not the session's, such as another API's token. */ notifySessionUnauthenticated(): void; + /** + * 1112/07-01. Call it per request: called while `composeProduct` runs it + * throws a `TypeError`. + */ + credentials: ProductRequestCredentials; }>; /** diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 5923f0ef..6b3d1ebe 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -68,6 +68,7 @@ import { } from "./product-composition.ts"; import type { ProductComposition, + ProductCredentialProvider, ProductScopeParticipant, } from "./product-composition-contract.ts"; import { createProductSessionOwnerContext } from "./product-session-owner-context.ts"; @@ -535,60 +536,83 @@ export async function createRuntimeAdapters( diagnostics, telemetry, }); - const contractHttp = createRuntimeContractHttpExecutor(config, { - fetcher: context.fetcher, - async attachCredentials(operation, authContext) { + /** + * 1112/02-10. Who supplies the credential of an auth profile, and so who + * hears the server's 401 to it. `attachCredentials` and + * `reportServerUnauthenticated` both read this one decision. 09-01: an + * ANONYMOUS profile admits no credential header at all, so nobody supplies + * one. 09-02: a product provider answers for its own profiles before the + * session. Every other profile needs the session and never downgrades to + * anonymous. `productCredentialProviders` is set below, before any request + * can run. + */ + let productComposed = false; + function credentialOwner(authProfileId: string): "NONE" | "PRODUCT" | "SESSION" { + // `context.credentials` is for requests: called while `composeProduct` + // runs, the provider table does not exist yet. + if (!productComposed) { + throw new TypeError( + "context.credentials is called per request, not while composeProduct runs.", + ); + } + if (INSTALLED_REST_AUTH_PROFILES.get(authProfileId)?.transport === "ANONYMOUS") { + return "NONE"; + } + return Object.hasOwn(productCredentialProviders, authProfileId) + ? "PRODUCT" + : "SESSION"; + } + const attachCredentials: ProductCredentialProvider = async ( + operation, + authContext, + ) => { + // Decided first (it reads no state); nothing is asked before the fence. + const owner = credentialOwner(operation.authProfileId); + if (serverStateScope.getPhase() !== "READY") { + return Object.freeze({ kind: "SCOPE_FENCED" as const }); + } + if (owner === "NONE") { + return Object.freeze({ kind: "READY" as const, headers: {} }); + } + // A throw is left to the executor, which closes it as + // CREDENTIAL_OWNER_FAILED. + if (owner === "PRODUCT") { + const provider = productCredentialProviders[operation.authProfileId]; + const answer = await provider(operation, authContext); + return serverStateScope.getPhase() === "READY" + ? answer + : Object.freeze({ kind: "SCOPE_FENCED" as const }); + } + const state = authSession.getState(); + if (state === "integration-failed") { + return Object.freeze({ kind: "UNAVAILABLE" as const }); + } + if (state !== "authenticated") { + return Object.freeze({ kind: "UNAUTHENTICATED" as const }); + } + try { + const patch = await authSession.credentialPatch( + { + origin: new URL(config.API_BASE_URL).origin, + method: operation.method, + operationId: operation.operationId, + }, + authContext, + ); if (serverStateScope.getPhase() !== "READY") { return Object.freeze({ kind: "SCOPE_FENCED" as const }); } - // 09-01. The operation's installed profile decides first, the session - // second. An ANONYMOUS profile admits no credential header at all, so it - // goes out bare in every session state and never reaches the owner. Every - // other profile still needs a session and never downgrades to anonymous. - if ( - INSTALLED_REST_AUTH_PROFILES.get(operation.authProfileId)?.transport === - "ANONYMOUS" - ) { - return Object.freeze({ kind: "READY" as const, headers: {} }); - } - // 09-02. A product provider answers for its own profiles, between the - // checks above and the session. A throw is left to the executor, which - // closes it as CREDENTIAL_OWNER_FAILED. `productCredentialProviders` is - // set below, before any request can run. - if (Object.hasOwn(productCredentialProviders, operation.authProfileId)) { - const provider = productCredentialProviders[operation.authProfileId]; - const answer = await provider(operation, authContext); - return serverStateScope.getPhase() === "READY" - ? answer - : Object.freeze({ kind: "SCOPE_FENCED" as const }); - } - const state = authSession.getState(); - if (state === "integration-failed") { - return Object.freeze({ kind: "UNAVAILABLE" as const }); - } - if (state !== "authenticated") { - return Object.freeze({ kind: "UNAUTHENTICATED" as const }); - } - try { - const patch = await authSession.credentialPatch( - { - origin: new URL(config.API_BASE_URL).origin, - method: operation.method, - operationId: operation.operationId, - }, - authContext, - ); - if (serverStateScope.getPhase() !== "READY") { - return Object.freeze({ kind: "SCOPE_FENCED" as const }); - } - return Object.freeze({ - kind: "READY" as const, - headers: patch.headers, - }); - } catch { - return Object.freeze({ kind: "UNAVAILABLE" as const }); - } - }, + return Object.freeze({ + kind: "READY" as const, + headers: patch.headers, + }); + } catch { + return Object.freeze({ kind: "UNAVAILABLE" as const }); + } + }; + const contractHttp = createRuntimeContractHttpExecutor(config, { + fetcher: context.fetcher, + attachCredentials, observe: observeHttpExecution, }); // 15-01. Filled one feature at a time as feature runtimes load; an @@ -597,21 +621,24 @@ export async function createRuntimeAdapters( const contractRegistry = createInstalledContractRegistry(); /** * 1103/09-01. A 401 judges the credential the request carried, so it goes to - * whoever supplied it, decided in the same order as `attachCredentials`. An - * ANONYMOUS request carried none: nobody is told. A product provider's - * credential: the product is told, the session is not. Only the session's - * own credential signs the session out. + * whoever supplied it (`credentialOwner`). An ANONYMOUS request carried + * none: nobody is told. A product provider's credential: the product is + * told, the session is not. Only the session's own credential signs the + * session out. */ function reportServerUnauthenticated( - authProfileId: string, binding: Readonly<{ operationId: string; authProfileId: string }>, ): void { - if (INSTALLED_REST_AUTH_PROFILES.get(authProfileId)?.transport === "ANONYMOUS") { - return; - } - if (Object.hasOwn(productCredentialProviders, authProfileId)) { + const owner = credentialOwner(binding.authProfileId); + if (owner === "NONE") return; + if (owner === "PRODUCT") { try { - onProductCredentialRejected?.(Object.freeze(binding)); + onProductCredentialRejected?.( + Object.freeze({ + operationId: binding.operationId, + authProfileId: binding.authProfileId, + }), + ); } catch { // A product hook defect cannot change the contract execution outcome. } @@ -673,7 +700,7 @@ export async function createRuntimeAdapters( // dispatch for lack of a credential carries no response metadata; telling // the owner would overwrite a recovering session and re-fence the scope. if (outcome.kind === "UNAUTHENTICATED" && outcome.metadata !== undefined) { - reportServerUnauthenticated(executableContract.frontend.authProfileId, { + reportServerUnauthenticated({ operationId: executableContract.contract.operationId, authProfileId: executableContract.frontend.authProfileId, }); @@ -703,12 +730,19 @@ export async function createRuntimeAdapters( // credential: the verdict reportServerUnauthenticated gives the session's // own 401. notifySessionUnauthenticated: () => authSession.onUnauthenticated(), + // 1112/07-01. The same owner and 401 routing for a request the product + // sends itself, such as a Fileserver upload. + credentials: Object.freeze({ + attachCredentials, + onUnauthenticated: reportServerUnauthenticated, + }), }) satisfies ProductComposition; // Read through the contract type: the product's own return type omits the // optional fields when the product does not use them, and `product` keeps // its narrow type above so a missing capability still fails the typecheck. const productContract: ProductComposition = product; const productCredentialProviders = productContract.credentialProviders; + productComposed = true; const onProductCredentialRejected = productContract.onCredentialRejected; for (const participant of productContract.scopeParticipants ?? []) { // 1105/02-01. The label names the participant in diagnostics, so it must diff --git a/src/features/feature-adapter-contribution.ts b/src/features/feature-adapter-contribution.ts index 40dcbb85..4d6a9af7 100644 --- a/src/features/feature-adapter-contribution.ts +++ b/src/features/feature-adapter-contribution.ts @@ -3,6 +3,7 @@ import type { ApplicationFeatureInputs, } from "../application/ports/in/application-api.ts"; import type { + FileserverUploadClientDependencies, InstalledHttpOperationExecutor, } from "../adapters/http/index.ts"; import type { TelemetryPort } from "../platform/telemetry/telemetry-port.ts"; @@ -57,6 +58,16 @@ export interface FeaturePlatformCapabilities extends ProductFeaturePlatformCapabilities { readonly http: InstalledHttpOperationExecutor; readonly indexedDb: IndexedDbRepositoryProvider; + /** + * 1112/09-01. Opt-in like `indexedDb`: the template types it and never + * builds it. A product that uploads to the paired backend's Fileserver + * returns it from `src/bootstrap/product-composition.ts` (manual 02 §7), + * and a feature that lists it in `needs` calls `createFileserverUploadClient` + * with it. Typed here rather than in `product-capabilities.ts`, which this + * file imports: that file reading the type from here would be an import + * cycle. + */ + readonly fileserverUpload: FileserverUploadClientDependencies; /** scale-architecture.md §24. Provider-neutral, bounded, fail-open feature telemetry. */ readonly telemetry: TelemetryPort; } diff --git a/tests/integration/fileserver-upload.test.ts b/tests/integration/fileserver-upload.test.ts index 0c9da0a4..cc5f9dc9 100644 --- a/tests/integration/fileserver-upload.test.ts +++ b/tests/integration/fileserver-upload.test.ts @@ -409,6 +409,38 @@ describe("Fileserver multipart upload — Envelope failures", () => { }, ); + // 1112/07-01. A 401 is the server's verdict on the credential the upload + // carried; the composition hears it through `onUnauthenticated`. + it("tells onUnauthenticated once about a 401, and about nothing else", async () => { + const onUnauthenticated = vi.fn(); + answer({ status: 401, body: failureEnvelope("UNAUTHENTICATED", "AUTH", false) }); + + const result = await client({ onUnauthenticated }).client.upload(upload()); + + expect(result).toMatchObject({ ok: false, error: { kind: "AUTH_REQUIRED" } }); + expect(onUnauthenticated).toHaveBeenCalledExactlyOnceWith({ + operationId: "FILESERVER_UPLOAD", + authProfileId: expect.any(String), + }); + + onUnauthenticated.mockClear(); + answer({ status: 403, body: failureEnvelope("ACCESS_DENIED", "AUTHZ", false) }); + await client({ onUnauthenticated }).client.upload(upload()); + expect(onUnauthenticated).not.toHaveBeenCalled(); + }); + + it("keeps the 401 outcome when onUnauthenticated throws", async () => { + answer({ status: 401, body: failureEnvelope("UNAUTHENTICATED", "AUTH", false) }); + + const result = await client({ + onUnauthenticated: () => { + throw new Error("hook defect"); + }, + }).client.upload(upload()); + + expect(result).toMatchObject({ ok: false, error: { kind: "AUTH_REQUIRED" } }); + }); + it("carries no traceId when the failure Envelope has none", async () => { const envelope = failureEnvelope("STORAGE_UNAVAILABLE", "TRANSIENT_DEPENDENCY", true); answer({ diff --git a/tests/unit/manual-code-blocks.test.ts b/tests/unit/manual-code-blocks.test.ts index dc18a37d..438e4ab8 100644 --- a/tests/unit/manual-code-blocks.test.ts +++ b/tests/unit/manual-code-blocks.test.ts @@ -30,12 +30,22 @@ import { childProcessTimeout } from "../helpers/child-process-timeout.ts"; * well have built `invoice-feature`. So the copy gets the reserved probe * feature instead, and every block and check is renamed to it on the way in * (`renameFeatureText`): paths, constants, types and words alike. + * + * 1112/09-01. A block may also be a whole product-owned file the template + * ships empty, such as the upload composition of manual 02 §7: it replaces + * that file in the copy. */ const MANUAL = "docs/manual"; const FEATURE_ID = MANUAL_PROBE_FEATURE_ID; const toProbe = (text: string) => renameFeatureText(text, MANUAL_EXAMPLE_FEATURE_ID, FEATURE_ID); const CHECKS = "tests/fixtures/manual-code-blocks"; const MARKED_BLOCK = /\n```tsx?\n([\s\S]*?)\n```/gu; +/** Product-owned files a block may replace whole; every other block adds a file. */ +const PRODUCT_OWNED_FILES: ReadonlySet = new Set([ + "src/bootstrap/product-composition.ts", + "src/contracts/product-contracts.ts", + "src/features/product-capabilities.ts", +]); async function manualDocuments(directory: string): Promise { const documents: string[] = []; @@ -90,6 +100,8 @@ describe("docs/manual code blocks, pasted into a generated feature", () => { const targets = [...(await markedBlocks()).keys()].sort(); expect(targets).toEqual([ + "src/bootstrap/product-composition.ts", + "src/features/invoice-feature/adapters/invoice-attachment-uploads.ts", "src/features/invoice-feature/adapters/invoice-problem-mapping.ts", "src/features/invoice-feature/contracts/invoice-list-search.ts", "src/features/invoice-feature/contracts/invoice-problem-details.ts", @@ -114,7 +126,9 @@ describe("docs/manual code blocks, pasted into a generated feature", () => { for (const [target, block] of blocks) { const file = path.join(root, toProbe(target)); // A block adds a file; it never stands in for one the command wrote. - expect(existsSync(file), `${target} exists before the block is pasted`).toBe(false); + expect(existsSync(file), `${target} exists before the block is pasted`).toBe( + PRODUCT_OWNED_FILES.has(target), + ); await mkdir(path.dirname(file), { recursive: true }); await writeFile(file, toProbe(block)); } diff --git a/tests/unit/runtime-adapters-credential-order.test.ts b/tests/unit/runtime-adapters-credential-order.test.ts index f47a84e9..d1210e8b 100644 --- a/tests/unit/runtime-adapters-credential-order.test.ts +++ b/tests/unit/runtime-adapters-credential-order.test.ts @@ -1,7 +1,14 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts"; -import type { ProductCredentialProvider } from "../../src/bootstrap/product-composition-contract.ts"; +import { + createFileserverUploadClient, + type InstalledHttpOperationExecutor, +} from "../../src/adapters/http/index.ts"; +import type { + ProductCompositionContext, + ProductCredentialProvider, +} from "../../src/bootstrap/product-composition-contract.ts"; +import { REST_AUTH_PROFILES } from "../../src/contracts/rest-profiles.ts"; import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts"; import { testRuntimeConfig } from "../helpers/runtime-config.ts"; @@ -22,6 +29,8 @@ const fixture = vi.hoisted(() => ({ http: undefined as InstalledHttpOperationExecutor | undefined, providers: {} as Record, onCredentialRejected: undefined as ((binding: unknown) => void) | undefined, + context: undefined as unknown, + onCompose: undefined as ((context: unknown) => void) | undefined, withProfile( contract: T, operationId: string, @@ -80,13 +89,17 @@ vi.mock("../../src/features/installed-feature-adapters.ts", async (importOrigina /** The product-owned file, filled the way a product fills it. */ vi.mock("../../src/bootstrap/product-composition.ts", () => ({ composeProductSessionOwner: () => null, - composeProduct: () => ({ + composeProduct: (context: unknown) => { + fixture.context = context; + fixture.onCompose?.(context); + return { capabilities: {}, credentialProviders: fixture.providers, ...(fixture.onCredentialRejected === undefined ? {} : { onCredentialRejected: fixture.onCredentialRejected }), - }), + }; + }, })); type Runtime = Parameters[0]["runtime"]; @@ -178,6 +191,8 @@ afterEach(() => { fixture.http = undefined; fixture.providers = {}; fixture.onCredentialRejected = undefined; + fixture.context = undefined; + fixture.onCompose = undefined; }); async function compose( @@ -418,3 +433,168 @@ describe("1103/09-01 a 401 to a product provider's credential", () => { expect(rejected).not.toHaveBeenCalled(); }); }); + +/** + * 1112/02-10, 1112/07-01. Whoever supplies a request's credential hears the + * server's 401 to it, for a V3 request and for an upload the product sends + * through `context.credentials`, one profile kind per row. The two answers + * come from one decision in the composition root; an order changed on one + * side only fails a row here. + */ +describe("1112/02-10 the credential's owner is the 401's owner", () => { + const unauthorized = () => + Response.json( + { + success: false, + error: { code: "UNAUTHENTICATED", category: "AUTH", message: "x", retryable: false }, + meta: { requestId: "req-1" }, + }, + { status: 401 }, + ); + + function uploadSource() { + const bytes = new TextEncoder().encode("file"); + return { + byteLength: bytes.byteLength, + async *stream() { + yield { ok: true as const, value: bytes }; + }, + }; + } + + async function upload( + authProfile: (typeof REST_AUTH_PROFILES)[keyof typeof REST_AUTH_PROFILES], + fetcher: typeof fetch, + ) { + const context = fixture.context as ProductCompositionContext | undefined; + if (!context) throw new Error("The product composition was not called"); + const client = createFileserverUploadClient({ + ...context.credentials, + baseUrl: "http://localhost:8080/", + authProfile, + maxFileBytes: 1024, + fetcher, + }); + return client.upload({ source: uploadSource(), signal: new AbortController().signal }); + } + + const ROWS = [ + { + owner: "nobody, for an ANONYMOUS profile", + providers: {} as Record, + operation: ANONYMOUS_OPERATION, + profile: REST_AUTH_PROFILES.ANONYMOUS, + sentAuthorization: null, + product: 0, + session: 0, + }, + { + owner: "the product, for a provider's profile", + providers: { EXTERNAL_BEARER: productToken }, + operation: PROFILE_OPERATION, + profile: REST_AUTH_PROFILES.EXTERNAL_BEARER, + sentAuthorization: "Bearer product-token", + product: 1, + session: 0, + }, + { + owner: "the session, for its own profile", + providers: {}, + operation: PROFILE_OPERATION, + profile: REST_AUTH_PROFILES.EXTERNAL_BEARER, + sentAuthorization: "Bearer owner-token", + product: 0, + session: 1, + }, + ] as const; + + it.each(ROWS)("V3: $owner", async (row) => { + const owner = externalOwner(); + const session = vi.spyOn(owner, "notifyUnauthenticated"); + const product = vi.fn(); + fixture.providers = row.providers; + fixture.onCredentialRejected = product; + const { http, fetcher } = await compose( + "external", + { __CA_FRONTEND_AUTH_OWNER__: owner }, + unauthorized, + ); + + const outcome = await http.execute(row.operation, { limit: 1 }, { routeId: "TEST_ROUTE" }); + + expect(outcome.kind).toBe("UNAUTHENTICATED"); + expect(new Headers(fetcher.mock.calls[0]?.[1]?.headers).get("authorization")).toBe( + row.sentAuthorization, + ); + expect(product).toHaveBeenCalledTimes(row.product); + expect(session).toHaveBeenCalledTimes(row.session); + }); + + it.each(ROWS)("upload: $owner", async (row) => { + const owner = externalOwner(); + const session = vi.spyOn(owner, "notifyUnauthenticated"); + const product = vi.fn(); + fixture.providers = row.providers; + fixture.onCredentialRejected = product; + await compose("external", { __CA_FRONTEND_AUTH_OWNER__: owner }); + const uploads = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => + unauthorized(), + ); + + const result = await upload(row.profile, uploads as unknown as typeof fetch); + + expect(result).toMatchObject({ ok: false, error: { kind: "AUTH_REQUIRED" } }); + expect(uploads).toHaveBeenCalledOnce(); + expect(new Headers(uploads.mock.calls[0]?.[1]?.headers).get("authorization")).toBe( + row.sentAuthorization, + ); + expect(product).toHaveBeenCalledTimes(row.product); + if (row.product === 1) { + expect(product).toHaveBeenCalledWith({ + operationId: "FILESERVER_UPLOAD", + authProfileId: "EXTERNAL_BEARER", + }); + } + expect(session).toHaveBeenCalledTimes(row.session); + }); + + it("upload: a fenced scope sends nothing, with the session's bearer profile", async () => { + // The demo session's sign-in fences the scope synchronously (row 1 above). + const { adapters } = await compose("demo"); + void adapters.outputPorts.session.beginSignIn(); + const uploads = vi.fn(async () => unauthorized()); + + const result = await upload( + REST_AUTH_PROFILES.EXTERNAL_BEARER, + uploads as unknown as typeof fetch, + ); + + expect(result).toMatchObject({ ok: false, error: { kind: "SCOPE_GENERATION_CHANGED" } }); + expect(uploads).not.toHaveBeenCalled(); + }); +}); + +describe("1112/07-01 context.credentials while composing", () => { + it("says it is called per request instead of failing on the provider table", async () => { + let attempt: Promise | undefined; + let reported: unknown; + fixture.onCompose = (context) => { + const { credentials } = context as ProductCompositionContext; + attempt = Promise.resolve( + credentials.attachCredentials( + { operationId: "X", authProfileId: "EXTERNAL_BEARER", method: "POST" }, + { signal: new AbortController().signal, deadlineAtMonotonicMs: 0 }, + ), + ); + try { + credentials.onUnauthenticated({ operationId: "X", authProfileId: "EXTERNAL_BEARER" }); + } catch (error) { + reported = error; + } + }; + await compose("demo"); + + await expect(attempt).rejects.toThrow(/per request/u); + expect(reported).toBeInstanceOf(TypeError); + }); +});