Files
PaperClipAI/server/src/__tests__/cloud-runtime-identity.test.ts
T
DottaandPaperclip 689bfd04ac feat(onboarding): add free_inference_1 onboarding flow, dual-trigger model gate, and multi-variant PostHog attribution (#23401)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - First-time Cloud users currently must connect an external AI
provider during onboarding before they can talk to their first agent.
> - Requiring provider setup up front adds friction before users
experience their first agent chat.
> - Paperclip needs a multi-variant onboarding experiment
(`onboarding-flow`) that defaults to `baseline` while allowing an
alternate `free_inference_1` path that skips the model-connection screen
and starts with capped starter inference.
> - When a trial-only workspace either exhausts its starter credit or
creates its first executable task or subtask, Paperclip must hold the
new task, prompt the user to connect a model provider, keep LLM actions
blocked if the modal is dismissed, and automatically resume held work
once a model is connected.
> - This pull request adds multi-variant onboarding resolution, PostHog
multi-variant attribution, dual-trigger connect-model gating with
restart-safe DB hydration, the `free_inference_1` UI onboarding flow,
and full-flow Storybooks.
> - The benefit is a safe, measurable onboarding experiment that leaves
`baseline` and self-hosted installs unchanged while letting opted-in
Cloud workspaces reach their first chat immediately and upgrade
seamlessly when real work begins.

## Linked Issues or Issue Description

**Subsystem affected**

Cross-cutting (`packages/shared/`, `server/`, `ui/`)

**Problem or motivation**

New Cloud users currently hit a mandatory "Connect a model" step during
onboarding before they can open their first agent chat. Existing
trial-inference gating only supported a binary flag and only triggered
on starter-credit exhaustion, not on subtask or manual task creation,
and did not track multi-variant onboarding cohorts cleanly in PostHog.

**Proposed solution**

Introduce the extensible `onboarding-flow` experiment (`baseline`
default, `free_inference_1` variant) across shared contracts, server
services, and UI:
- Resolve `onboardingVariant` from the Cloud control plane (`GET
/v1/tenant/onboarding-config`) with safe fallbacks to
`PAPERCLIP_ONBOARDING_VARIANT`, managed config, and `"baseline"`.
- In `free_inference_1`, skip Step 4 ("Connect a model") in
`OnboardingWizard`, hire the first agent on starter inference, and drop
the user straight into the first chat.
- Support a dual-trigger connect-model gate (`exhausted` and
`work_requires_model`) that holds newly created tasks/subtasks on
trial-only workspaces (hydrated from DB across restarts), returns HTTP
402 for blocked LLM chat/runs, keeps the modal dismissible while
blocking chat composers with a "Connect a model" CTA banner, and
automatically resumes held work after provider migration.
- Stamp `$feature/onboarding-flow`, `onboarding_variant`, and immutable
`initial_onboarding_variant` across server PostHog events,
`$groupidentify` (with top-level `$group_set_once`), and browser PostHog
super-properties / `identify()`.

**Alternatives considered**

- Baking per-stack experiment variants into warm-pool container config
was ruled out because warm-pool stacks must remain homogeneous until
claim time.
- Failing agent subtask creation calls on trial-only workspaces was
ruled out because it breaks the agent's first-chat experience; creating
the task in a held state and auto-resuming it after model connection
preserves user intent.

## What Changed

- **`packages/shared`**: Added `onboarding-flow` variant
constants/helpers, `CloudTrialGateReason` (`"exhausted" |
"work_requires_model"`), `CloudTrialHeldIssueSummary`, `gateReason`,
`llmBlocked`, `heldIssueIds`, `heldIssues`, `onboardingVariant`, and
`resumedIssueIds` on cloud-inference and session/browser-analytics
contracts.
- **`server/`**:
- Added Ed25519-signed `GET /v1/tenant/onboarding-config` resolution
with warm-pool claim cache invalidation and safe `"baseline"` default.
- Added dual-trigger trial gating (`exhausted` + `work_requires_model`)
with DB-backed held-issue hydration across restarts, HTTP 402 refusal
for blocked trial runs and chat sends, and automatic wake/resume of held
subtasks upon migration.
- Updated PostHog server telemetry, `$groupidentify` (top-level
`$group_set` and `$group_set_once`), `$feature_flag_called`, and
`BrowserAnalyticsConfig` to stamp `onboarding-flow` multi-variant
properties while preserving backwards-compatible `cloud-trial-inference`
properties.
- Added and updated Vitest suites covering multi-variant resolution,
PostHog attribution, held subtask creation, cold-restart hydration, LLM
run refusal, and auto-resume.
- **`ui/`**:
- Updated `OnboardingWizard` so `free_inference_1` skips Step 4
("Connect a model"), auto-hires with `cloudTrialInference: true`, and
launches straight into the first chat while leaving `baseline`
unchanged.
- Updated `CloudTrialGate` and `CloudTrialExhaustedModal` for
dual-trigger copy (`work_requires_model` vs `exhausted`), waiting
subtask pills, and dismissible modal behavior (`required={false}`).
- Added `CloudTrialBlockedBanner` and wired LLM-blocked composer
disabling + "Connect a model" CTA into `IssueDetail` / `AgentChat` and
`DashboardChatComposer`, plus status refresh on manual task creation in
`NewIssueDialog`.
- Updated `product-analytics.ts` + tests to register
`$feature/onboarding-flow` and `onboarding_variant` super-properties and
`$set_once.initial_onboarding_variant`.
- Added full-flow Storybooks
(`free-inference-onboarding-flow.stories.tsx`) covering all 7 onboarding
and gate states.

## Verification

- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck` (0 errors)
- `pnpm --filter @paperclipai/ui typecheck` (0 errors)
- 9 targeted server Vitest suites (`cloud-trial-inference`,
`cloud-posthog-config`, `cloud-posthog-browser`,
`posthog-direct-telemetry`, `posthog-direct-transport`, `auth-routes`,
`cloud-runtime-identity`, `onboarding-seed-route`,
`issue-onboarding-first-task-routes`): 196/196 passed
- 4 targeted UI Vitest suites (`CloudTrialGate.test.tsx`,
`product-analytics.test.ts`, `onboarding-analytics.test.tsx`,
`Layout.mobile.test.tsx`): 37/37 passed
- `pnpm --filter @paperclipai/ui build` and `pnpm --filter
@paperclipai/ui build-storybook`: passed
- Visually inspected Storybook renders across all 7 `free_inference_1`
states in headless Chromium via Playwright with zero page errors.

## Risks

- Low risk to existing users: `onboardingVariant` defaults to
`"baseline"` everywhere, leaving self-hosted installs and unflagged
Cloud stacks unchanged.
- No database schema migrations are required; held trial subtasks are
hydrated from existing `issues` and `toolConnections` tables on restart.
- Requires the companion `paperclip-cloud` control-plane endpoint (`GET
/v1/tenant/onboarding-config`) to activate non-baseline variants in
Cloud; falls back safely to `"baseline"` if unavailable.

## Model Used

- Google Gemini (Antigravity agentic coding environment with multi-agent
swarm, tool use, code execution, and Playwright Storybook verification)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 20:54:03 +00:00

472 lines
17 KiB
TypeScript

import { createCloudWarmStandby } from "../services/cloud-warm-standby.js";
import { cloudWarmStandbyMiddleware } from "../middleware/cloud-warm-standby.js";
import { generateKeyPairSync, sign } from "node:crypto";
import express from "express";
import request from "supertest";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { createDb, instanceSettings } from "@paperclipai/db";
import {
applyCloudRuntimeIdentityAssertion,
CLOUD_RUNTIME_IDENTITY_AUDIENCE,
CLOUD_RUNTIME_IDENTITY_ISSUER,
CLOUD_RUNTIME_IDENTITY_JWS_TYPE,
getCloudRuntimeIdentity,
initializeCloudRuntimeIdentity,
resetCloudRuntimeIdentityForTests,
runtimePublicOrigin,
} from "../services/cloud-runtime-identity.js";
import { routineWebhookUrl } from "../services/routines.js";
import { paperclipCloudConnectorEnrollmentStatus } from "../services/paperclip-cloud-connector-enrollment.js";
import { cloudRuntimeIdentityMiddleware } from "../middleware/cloud-runtime-identity.js";
import { idleAdmissionMiddleware, trackIdleRequestHandlers } from "../middleware/idle-admission.js";
import { idleWorkSnapshot } from "../services/task-admission.js";
import { healthRoutes } from "../routes/health.js";
import { createPostHogDirectTransport, type PostHogNodeClient } from "../services/posthog-direct/transport.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
const STACK_ID = "stack-pool-123";
const POOL_ORIGIN = "https://pool-123.staging.paperclip.app";
const CANONICAL_ORIGIN = "https://gonzo.staging.paperclip.app";
const NOW = new Date("2099-01-01T00:00:00.000Z");
const pair = generateKeyPairSync("ed25519");
const publicJwk = {
...pair.publicKey.export({ format: "jwk" }),
kid: "runtime-identity-test-key",
use: "sig",
alg: "EdDSA",
};
function encodeJson(value: Record<string, unknown>) {
return Buffer.from(JSON.stringify(value)).toString("base64url");
}
function assertion(input: {
claims?: Record<string, unknown>;
header?: Record<string, unknown>;
signingKey?: typeof pair.privateKey;
} = {}) {
const iat = Math.floor(NOW.getTime() / 1000);
const header = encodeJson({
alg: "EdDSA",
typ: CLOUD_RUNTIME_IDENTITY_JWS_TYPE,
kid: publicJwk.kid,
...input.header,
});
const payload = encodeJson({
v: 1,
iss: CLOUD_RUNTIME_IDENTITY_ISSUER,
aud: CLOUD_RUNTIME_IDENTITY_AUDIENCE,
sub: STACK_ID,
claimId: "pool-entry-123",
previousOrigin: POOL_ORIGIN,
canonicalOrigin: CANONICAL_ORIGIN,
stackSlug: "gonzo",
iat,
exp: iat + 300,
...input.claims,
});
const signature = sign(
null,
Buffer.from(`${header}.${payload}`, "ascii"),
input.signingKey ?? pair.privateKey,
).toString("base64url");
return `${header}.${payload}.${signature}`;
}
describeEmbeddedPostgres("Cloud runtime identity", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
const originalEnv = { ...process.env };
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-cloud-runtime-identity-");
db = createDb(tempDb.connectionString);
}, 20_000);
beforeEach(async () => {
await db.delete(instanceSettings);
resetCloudRuntimeIdentityForTests();
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "test-tenant-server-token";
process.env.PAPERCLIP_CLOUD_STACK_ID = STACK_ID;
process.env.PAPERCLIP_CLOUD_API_ORIGIN = "https://my-staging.paperclip.app";
process.env.PAPERCLIP_PUBLIC_URL = POOL_ORIGIN;
process.env.PAPERCLIP_AUTH_PUBLIC_BASE_URL = POOL_ORIGIN;
process.env.PAPERCLIP_API_URL = POOL_ORIGIN;
process.env.PAPERCLIP_PRIMARY_HOST = "pool-123.staging.paperclip.app";
process.env.PAPERCLIP_STACK_SLUG = "pool-123";
process.env.PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS = JSON.stringify({ keys: [publicJwk] });
process.env.PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID = "managed-instance";
process.env.PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY = "managed-signing-key";
process.env.PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY = "managed-sealing-key";
process.env.PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT = "staging";
process.env.PAPERCLIP_CLOUD_CONNECTOR_BASE_URL = "https://my-staging.paperclip.app";
await initializeCloudRuntimeIdentity(db);
});
afterEach(() => {
vi.restoreAllMocks();
for (const key of [
"PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN",
"PAPERCLIP_CLOUD_STACK_ID",
"PAPERCLIP_CLOUD_API_ORIGIN",
"PAPERCLIP_PUBLIC_URL",
"PAPERCLIP_AUTH_PUBLIC_BASE_URL",
"PAPERCLIP_API_URL",
"PAPERCLIP_PRIMARY_HOST",
"PAPERCLIP_STACK_SLUG",
"PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS",
"PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID",
"PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY",
"PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY",
"PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT",
"PAPERCLIP_CLOUD_CONNECTOR_BASE_URL",
"PAPERCLIP_RUNTIME_API_CANDIDATES_JSON",
]) {
const original = originalEnv[key];
if (original === undefined) delete process.env[key];
else process.env[key] = original;
}
resetCloudRuntimeIdentityForTests();
});
afterAll(async () => {
await tempDb?.cleanup();
});
it("persists and immediately applies a valid one-time claim", async () => {
const applied = await applyCloudRuntimeIdentityAssertion({
db,
compactJws: assertion(),
now: NOW,
});
expect(applied.canonicalOrigin).toBe(CANONICAL_ORIGIN);
expect(getCloudRuntimeIdentity()?.stackSlug).toBe("gonzo");
expect(runtimePublicOrigin()).toBe(CANONICAL_ORIGIN);
expect(process.env.PAPERCLIP_PUBLIC_URL).toBe(CANONICAL_ORIGIN);
expect(process.env.PAPERCLIP_AUTH_PUBLIC_BASE_URL).toBe(CANONICAL_ORIGIN);
expect(process.env.PAPERCLIP_API_URL).toBe(CANONICAL_ORIGIN);
expect(process.env.PAPERCLIP_PRIMARY_HOST).toBe("gonzo.staging.paperclip.app");
expect(process.env.PAPERCLIP_STACK_SLUG).toBe("gonzo");
expect(routineWebhookUrl("hook-1")).toBe(
"https://gonzo.staging.paperclip.app/api/routine-triggers/public/hook-1/fire",
);
expect(paperclipCloudConnectorEnrollmentStatus()).toMatchObject({
configured: true,
status: "active",
origins: [CANONICAL_ORIGIN],
});
});
it("re-identifies the PostHog workspace group with the claimed slug and host", async () => {
const groupIdentifies: Array<Parameters<PostHogNodeClient["capture"]>[0]> = [];
const flush = vi.fn(async () => {});
const fakeClient: PostHogNodeClient = {
capture: (message) => {
if (message.event === "$groupidentify") groupIdentifies.push(message);
},
groupIdentify: () => {},
flush,
shutdown: async () => {},
};
const transport = createPostHogDirectTransport(
{
token: "phc_test",
host: "http://127.0.0.1:1",
environment: "staging",
stackId: STACK_ID,
directEnabled: true,
browserEnabled: false,
replayEnabled: false,
replayWorkContentEnabled: false,
cloudTrialInferenceEnabled: false,
},
{ factory: async () => fakeClient },
);
try {
await transport.announceWorkspace({
stackSlug: "pool-123",
primaryHost: "pool-123.staging.paperclip.app",
app: "paperclip",
schemaVersion: "1",
version: "1.0.0",
installId: "install-1",
installHash: "hash-1",
});
expect(groupIdentifies).toHaveLength(1);
expect(groupIdentifies[0]?.properties?.$group_set).toMatchObject({
stack_slug: "pool-123",
primary_host: "pool-123.staging.paperclip.app",
});
await applyCloudRuntimeIdentityAssertion({
db,
compactJws: assertion(),
now: NOW,
});
await vi.waitFor(() => {
expect(groupIdentifies).toHaveLength(2);
});
expect(groupIdentifies[1]?.properties).toMatchObject({
$group_type: "workspace",
$group_key: STACK_ID,
$group_set: {
stack_slug: "gonzo",
primary_host: "gonzo.staging.paperclip.app",
environment: "staging",
},
});
expect(flush).toHaveBeenCalledTimes(2);
// Idempotent retry of the same claim does not spam duplicate groupIdentify calls.
await applyCloudRuntimeIdentityAssertion({
db,
compactJws: assertion(),
now: NOW,
});
await new Promise((resolve) => setTimeout(resolve, 25));
expect(groupIdentifies).toHaveLength(2);
} finally {
await transport.shutdown();
}
});
it("uses the claimed slug and host when the claim arrives while PostHog client loading is in flight", async () => {
const groupIdentifies: Array<Parameters<PostHogNodeClient["capture"]>[0]> = [];
const fakeClient: PostHogNodeClient = {
capture: (message) => {
if (message.event === "$groupidentify") groupIdentifies.push(message);
},
groupIdentify: () => {},
flush: async () => {},
shutdown: async () => {},
};
let resolveFactory!: (client: PostHogNodeClient) => void;
const factoryPromise = new Promise<PostHogNodeClient>((resolve) => {
resolveFactory = resolve;
});
const transport = createPostHogDirectTransport(
{
token: "phc_test",
host: "http://127.0.0.1:1",
environment: "staging",
stackId: STACK_ID,
directEnabled: true,
browserEnabled: false,
replayEnabled: false,
replayWorkContentEnabled: false,
cloudTrialInferenceEnabled: false,
},
{ factory: () => factoryPromise },
);
try {
const announcePromise = transport.announceWorkspace({
stackSlug: "pool-123",
primaryHost: "pool-123.staging.paperclip.app",
app: "paperclip",
schemaVersion: "1",
version: "1.0.0",
installId: "install-1",
installHash: "hash-1",
});
await applyCloudRuntimeIdentityAssertion({
db,
compactJws: assertion(),
now: NOW,
});
resolveFactory(fakeClient);
await announcePromise;
expect(groupIdentifies).toHaveLength(1);
expect(groupIdentifies[0]?.properties).toMatchObject({
$group_type: "workspace",
$group_key: STACK_ID,
$group_set: {
stack_slug: "gonzo",
primary_host: "gonzo.staging.paperclip.app",
environment: "staging",
},
});
} finally {
await transport.shutdown();
}
});
it("applies the assertion on the existing health request and acknowledges the exact origin", async () => {
const requestTime = Math.floor(Date.now() / 1000);
const app = express();
app.use(cloudRuntimeIdentityMiddleware(db));
app.use("/api/health", healthRoutes(db, {
deploymentMode: "authenticated",
deploymentExposure: "public",
authReady: true,
companyDeletionEnabled: false,
}));
const response = await request(app)
.get("/api/health")
.set("x-paperclip-cloud-runtime-identity", assertion({
claims: { iat: requestTime, exp: requestTime + 300 },
}));
expect(response.status).toBe(200);
expect(response.body.cloud.runtimeIdentity).toEqual({
canonicalOrigin: CANONICAL_ORIGIN,
stackSlug: "gonzo",
});
});
it.each([false, true])("counts exempt bootstrap writes until they settle (failure=%s)", async (fail) => {
let enterWrite!: () => void, finishWrite!: () => void;
const entered = new Promise<void>(resolve => { enterWrite = resolve; });
const pending = new Promise<void>(resolve => { finishWrite = resolve; });
const transaction = db.transaction.bind(db);
vi.spyOn(db, "transaction").mockImplementationOnce(async (...args) => {
enterWrite();
await pending;
if (fail) throw new Error("fixture bootstrap write failed");
return transaction(...args);
});
const app = express();
app.use(idleAdmissionMiddleware);
app.use(cloudRuntimeIdentityMiddleware(db));
app.get("/api/health", (_req, res) => res.sendStatus(204));
trackIdleRequestHandlers(app);
const requestTime = Math.floor(Date.now() / 1000);
const accepted = request(app).get("/api/health")
.set("x-paperclip-cloud-runtime-identity", assertion({ claims: { iat: requestTime, exp: requestTime + 300 } }))
.then(response => response);
try {
await entered;
expect(idleWorkSnapshot().active).toBe(1);
} finally {
finishWrite();
const response = await accepted;
expect(response.status).toBe(fail ? 401 : 204);
}
expect(idleWorkSnapshot().active).toBe(0);
});
it("keeps probes idle until a verified durable claim and stays active across restart", async () => {
const env = { ...process.env, PAPERCLIP_CLOUD_WARM_STANDBY: "1" };
const isStandby = await createCloudWarmStandby(db, env);
const execute = vi.spyOn(db, "execute");
const health = healthRoutes(db, {
deploymentMode: "authenticated", deploymentExposure: "public",
authReady: true, companyDeletionEnabled: false, isWarmStandby: isStandby,
});
const app = express();
app.use(cloudRuntimeIdentityMiddleware(db));
app.use(cloudWarmStandbyMiddleware(isStandby, health));
app.use("/api/health", health);
expect((await request(app).get("/api/health")).body.warmStandby).toBe(true);
expect(execute).not.toHaveBeenCalled();
const requestTime = Math.floor(Date.now() / 1000);
const invalid = await request(app).get("/api/health").set("x-paperclip-cloud-runtime-identity", assertion({
claims: { sub: "another-stack", iat: requestTime, exp: requestTime + 300 },
}));
expect(invalid.status).toBe(401);
expect(isStandby()).toBe(true);
const signed = assertion({ claims: { iat: requestTime, exp: requestTime + 300 } });
const claimed = await request(app).get("/api/health").set("x-paperclip-cloud-runtime-identity", signed);
expect(claimed.status).toBe(200);
expect(claimed.body.warmStandby).toBeUndefined();
expect(isStandby()).toBe(false);
expect(execute).toHaveBeenCalledOnce();
expect((await request(app).get("/api/health").set("x-paperclip-cloud-runtime-identity", signed)).status).toBe(200);
resetCloudRuntimeIdentityForTests();
process.env.PAPERCLIP_PUBLIC_URL = POOL_ORIGIN;
await initializeCloudRuntimeIdentity(db);
expect((await createCloudWarmStandby(db, env))()).toBe(false);
});
it("restores the canonical identity before consumers read stale startup variables", async () => {
await applyCloudRuntimeIdentityAssertion({ db, compactJws: assertion(), now: NOW });
resetCloudRuntimeIdentityForTests();
process.env.PAPERCLIP_PUBLIC_URL = POOL_ORIGIN;
process.env.PAPERCLIP_AUTH_PUBLIC_BASE_URL = POOL_ORIGIN;
process.env.PAPERCLIP_API_URL = POOL_ORIGIN;
await initializeCloudRuntimeIdentity(db);
expect(runtimePublicOrigin()).toBe(CANONICAL_ORIGIN);
expect(process.env.PAPERCLIP_API_URL).toBe(CANONICAL_ORIGIN);
});
it("accepts the identical claim after a restart with already-aligned provider variables", async () => {
await applyCloudRuntimeIdentityAssertion({ db, compactJws: assertion(), now: NOW });
resetCloudRuntimeIdentityForTests();
process.env.PAPERCLIP_PUBLIC_URL = CANONICAL_ORIGIN;
process.env.PAPERCLIP_AUTH_PUBLIC_BASE_URL = CANONICAL_ORIGIN;
process.env.PAPERCLIP_API_URL = CANONICAL_ORIGIN;
await initializeCloudRuntimeIdentity(db);
await expect(applyCloudRuntimeIdentityAssertion({
db,
compactJws: assertion(),
now: NOW,
})).resolves.toMatchObject({ canonicalOrigin: CANONICAL_ORIGIN });
});
it("accepts an identical replay but rejects a different claim or destination", async () => {
await applyCloudRuntimeIdentityAssertion({ db, compactJws: assertion(), now: NOW });
await expect(applyCloudRuntimeIdentityAssertion({
db,
compactJws: assertion(),
now: NOW,
})).resolves.toMatchObject({ canonicalOrigin: CANONICAL_ORIGIN });
await expect(applyCloudRuntimeIdentityAssertion({
db,
compactJws: assertion({ claims: { claimId: "another-claim" } }),
now: NOW,
})).rejects.toThrow("already claimed");
});
it.each([
["expired", { exp: Math.floor(NOW.getTime() / 1000) - 1 }],
["cross-stack", { sub: "stack-someone-else" }],
["wrong previous origin", { previousOrigin: "https://another.staging.paperclip.app" }],
["path-bearing destination", { canonicalOrigin: `${CANONICAL_ORIGIN}/GON` }],
["slug mismatch", { stackSlug: "kermit" }],
])("rejects %s assertions", async (_label, claims) => {
await expect(applyCloudRuntimeIdentityAssertion({
db,
compactJws: assertion({ claims }),
now: NOW,
})).rejects.toThrow();
});
it("rejects unknown keys and altered signed destinations", async () => {
await expect(applyCloudRuntimeIdentityAssertion({
db,
compactJws: assertion({ header: { kid: "unknown" } }),
now: NOW,
})).rejects.toThrow("unknown signing key");
const valid = assertion();
const [header, payload, signature] = valid.split(".");
const altered = encodeJson({
...JSON.parse(Buffer.from(payload!, "base64url").toString("utf8")),
canonicalOrigin: "https://attacker.example.com",
});
await expect(applyCloudRuntimeIdentityAssertion({
db,
compactJws: `${header}.${altered}.${signature}`,
now: NOW,
})).rejects.toThrow("signature is invalid");
});
});