Skip to content
65 changes: 57 additions & 8 deletions platform/packages/api/src/routes/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,60 @@ async function presignUnderProjectLock(
// Deploy to a project
app.post('/:id/deploy', handleManifestOnlyDeploy);

const ADMISSION_REJECTED_MESSAGE = 'Admitted deployment is no longer authorized or valid';
const ADMISSION_REASON_MAX_BYTES = 8192;
const ADMISSION_REASON_MAX_CHARS = 4096;

/**
* Read why the deploy handler refused an admitted input, for example a Zero
* Trust change that landed while the deploy waited. Its JSON body carries the
* same `message` (or bare `error`) a direct deploy would show, so the user
* learns whether a retry fixes it. Only a small JSON body is read.
*/
async function rejectedAdmissionReason(response: Response): Promise<string | null> {
const type = response.headers.get('content-type') ?? '';
const reader: ReadableStreamDefaultReader<Uint8Array> | undefined = response.body?.getReader();
if (!reader) {
return null;
}
const bytes = new Uint8Array(ADMISSION_REASON_MAX_BYTES);
let size = 0;
try {
if (type.split(';')[0].trim().toLowerCase() !== 'application/json') {
return null;
}
for (;;) {
const chunk = await reader.read();
if (chunk.done) {
break;
}
if (size + chunk.value.byteLength > bytes.byteLength) {
return null;
}
bytes.set(chunk.value, size);
size += chunk.value.byteLength;
}
} finally {
void reader.cancel().catch(() => {});
}
let body: unknown;
try {
body = JSON.parse(new TextDecoder().decode(bytes.subarray(0, size)));
} catch {
return null;
}
if (!body || typeof body !== 'object') {
return null;
}
const { message, error } = body as { message?: unknown; error?: unknown };
for (const candidate of [message, error]) {
if (typeof candidate === 'string' && candidate.trim()) {
return candidate.trim().slice(0, ADMISSION_REASON_MAX_CHARS);
}
}
return null;
}

export async function executeQueuedDeployment(
env: ApiEnv['Bindings'],
db: Db,
Expand Down Expand Up @@ -590,6 +644,7 @@ export async function executeQueuedDeployment(
env,
);
if (response.status !== 204) {
const reason = (await rejectedAdmissionReason(response)) ?? ADMISSION_REJECTED_MESSAGE;
// A rejected admitted input never entered the pipeline. No provider write
// occurred, so its placeholder can be finalized without replaying it.
await db.transaction(async (tx) => {
Expand All @@ -600,17 +655,11 @@ export async function executeQueuedDeployment(
if (!candidate || candidate.manifest !== null || candidate.status !== 'pending') {
throw new Error('Admitted deployment needs reconciliation');
}
await updateDeploymentStatus(
tx,
operation.id,
'failed',
'Admitted deployment is no longer authorized or valid',
{ force: true },
);
await updateDeploymentStatus(tx, operation.id, 'failed', reason, { force: true });
});
await appendDeploymentEvent(db, operation.id, operation.owner_id!, {
event: 'error',
message: 'Admitted deployment is no longer authorized or valid',
message: reason,
step: 'authorization',
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ import {
} from '../../src/schema.ts';
import type { DeployEvent } from '../../src/types.ts';
import { WORKER_UPLOAD_OUT_OF_TIME } from '../../src/worker-upload.ts';
import { ZeroTrustUnavailableError } from '../../src/zero-trust/errors.ts';
// oxlint-disable-next-line import/no-namespace -- The test replaces or spies on members of the module object.
import * as zeroTrustRouting from '../../src/zero-trust/routing.ts';
import {
createTestBuild,
clearTables,
Expand Down Expand Up @@ -1192,9 +1195,37 @@ describe('durable execution claim and revocation', () => {
expect(await env.ROUTING.get(`slug:${project.slug}`)).toBeNull();
const operation = await getDeploymentOperation(env.db, id);
expect(operation).toMatchObject({ status: 'terminal' });
const reason =
'This build is no longer active. Start a new build to deploy the current version.';
expect(await env.db.select().from(deployments)).toMatchObject([{ error_message: reason }]);
expect(operation?.events.at(-1)?.event).toMatchObject({
event: 'error',
step: expect.any(String),
message: reason,
step: 'authorization',
});
});

it('reports the Zero Trust reason when protection changes while a deploy waits', async () => {
const id = await admit();
// A Zero Trust flip that lands after admission makes the deploy handler
// answer 409 when the queued work runs.
vi.spyOn(zeroTrustRouting, 'resolveProjectZeroTrustRouting').mockRejectedValue(
new ZeroTrustUnavailableError('The project public exception is still reconciling.'),
);
const message = await run(id);
expect(message.ack).toHaveBeenCalledOnce();
expect(message.retry).not.toHaveBeenCalled();
const [deployment] = await env.db.select().from(deployments);
expect(deployment).toMatchObject({ id, status: 'failed' });
expect(deployment.error_message).toContain(
'Zero Trust protection for this project is not ready: The project public exception is still reconciling.',
);
expect(deployment.error_message).toContain('then retry.');
const operation = await getDeploymentOperation(env.db, id);
expect(operation?.events.at(-1)?.event).toMatchObject({
event: 'error',
message: deployment.error_message,
step: 'authorization',
});
});
});
Expand Down