문제: Fileserver 업로드 client가 서버 401을 AUTH_REQUIRED 실패로만 돌려준다. 세션은 authenticated로 남고 OIDC refresh도, 서버 상태 fence도 일어나지 않는다. JWT 모드(EXTERNAL_BEARER)에는 업로드에 세션 bearer를 붙일 지원 경로가 없어, 제품이 세션 owner를 붙잡아 scope fence 밖에서 부르게 된다. bootstrap은 "자격 증명 주인" 판정 순서를 attachCredentials와 reportServerUnauthenticated 두 곳에 따로 적는다. 매뉴얼 02 7절 업로드 예는 declare module로 capability를 보강해 check:types:node가 그 키를 못 본다. 고른 방법(R9-D2, R9-D13 대안): - credentialOwner(authProfileId) 하나가 NONE·PRODUCT·SESSION을 정하고, V3 attachCredentials와 401 전달이 둘 다 그것을 읽는다(02-10). - ProductCompositionContext.credentials를 더한다. V3와 같은 attachCredentials와 같은 401 전달(onUnauthenticated)이다(추가만). - FileserverUploadClientDependencies에 선택 onUnauthenticated를 더하고, client는 서버 401이면 본문과 상관없이 한 번 부른다(추가만). - 업로드 capability 타입은 indexedDb처럼 템플릿이 FeaturePlatformCapabilities에 opt-in 키 fileserverUpload로 선언한다. R9-D13 권하는 안(product-capabilities.ts가 contribution 파일에서 타입을 가져옴)은 contribution 파일이 이미 product-capabilities.ts를 type import해서 그래프 순환이 된다(r9-fe 승인 2026-11-13). - 매뉴얼 02 7절을 context.credentials를 펼치는 조각 둘로 바꾸고 manual-code-block 표식을 단다. 시험은 제품 소유 파일 조각이 그 파일을 통째로 바꾸게 한다. 버린 대안: 템플릿이 제품 capability를 모양으로 찾아 감싸기 — 제품이 정한 키 이름을 템플릿이 추측해야 한다. 위험·한계: 업로드 capability에 context.credentials를 펼치지 않은 제품은 그대로 401이 세션에 닿지 않는다(매뉴얼 02 7절·04에 적음). 쿠키 세션 모드 조각은 문장으로만 있고 시험 조각은 JWT 모드다. 검증: desktop, RED — 고치기 전 코드에서 새 업로드·주인 시험이 실패 (/tmp/claude-gates/r9b-pr1-red/exec_node.log). check:types·lint· check:architecture rc=0(/tmp/claude-gates/r9b-pr1-quick). merge 단계는 PR 본문. Refs: 1112/02-10, 1112/07-01, 1112/09-01
601 lines
19 KiB
TypeScript
601 lines
19 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
|
|
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";
|
|
|
|
/**
|
|
* 09-02. The composition root alone decides the order a credential is looked
|
|
* for, so a product credential provider can never run outside the fences:
|
|
*
|
|
* scope fence -> ANONYMOUS profile -> product provider -> session -> scope fence again
|
|
*
|
|
* Each row runs the real `createRuntimeAdapters`. Replaced: the installed
|
|
* contract set (adds the fixture operations), the feature-input composer (to
|
|
* reach the `http` capability) and the product-owned composition file (the
|
|
* provider table under test).
|
|
*/
|
|
|
|
const fixture = vi.hoisted(() => ({
|
|
http: undefined as InstalledHttpOperationExecutor | undefined,
|
|
providers: {} as Record<string, unknown>,
|
|
onCredentialRejected: undefined as ((binding: unknown) => void) | undefined,
|
|
context: undefined as unknown,
|
|
onCompose: undefined as ((context: unknown) => void) | undefined,
|
|
withProfile<T extends { contract: object; frontend: object }>(
|
|
contract: T,
|
|
operationId: string,
|
|
authProfileId: string,
|
|
): T {
|
|
return {
|
|
...contract,
|
|
contract: { ...contract.contract, operationId },
|
|
frontend: { ...contract.frontend, authProfileId },
|
|
};
|
|
},
|
|
}));
|
|
|
|
vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => {
|
|
const original =
|
|
await importOriginal<typeof import("../../src/features/installed-contract-contributions.ts")>();
|
|
const { TEST_CONTRACT_CONTRIBUTION, TEST_LIST_HTTP_CONTRACT: list } =
|
|
await import("../helpers/external-contract-fixture.ts");
|
|
const source = TEST_CONTRACT_CONTRIBUTION.source;
|
|
if (source.kind !== "EXTERNAL_PACKAGE") throw new Error("fixture source changed");
|
|
return {
|
|
...original,
|
|
createInstalledContractRegistry: () => {
|
|
const registry = original.createInstalledContractRegistry([
|
|
...original.EXPECTED_CONTRACT_SET_PACKAGES,
|
|
source.package,
|
|
]);
|
|
registry.install(TEST_CONTRACT_CONTRIBUTION.featureId, [
|
|
{
|
|
...TEST_CONTRACT_CONTRIBUTION,
|
|
http: [
|
|
list,
|
|
fixture.withProfile(list, "TEST_LIST_ENTITIES_BEARER", "EXTERNAL_BEARER"),
|
|
] as typeof TEST_CONTRACT_CONTRIBUTION.http,
|
|
},
|
|
]);
|
|
return registry;
|
|
},
|
|
};
|
|
});
|
|
|
|
vi.mock("../../src/features/installed-feature-adapters.ts", async (importOriginal) => {
|
|
const original =
|
|
await importOriginal<typeof import("../../src/features/installed-feature-adapters.ts")>();
|
|
return {
|
|
...original,
|
|
createInstalledFeatureLoaders: (
|
|
...args: Parameters<typeof original.createInstalledFeatureLoaders>
|
|
) => {
|
|
fixture.http = Reflect.get(args[0], "http") as typeof fixture.http;
|
|
return original.createInstalledFeatureLoaders(...args);
|
|
},
|
|
};
|
|
});
|
|
|
|
/** The product-owned file, filled the way a product fills it. */
|
|
vi.mock("../../src/bootstrap/product-composition.ts", () => ({
|
|
composeProductSessionOwner: () => null,
|
|
composeProduct: (context: unknown) => {
|
|
fixture.context = context;
|
|
fixture.onCompose?.(context);
|
|
return {
|
|
capabilities: {},
|
|
credentialProviders: fixture.providers,
|
|
...(fixture.onCredentialRejected === undefined
|
|
? {}
|
|
: { onCredentialRejected: fixture.onCredentialRejected }),
|
|
};
|
|
},
|
|
}));
|
|
|
|
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
|
|
type Adapters = Awaited<ReturnType<typeof createRuntimeAdapters>>;
|
|
|
|
function runtimeFor(authMode: "demo" | "external"): Runtime {
|
|
return {
|
|
config: testRuntimeConfig({
|
|
APP_ENV: "local",
|
|
API_BASE_URL: "http://localhost:8080",
|
|
TELEMETRY_ENABLED: false,
|
|
AUTH_MODE: authMode,
|
|
REQUEST_TIMEOUT_MS: 10_000,
|
|
MAX_RETRY_ATTEMPTS: 0,
|
|
RELEASE_MANIFEST_URL: "/release-manifest.json",
|
|
CONFIG_SCHEMA_VERSION: "2.0",
|
|
CAPABILITY_OVERRIDES: {
|
|
REALTIME: "DEFAULT",
|
|
WEB_WORKER: "DEFAULT",
|
|
SERVICE_WORKER: "DEFAULT",
|
|
OFFLINE_COMMANDS: "DEFAULT",
|
|
},
|
|
FEATURE_OVERRIDES: {},
|
|
}),
|
|
configSchema: "V2",
|
|
build: {
|
|
buildId: "build-a",
|
|
commitSha: "abc123",
|
|
routerBasePath: "/",
|
|
runtimeConfigUrl: "/config.json",
|
|
},
|
|
validationDurationMs: 0,
|
|
};
|
|
}
|
|
|
|
const release: Parameters<typeof createRuntimeAdapters>[0]["release"] = {
|
|
schemaVersion: 2,
|
|
appVersion: "0.1.0",
|
|
buildId: "build-a",
|
|
commitSha: "abc123",
|
|
configSchemaVersion: "2.0",
|
|
contractSet: {
|
|
setAlgorithm: "CA_CONTRACT_SET_V1",
|
|
setDigest: `sha256:${"0".repeat(64)}`,
|
|
packages: [],
|
|
},
|
|
assetManifestHash: "hash-a",
|
|
releaseId: "release-a",
|
|
builtAt: "2026-07-25T00:00:00Z",
|
|
routeChunks: { "route-home": "assets/home.js" },
|
|
};
|
|
|
|
const ANONYMOUS_OPERATION = TEST_LIST_HTTP_CONTRACT;
|
|
/** The only non-anonymous profile the template installs. */
|
|
const PROFILE_OPERATION = fixture.withProfile(
|
|
TEST_LIST_HTTP_CONTRACT,
|
|
"TEST_LIST_ENTITIES_BEARER",
|
|
"EXTERNAL_BEARER",
|
|
);
|
|
|
|
function externalOwner() {
|
|
const listeners = new Set<() => void>();
|
|
let subject = "user-a";
|
|
return {
|
|
readState: () => "authenticated",
|
|
readSubject: () => subject,
|
|
subscribe(listener: () => void) {
|
|
listeners.add(listener);
|
|
return () => listeners.delete(listener);
|
|
},
|
|
beginSignIn: async () => {},
|
|
signOut: async () => {},
|
|
attachCredential: vi.fn(async () => ({
|
|
headers: { authorization: "Bearer owner-token" },
|
|
})),
|
|
recoverSession: async () => "no-session",
|
|
notifyUnauthenticated: () => {},
|
|
switchUser() {
|
|
subject = "user-b";
|
|
for (const listener of listeners) listener();
|
|
},
|
|
};
|
|
}
|
|
|
|
let current: Adapters | undefined;
|
|
afterEach(() => {
|
|
current?.infrastructure.dispose();
|
|
current = undefined;
|
|
fixture.http = undefined;
|
|
fixture.providers = {};
|
|
fixture.onCredentialRejected = undefined;
|
|
fixture.context = undefined;
|
|
fixture.onCompose = undefined;
|
|
});
|
|
|
|
async function compose(
|
|
authMode: "demo" | "external",
|
|
host: Record<string, unknown> = {},
|
|
respond: () => Response = () =>
|
|
Response.json([{ id: "entity-1", name: "Entity" }]),
|
|
) {
|
|
const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
|
|
respond(),
|
|
);
|
|
current = await createRuntimeAdapters({
|
|
runtime: runtimeFor(authMode),
|
|
release,
|
|
host,
|
|
fetcher: fetcher as unknown as typeof fetch,
|
|
});
|
|
const http = fixture.http;
|
|
if (!http) throw new Error("The http capability was not composed");
|
|
return { adapters: current, http, fetcher };
|
|
}
|
|
|
|
const productToken: ProductCredentialProvider = async () => ({
|
|
kind: "READY",
|
|
headers: { authorization: "Bearer product-token" },
|
|
});
|
|
|
|
type Row = Readonly<{
|
|
step: string;
|
|
/** Builds the product provider table; may close over the composed state. */
|
|
providers: (owner: ReturnType<typeof externalOwner>) => Record<string, ProductCredentialProvider>;
|
|
authMode: "demo" | "external";
|
|
/** Runs after composition, before the request. */
|
|
before?: (adapters: Adapters) => void;
|
|
operation: typeof PROFILE_OPERATION;
|
|
outcome: Record<string, unknown>;
|
|
sentAuthorization: string | null;
|
|
providerCalls: number;
|
|
ownerCalls: number;
|
|
}>;
|
|
|
|
const ROWS: readonly Row[] = [
|
|
{
|
|
step: "1 scope fence comes before the product provider",
|
|
providers: () => ({ EXTERNAL_BEARER: productToken }),
|
|
authMode: "demo",
|
|
// The session change fences the scope synchronously; READY comes later.
|
|
before: (adapters) => void adapters.outputPorts.session.beginSignIn(),
|
|
operation: PROFILE_OPERATION,
|
|
outcome: { kind: "CONTRACT_VIOLATION", violation: { kind: "SCOPE_FENCED" } },
|
|
sentAuthorization: null,
|
|
providerCalls: 0,
|
|
ownerCalls: 0,
|
|
},
|
|
{
|
|
step: "2 an ANONYMOUS profile never reaches a provider",
|
|
providers: () => ({ ANONYMOUS: productToken }),
|
|
authMode: "demo",
|
|
operation: ANONYMOUS_OPERATION,
|
|
outcome: { kind: "SUCCESS" },
|
|
sentAuthorization: null,
|
|
providerCalls: 0,
|
|
ownerCalls: 0,
|
|
},
|
|
{
|
|
step: "3 a registered provider answers before the session (signed out)",
|
|
providers: () => ({ EXTERNAL_BEARER: productToken }),
|
|
authMode: "demo",
|
|
operation: PROFILE_OPERATION,
|
|
outcome: { kind: "SUCCESS" },
|
|
sentAuthorization: "Bearer product-token",
|
|
providerCalls: 1,
|
|
ownerCalls: 0,
|
|
},
|
|
{
|
|
step: "3 a registered provider answers before the external owner",
|
|
providers: () => ({ EXTERNAL_BEARER: productToken }),
|
|
authMode: "external",
|
|
operation: PROFILE_OPERATION,
|
|
outcome: { kind: "SUCCESS" },
|
|
sentAuthorization: "Bearer product-token",
|
|
providerCalls: 1,
|
|
ownerCalls: 0,
|
|
},
|
|
{
|
|
step: "4 a profile without a provider still needs the session",
|
|
providers: () => ({}),
|
|
authMode: "demo",
|
|
operation: PROFILE_OPERATION,
|
|
outcome: { kind: "UNAUTHENTICATED", effect: "NOT_APPLICABLE" },
|
|
sentAuthorization: null,
|
|
providerCalls: 0,
|
|
ownerCalls: 0,
|
|
},
|
|
{
|
|
step: "5 the scope fence is checked again after the provider answers",
|
|
providers: (owner) => ({
|
|
EXTERNAL_BEARER: async (...args) => {
|
|
owner.switchUser();
|
|
return productToken(...args);
|
|
},
|
|
}),
|
|
authMode: "external",
|
|
operation: PROFILE_OPERATION,
|
|
// A fence during the credential wait aborts the transport (Q-6.3-6). The
|
|
// composition root's own re-check behind it is not visible from here.
|
|
outcome: { kind: "TRANSPORT_FAILURE", failure: { kind: "ABORTED_BY_SCOPE" } },
|
|
sentAuthorization: null,
|
|
providerCalls: 1,
|
|
ownerCalls: 0,
|
|
},
|
|
{
|
|
step: "6 a provider that throws fails closed",
|
|
providers: () => ({
|
|
EXTERNAL_BEARER: async () => {
|
|
throw new Error("product provider down");
|
|
},
|
|
}),
|
|
authMode: "demo",
|
|
operation: PROFILE_OPERATION,
|
|
outcome: {
|
|
kind: "AUTH_INTEGRATION_FAILURE",
|
|
reason: "CREDENTIAL_OWNER_FAILED",
|
|
},
|
|
sentAuthorization: null,
|
|
providerCalls: 1,
|
|
ownerCalls: 0,
|
|
},
|
|
];
|
|
|
|
describe("09-02 credential order in the composition root", () => {
|
|
it.each(ROWS)("$step", async (row) => {
|
|
const owner = externalOwner();
|
|
const providerCalls = vi.fn();
|
|
fixture.providers = Object.fromEntries(
|
|
Object.entries(row.providers(owner)).map(([profileId, provider]) => [
|
|
profileId,
|
|
((...args) => {
|
|
providerCalls(profileId);
|
|
return provider(...args);
|
|
}) satisfies ProductCredentialProvider,
|
|
]),
|
|
);
|
|
const { http, fetcher, adapters } = await compose(
|
|
row.authMode,
|
|
row.authMode === "external" ? { __CA_FRONTEND_AUTH_OWNER__: owner } : {},
|
|
);
|
|
row.before?.(adapters);
|
|
|
|
const outcome = await http.execute(
|
|
row.operation,
|
|
{ limit: 1 },
|
|
{ routeId: "TEST_ROUTE" },
|
|
);
|
|
|
|
expect(outcome).toMatchObject(row.outcome);
|
|
expect(providerCalls).toHaveBeenCalledTimes(row.providerCalls);
|
|
expect(owner.attachCredential).toHaveBeenCalledTimes(row.ownerCalls);
|
|
if (row.sentAuthorization === null) {
|
|
for (const [, init] of fetcher.mock.calls) {
|
|
expect(new Headers(init?.headers).has("authorization")).toBe(false);
|
|
}
|
|
} else {
|
|
expect(fetcher).toHaveBeenCalledOnce();
|
|
expect(
|
|
new Headers(fetcher.mock.calls[0]?.[1]?.headers).get("authorization"),
|
|
).toBe(row.sentAuthorization);
|
|
}
|
|
});
|
|
});
|
|
|
|
/**
|
|
* 1103/09-01. A 401 to a credential a product provider supplied is the
|
|
* provider's verdict, not the template session's: the session did not supply
|
|
* that credential. The product hears it through `onCredentialRejected`.
|
|
*/
|
|
describe("1103/09-01 a 401 to a product provider's credential", () => {
|
|
const unauthorized = () => new Response(null, { status: 401 });
|
|
|
|
it("leaves the session alone and tells the product", async () => {
|
|
const owner = externalOwner();
|
|
const notifyUnauthenticated = vi.spyOn(owner, "notifyUnauthenticated");
|
|
const rejected = vi.fn();
|
|
fixture.providers = { EXTERNAL_BEARER: productToken };
|
|
fixture.onCredentialRejected = rejected;
|
|
const { http, adapters } = await compose(
|
|
"external",
|
|
{ __CA_FRONTEND_AUTH_OWNER__: owner },
|
|
unauthorized,
|
|
);
|
|
const scope = adapters.infrastructure.serverStateScope.getSnapshot();
|
|
|
|
const outcome = await http.execute(
|
|
PROFILE_OPERATION,
|
|
{ limit: 1 },
|
|
{ routeId: "TEST_ROUTE" },
|
|
);
|
|
|
|
expect(outcome.kind).toBe("UNAUTHENTICATED");
|
|
expect(notifyUnauthenticated).not.toHaveBeenCalled();
|
|
expect(scope.isCurrent()).toBe(true);
|
|
expect(rejected).toHaveBeenCalledExactlyOnceWith({
|
|
operationId: "TEST_LIST_ENTITIES_BEARER",
|
|
authProfileId: "EXTERNAL_BEARER",
|
|
});
|
|
});
|
|
|
|
it("keeps the outcome when the product hook throws", async () => {
|
|
fixture.providers = { EXTERNAL_BEARER: productToken };
|
|
fixture.onCredentialRejected = () => {
|
|
throw new Error("product hook defect");
|
|
};
|
|
const { http } = await compose("demo", {}, unauthorized);
|
|
|
|
const outcome = await http.execute(
|
|
PROFILE_OPERATION,
|
|
{ limit: 1 },
|
|
{ routeId: "TEST_ROUTE" },
|
|
);
|
|
|
|
expect(outcome.kind).toBe("UNAUTHENTICATED");
|
|
});
|
|
|
|
it("does not call the product hook for the session's own credential", async () => {
|
|
const rejected = vi.fn();
|
|
fixture.onCredentialRejected = rejected;
|
|
const owner = externalOwner();
|
|
const notifyUnauthenticated = vi.spyOn(owner, "notifyUnauthenticated");
|
|
const { http } = await compose(
|
|
"external",
|
|
{ __CA_FRONTEND_AUTH_OWNER__: owner },
|
|
unauthorized,
|
|
);
|
|
|
|
await http.execute(PROFILE_OPERATION, { limit: 1 }, { routeId: "TEST_ROUTE" });
|
|
|
|
expect(notifyUnauthenticated).toHaveBeenCalledOnce();
|
|
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<string, ProductCredentialProvider>,
|
|
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<unknown> | 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);
|
|
});
|
|
});
|