285 lines
12 KiB
TypeScript
285 lines
12 KiB
TypeScript
import { describe, expect, test, vi } from "vitest";
|
|
|
|
import { app } from "../app.js";
|
|
import {
|
|
TEST_API_CONFIG,
|
|
configureApiIsolationDependenciesForTests,
|
|
createStoredApiKeyFixture,
|
|
installApiIsolationTestHooks,
|
|
} from "./fixtures/api-key.js";
|
|
|
|
installApiIsolationTestHooks();
|
|
|
|
const STORED_API_KEY_SECRET = "stored-service-boundary-key-secret";
|
|
const SECOND_TENANT_API_KEY_SECRET = "stored-service-boundary-tenant-2-key-secret";
|
|
const INVALID_API_KEY_SECRET = "invalid-service-boundary-key-secret";
|
|
const REQUEST_ID = "req_service_boundary";
|
|
const SIGNED_DOWNLOAD_URL = "https://storage.local/signed/export_job_1.csv?signature=redacted";
|
|
|
|
function createBoundaryApiKey(patch: Parameters<typeof createStoredApiKeyFixture>[0] = {}) {
|
|
return createStoredApiKeyFixture({
|
|
id: "api_key_boundary_1",
|
|
tenantId: "tenant_1",
|
|
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
|
|
...patch,
|
|
});
|
|
}
|
|
|
|
function createExportJob(patch: Record<string, unknown> = {}) {
|
|
return {
|
|
id: "export_job_1",
|
|
tenantId: "tenant_1",
|
|
requestedByUserId: null,
|
|
format: "csv",
|
|
status: "COMPLETED" as const,
|
|
artifactBucket: "exports",
|
|
artifactKey: "tenant_1/export_job_1.csv",
|
|
rowCount: 1,
|
|
expiresAt: new Date("2999-01-02T00:00:00.000Z"),
|
|
errorName: null,
|
|
requestId: "req_export_job_1",
|
|
...patch,
|
|
};
|
|
}
|
|
|
|
function createBoundaryDependencies() {
|
|
const primaryApiKey = createBoundaryApiKey();
|
|
const secondTenantApiKey = createBoundaryApiKey({
|
|
id: "api_key_boundary_2",
|
|
tenantId: "tenant_2",
|
|
tenant: { id: "tenant_2", name: "Other", slug: "other", deactivatedReason: null },
|
|
});
|
|
const exportJob = createExportJob();
|
|
|
|
const dependencies = {
|
|
findLegacyApiKeyByKey: vi.fn(async (key: string) => {
|
|
if (key === STORED_API_KEY_SECRET) return primaryApiKey;
|
|
if (key === SECOND_TENANT_API_KEY_SECRET) return secondTenantApiKey;
|
|
return null;
|
|
}),
|
|
findExportJobForDownload: vi.fn(async ({ id, tenantId }: { id: string; tenantId?: string | null }) => {
|
|
if (id === exportJob.id && tenantId === exportJob.tenantId) return exportJob;
|
|
return null;
|
|
}),
|
|
createSignedDownloadUrl: vi.fn(async () => ({
|
|
method: "GET" as const,
|
|
url: SIGNED_DOWNLOAD_URL,
|
|
expiresAt: new Date("2026-01-01T00:05:00.000Z"),
|
|
expiresInSeconds: 300,
|
|
headers: { "x-download": "allowed" },
|
|
})),
|
|
};
|
|
|
|
configureApiIsolationDependenciesForTests(dependencies);
|
|
|
|
return { primaryApiKey, secondTenantApiKey, exportJob, dependencies };
|
|
}
|
|
|
|
function apiKeyHeaders(secret = STORED_API_KEY_SECRET, requestId = REQUEST_ID) {
|
|
return { "x-api-key": secret, "x-request-id": requestId };
|
|
}
|
|
|
|
function bearerHeaders(secret: string, requestId = REQUEST_ID) {
|
|
return { authorization: `Bearer ${secret}`, "x-request-id": requestId };
|
|
}
|
|
|
|
function jsonHeaders(headers: Record<string, string>) {
|
|
return { ...headers, "content-type": "application/json" };
|
|
}
|
|
|
|
function jsonRequest(headers: Record<string, string>, body: unknown) {
|
|
const serialized = JSON.stringify(body);
|
|
return {
|
|
headers: { ...jsonHeaders(headers), "content-length": String(Buffer.byteLength(serialized)) },
|
|
body: serialized,
|
|
};
|
|
}
|
|
|
|
async function expectSerializedBodyRedacts(response: Response, secrets: string[]) {
|
|
const text = await response.text();
|
|
const configuredServiceToken = TEST_API_CONFIG.apiAccessToken;
|
|
for (const secret of secrets) {
|
|
expect(text).not.toContain(secret);
|
|
}
|
|
expect(text).not.toContain(configuredServiceToken);
|
|
expect(text).not.toContain("scope-secret");
|
|
return text;
|
|
}
|
|
|
|
async function expectRedactedError(response: Response, expected: { status: number; code: string; requestId: string }) {
|
|
expect(response.status).toBe(expected.status);
|
|
expect(response.headers.get("x-request-id")).toBe(expected.requestId);
|
|
|
|
const text = await expectSerializedBodyRedacts(response, [STORED_API_KEY_SECRET, SECOND_TENANT_API_KEY_SECRET, INVALID_API_KEY_SECRET]);
|
|
expect(text).toContain(expected.requestId);
|
|
expect(JSON.parse(text)).toEqual({
|
|
error: expect.objectContaining({
|
|
code: expected.code,
|
|
requestId: expected.requestId,
|
|
}),
|
|
});
|
|
}
|
|
|
|
describe("API-key validation service boundary", () => {
|
|
test("returns active stored-key metadata for the stored key tenant without raw key material", async () => {
|
|
const { primaryApiKey, dependencies } = createBoundaryDependencies();
|
|
|
|
const response = await app.request("/v1/api-keys/validate", {
|
|
method: "POST",
|
|
...jsonRequest(apiKeyHeaders(STORED_API_KEY_SECRET, "req_validate_active"), { apiKey: STORED_API_KEY_SECRET }),
|
|
});
|
|
|
|
expect(response.status).toBe(200);
|
|
const text = await expectSerializedBodyRedacts(response, [STORED_API_KEY_SECRET]);
|
|
expect(JSON.parse(text)).toEqual({
|
|
active: true,
|
|
keyType: "stored-api-key",
|
|
apiKey: {
|
|
id: primaryApiKey.id,
|
|
alias: primaryApiKey.alias,
|
|
tenantId: "tenant_1",
|
|
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
|
|
expires: null,
|
|
},
|
|
});
|
|
expect(dependencies.findLegacyApiKeyByKey).toHaveBeenCalledWith(STORED_API_KEY_SECRET, undefined, "scope-secret", { allowPlaintextFallback: true });
|
|
});
|
|
|
|
test.each([
|
|
{ label: "expired", patch: { expires: new Date("2000-01-01T00:00:00.000Z") } },
|
|
{ label: "inactive", patch: { active: false } },
|
|
{ label: "deactivated", patch: { tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: "closed" } } },
|
|
])("returns inactive stored-key metadata for $label keys without raw key or tenant material", async ({ patch }) => {
|
|
const inactiveKey = createBoundaryApiKey(patch);
|
|
configureApiIsolationDependenciesForTests({
|
|
findLegacyApiKeyByKey: vi.fn(async (key: string) => (key === STORED_API_KEY_SECRET ? inactiveKey : null)),
|
|
});
|
|
|
|
const response = await app.request("/v1/api-keys/validate", {
|
|
method: "POST",
|
|
...jsonRequest({ "x-request-id": "req_validate_inactive" }, { apiKey: STORED_API_KEY_SECRET }),
|
|
});
|
|
|
|
expect(response.status).toBe(200);
|
|
const text = await expectSerializedBodyRedacts(response, [STORED_API_KEY_SECRET]);
|
|
expect(JSON.parse(text)).toMatchObject({
|
|
active: false,
|
|
keyType: "stored-api-key",
|
|
apiKey: { id: inactiveKey.id, alias: inactiveKey.alias },
|
|
});
|
|
expect(text).not.toContain("tenant_1");
|
|
expect(text).not.toContain("Acme");
|
|
});
|
|
|
|
test("returns service-token validation result without exposing the submitted token", async () => {
|
|
createBoundaryDependencies();
|
|
const serviceToken = TEST_API_CONFIG.apiAccessToken ?? "";
|
|
|
|
const response = await app.request("/v1/api-keys/validate", {
|
|
method: "POST",
|
|
...jsonRequest({ "x-request-id": "req_validate_service" }, { apiKey: serviceToken }),
|
|
});
|
|
|
|
expect(response.status).toBe(200);
|
|
const text = await expectSerializedBodyRedacts(response, [serviceToken]);
|
|
expect(JSON.parse(text)).toEqual({ active: true, keyType: "service-token" });
|
|
});
|
|
|
|
test("returns inactive service-token validation for invalid keys without service-token fallback", async () => {
|
|
const { dependencies } = createBoundaryDependencies();
|
|
|
|
const response = await app.request("/v1/api-keys/validate", {
|
|
method: "POST",
|
|
...jsonRequest({ "x-request-id": "req_validate_invalid" }, { apiKey: INVALID_API_KEY_SECRET }),
|
|
});
|
|
|
|
expect(response.status).toBe(200);
|
|
const text = await expectSerializedBodyRedacts(response, [INVALID_API_KEY_SECRET]);
|
|
expect(JSON.parse(text)).toEqual({ active: false, keyType: "service-token" });
|
|
expect(dependencies.findLegacyApiKeyByKey).toHaveBeenCalledWith(INVALID_API_KEY_SECRET, undefined, "scope-secret", { allowPlaintextFallback: true });
|
|
});
|
|
});
|
|
describe("export download service boundary", () => {
|
|
test("rejects stored key export lookup when tenantId query is tampered", async () => {
|
|
const { dependencies } = createBoundaryDependencies();
|
|
|
|
const response = await app.request("/v1/exports/export_job_1/download-url?tenantId=tenant_2", { headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_export_tamper") });
|
|
|
|
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_export_tamper" });
|
|
expect(dependencies.findExportJobForDownload).not.toHaveBeenCalled();
|
|
expect(dependencies.createSignedDownloadUrl).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("rejects stored keys whose tenant does not match the export job", async () => {
|
|
const { dependencies } = createBoundaryDependencies();
|
|
|
|
const response = await app.request("/v1/exports/export_job_1/download-url?tenantId=tenant_1", { headers: apiKeyHeaders(SECOND_TENANT_API_KEY_SECRET, "req_export_tenant_mismatch") });
|
|
|
|
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_export_tenant_mismatch" });
|
|
expect(dependencies.findExportJobForDownload).not.toHaveBeenCalled();
|
|
expect(dependencies.createSignedDownloadUrl).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("rejects inactive stored keys before export lookup", async () => {
|
|
const { primaryApiKey, dependencies } = createBoundaryDependencies();
|
|
primaryApiKey.active = false;
|
|
|
|
const response = await app.request("/v1/exports/export_job_1/download-url?tenantId=tenant_1", { headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_export_inactive_key") });
|
|
|
|
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_export_inactive_key" });
|
|
expect(dependencies.findExportJobForDownload).not.toHaveBeenCalled();
|
|
expect(dependencies.createSignedDownloadUrl).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("rejects paused exports before signing artifact URLs without leaking pause reason", async () => {
|
|
const pauseReason = "retention pause secret_token=super-secret-value";
|
|
const { dependencies } = createBoundaryDependencies();
|
|
dependencies.findExportJobForDownload.mockResolvedValueOnce(
|
|
createExportJob({
|
|
errorName: "ExportPaused",
|
|
errorMessage: pauseReason,
|
|
artifactBucket: "exports",
|
|
artifactKey: "tenant_1/export_job_1.csv",
|
|
})
|
|
);
|
|
|
|
const response = await app.request("/v1/exports/export_job_1/download-url?tenantId=tenant_1", { headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_export_paused") });
|
|
|
|
const body = await response.text();
|
|
expect(response.status).toBe(409);
|
|
expect(response.headers.get("x-request-id")).toBe("req_export_paused");
|
|
expect(JSON.parse(body)).toEqual({
|
|
error: expect.objectContaining({
|
|
code: "export_job_paused",
|
|
requestId: "req_export_paused",
|
|
}),
|
|
});
|
|
expect(body).not.toContain(pauseReason);
|
|
expect(body).not.toContain("super-secret-value");
|
|
expect(dependencies.createSignedDownloadUrl).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("preserves service-token lookup by requested tenant", async () => {
|
|
const { dependencies } = createBoundaryDependencies();
|
|
|
|
const serviceToken = TEST_API_CONFIG.apiAccessToken ?? "";
|
|
const response = await app.request("/v1/exports/export_job_1/download-url?tenantId=tenant_1", { headers: bearerHeaders(serviceToken, "req_export_service") });
|
|
|
|
expect(response.status).toBe(200);
|
|
await expect(response.json()).resolves.toMatchObject({ exportJobId: "export_job_1", requestId: "req_export_service" });
|
|
expect(dependencies.findLegacyApiKeyByKey).not.toHaveBeenCalledWith(serviceToken, undefined, expect.any(String));
|
|
expect(dependencies.findExportJobForDownload).toHaveBeenCalledWith({ id: "export_job_1", tenantId: "tenant_1" });
|
|
});
|
|
|
|
test("denies invalid API keys without falling through to service-token lookup", async () => {
|
|
const { dependencies } = createBoundaryDependencies();
|
|
|
|
const response = await app.request("/v1/exports/export_job_1/download-url?tenantId=tenant_1", { headers: apiKeyHeaders(INVALID_API_KEY_SECRET, "req_export_invalid") });
|
|
|
|
await expectRedactedError(response, { status: 401, code: "unauthorized", requestId: "req_export_invalid" });
|
|
expect(dependencies.findLegacyApiKeyByKey).toHaveBeenCalledWith(INVALID_API_KEY_SECRET, undefined, "scope-secret", { allowPlaintextFallback: true });
|
|
expect(dependencies.findExportJobForDownload).not.toHaveBeenCalled();
|
|
expect(dependencies.createSignedDownloadUrl).not.toHaveBeenCalled();
|
|
});
|
|
});
|