diff --git a/server/src/maintenance/ephemeral-migration-service.test.ts b/server/src/maintenance/ephemeral-migration-service.test.ts index 4f11ca250cc..f5cb89bd7ed 100644 --- a/server/src/maintenance/ephemeral-migration-service.test.ts +++ b/server/src/maintenance/ephemeral-migration-service.test.ts @@ -1,9 +1,9 @@ import { randomBytes, randomUUID } from "node:crypto"; -import { afterEach, expect, it } from "vitest"; -import { startEphemeralMigrationService, type EphemeralMigrationResult } from "./ephemeral-migration-service.js"; +import { afterEach, expect, it, vi } from "vitest"; +import { ownerRefusalCode, startEphemeralMigrationService, type EphemeralMigrationResult } from "./ephemeral-migration-service.js"; let service: Awaited> | undefined; -afterEach(async () => { await service?.close(); service = undefined; }); +afterEach(async () => { await service?.close(); service = undefined; vi.restoreAllMocks(); }); const result = (): EphemeralMigrationResult => ({ counts: { files: 2 }, eligibility: { eligible: true, blockers: [] }, decisionSigningSecret: randomBytes(32).toString("base64") }); async function start(migrate: Parameters[0]["migrate"], timeoutMs?: number) { const id = randomUUID(), token = randomBytes(32).toString("base64url"), commit = "a".repeat(40); @@ -41,6 +41,51 @@ it("fails closed without exposing owner errors or credentials", async () => { expect((await request("/export", "POST")).status).toBe(409); }); +it("reports an owner's structured refusal and the workspace it was moving, in the receipt and the deployment log", async () => { + const logged = vi.spyOn(console, "error").mockImplementation(() => {}); + const workspaceId = randomUUID(); + const refusal = "remote_workspace_migration_blocked:archived_git_source_unavailable,local_source_unsafe_or_missing"; + const { request } = await start(async (_signal, phase) => { + phase(`workspace:${workspaceId}`); + throw new Error(refusal); + }); + await service!.finished; + expect(await (await request("/status")).json()).toMatchObject({ state: "blocked", phase: `workspace:${workspaceId}`, failure: refusal }); + expect(logged.mock.calls.map(call => JSON.parse(String(call[0])))) + .toEqual([{ event: "ephemeral_migration_blocked", phase: `workspace:${workspaceId}`, failure: refusal }]); +}); + +it("logs only the sanitized code for an arbitrary owner error", async () => { + const logged = vi.spyOn(console, "error").mockImplementation(() => {}); + await start(async () => { throw new Error("provider rejected secret-value at https://private.invalid"); }); + await service!.finished; + expect(logged.mock.calls.map(call => JSON.parse(String(call[0])))) + .toEqual([{ event: "ephemeral_migration_blocked", phase: "configuration", failure: "owner_migration_failed" }]); +}); + +it.each([ + ["remote_workspace_migration_blocked:workspace_recovery_unresolved", "remote_workspace_migration_blocked:workspace_recovery_unresolved"], + ["active_execution_requires_drain", "active_execution_requires_drain"], + // Only known reason-list owners may carry text after a colon. + ["provider:secretvalue", "owner_migration_failed"], + ["a:b:c", "owner_migration_failed"], + // A known owner keeps its code when its reasons are malformed. + ["remote_workspace_migration_blocked:", "remote_workspace_migration_blocked"], + ["remote_workspace_migration_blocked:Secret", "remote_workspace_migration_blocked"], + ["remote_workspace_migration_blocked:a:b", "remote_workspace_migration_blocked"], + ["x".repeat(81), "owner_migration_failed"], +])("reports %s as %s", (message, expected) => { + expect(ownerRefusalCode(new Error(message))).toBe(expected); +}); + +it("keeps the owner and its first reasons when a refusal names too many", () => { + const reasons = Array.from({ length: 40 }, (_, index) => `reason_${String.fromCharCode(97 + index % 26)}${index >= 26 ? "_again" : ""}`); + const code = ownerRefusalCode(new Error(`remote_workspace_migration_blocked:${reasons.join(",")}`)); + expect(code).toBe(`remote_workspace_migration_blocked:${[...reasons.slice(0, 31), "more_reasons_truncated"].join(",")}`); + expect(ownerRefusalCode(new Error(`remote_workspace_migration_blocked:${reasons.slice(0, 17).join(",")}`))) + .toBe(`remote_workspace_migration_blocked:${reasons.slice(0, 17).join(",")}`); +}); + it("rejects incomplete eligibility even when a key was recovered", async () => { const { request } = await start(async () => ({ ...result(), eligibility: { eligible: false, blockers: ["legacy_data"] } })); await service!.finished; diff --git a/server/src/maintenance/ephemeral-migration-service.ts b/server/src/maintenance/ephemeral-migration-service.ts index e4cfd957790..f2bb9ab8d5e 100644 --- a/server/src/maintenance/ephemeral-migration-service.ts +++ b/server/src/maintenance/ephemeral-migration-service.ts @@ -7,6 +7,27 @@ export interface EphemeralMigrationResult { decisionSigningSecret: string; } +const OWNER_CODE = /^[a-z_]{1,80}$/; +// Owners that refuse with their fixed reason list as `owner_code:reason,...`. +// Only these may carry reasons; any other colon message is not an owner code. +const OWNER_REASON_LISTS = new Set(["remote_workspace_migration_blocked"]); +const MAX_REPORTED_REASONS = 32; + +/** Reports an owner's refusal without echoing arbitrary error text. A known + * owner keeps its code when its reason list is malformed or too long. */ +export function ownerRefusalCode(error: unknown) { + const message = error instanceof Error ? error.message : ""; + if (OWNER_CODE.test(message)) return message; + const separator = message.indexOf(":"); + const owner = message.slice(0, separator); + if (separator < 0 || !OWNER_REASON_LISTS.has(owner)) return "owner_migration_failed"; + const reasons = message.slice(separator + 1).split(","); + if (!reasons.every(reason => OWNER_CODE.test(reason))) return owner; + return reasons.length > MAX_REPORTED_REASONS + ? `${owner}:${[...reasons.slice(0, MAX_REPORTED_REASONS - 1), "more_reasons_truncated"].join(",")}` + : `${owner}:${reasons.join(",")}`; +} + /** A dedicated maintenance process, never mounted on the ordinary app router. * Cloud supplies a fresh attempt token and keeps tenant routing closed. Only * the authenticated export transfers the original key to its durable vault. */ @@ -59,9 +80,11 @@ export async function startEphemeralMigrationService(input: { } catch (error) { // Owner codes are safe diagnostics. Never echo arbitrary SDK errors, // credential-bearing URLs, file contents or stack traces through HTTP. - const code = error instanceof Error ? error.message : "owner_migration_failed"; - failure = /^[a-z_]{1,80}$/.test(code) ? code : "owner_migration_failed"; + failure = ownerRefusalCode(error); state = "blocked"; + // The maintenance process has no other log. Record the same fixed codes + // so the provider's deployment log names the refusal too. + console.error(JSON.stringify({ event: "ephemeral_migration_blocked", phase, failure })); } finally { // Successful export authority expires at the original deadline too. // A failed migration has no export authority to retain.