Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 64 additions & 64 deletions packages/api-client/src/schema.d.ts

Large diffs are not rendered by default.

17 changes: 15 additions & 2 deletions packages/api/src/access-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,21 @@ import type { Env, OAuthProps } from "./types";
import { databaseFor } from "./postgres/database";
import { AccessTokenRepository } from "./postgres/access-token-repository";

export const ACCESS_SCOPES = ["flows:read", "flows:write", "runs:read", "runs:write"] as const;
export const ACCESS_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"] as const;
export type AccessScope = typeof ACCESS_SCOPES[number];
export type LegacyScope = "flows:read" | "flows:write" | "runs:write";

/** Legacy grants are accepted only at authentication time. New issuance never emits them. */
export function normalizeScopes(scopes: readonly string[]): string[] {
const result = new Set<string>();
for (const scope of scopes) {
if (scope === "flows:read") ["projects:read", "jobs:read", "integrations:read"].forEach(value => result.add(value));
else if (scope === "flows:write") ["projects:write", "jobs:write", "integrations:write"].forEach(value => result.add(value));
else if (scope === "runs:write") ["runs:read", "runs:invoke", "runs:cancel"].forEach(value => result.add(value));
else if (ACCESS_SCOPES.includes(scope as AccessScope)) result.add(scope);
}
return [...result];
}

const encoder = new TextEncoder();
const base64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
Expand Down Expand Up @@ -33,5 +46,5 @@ export async function authenticateAccessToken(request: Request, env: Env): Promi
const token = authorization.slice(7), tenantId = accessTokenTenant(token);
if (!tenantId) return null;
const auth = await new AccessTokenRepository(databaseFor(env), tenantId).authenticate(await accessTokenDigest(token));
return auth ? { ...auth, authMethod: "access_token" } : null;
return auth ? { ...auth, scopes: normalizeScopes(auth.scopes), authMethod: "access_token" } : null;
}
36 changes: 29 additions & 7 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type JsonSchema = Record<string, any>;
export interface RouteContract {
method: string;
path: string;
scope: z.infer<typeof scopeSchema>;
scope: string | string[];
ownerSession: boolean;
authOperation?: AuthAction;
body?: z.ZodType;
Expand Down Expand Up @@ -104,14 +104,16 @@ const scheduleBody = z
.strict();
const accessTokenBody = z.object({
name: z.string().trim().min(1).max(100),
scopes: z.array(scopeSchema).min(1),
// Legacy names remain accepted at this boundary for migration; the service
// immediately stores their canonical resource-scope expansion.
scopes: z.array(z.union([scopeSchema, z.enum(["flows:read", "flows:write", "runs:write"])] )).min(1),
expiryDays: z.union([z.literal(7), z.literal(30), z.literal(90)]),
});

function route(
method: string,
path: string,
scope: RouteContract["scope"],
scope: string,
documentation: RouteContract["documentation"],
execute: RouteContract["execute"],
options: Partial<
Expand All @@ -132,10 +134,11 @@ function route(
const status = Number(
Object.keys(documentation.responses).find((code) => code.startsWith("2")),
);
const requiredScope = scopeForRoute(path, scope);
return {
method,
path,
scope,
scope: requiredScope,
parameters,
status,
ownerSession: false,
Expand All @@ -145,6 +148,25 @@ function route(
};
}

// Keep the catalog readable while making the authorization boundary explicit.
// Legacy route labels are translated by resource and effect; they are never
// accepted as newly issued scopes.
function scopeForRoute(path: string, legacy: string): string | string[] {
if (legacy === "runs:read" && path === "/api/v1/search") return "jobs:read+runs:read";
if (legacy === "flows:read") {
if (path.startsWith("/api/v1/projects") || path.includes("/jobs/") && path.endsWith("/project")) return "projects:read";
if (path.includes("/integrations") || path.includes("/providers") || path.includes("execution-target") || path.includes("exe-connections") || path.includes("github-installations")) return "integrations:read";
return "jobs:read";
}
if (legacy === "flows:write") {
if (path.startsWith("/api/v1/projects") || path.includes("/jobs/") && path.endsWith("/project")) return "projects:write";
if (path.includes("/integrations") || path.includes("/providers") || path.includes("execution-target") || path.includes("exe-connections") || path.includes("github-installations")) return "integrations:write";
return "jobs:write";
}
if (legacy === "runs:write") return path.includes("invocation") ? "runs:invoke" : "runs:cancel";
return legacy;
}

/** The executable API catalog: change an operation here, then run generate:openapi.
* Service methods retain tenant/identity authorization for both REST and MCP.
*/
Expand Down Expand Up @@ -912,7 +934,7 @@ export const API_ROUTES: RouteContract[] = [
summary:
"Replay a retained trace artifact or restore a native-session projection",
description:
"Requires runs:write and an interactive tenant owner session. One terminal run per request, limited to 10 attempts per tenant per minute including retries and failures. Projection and result commit atomically; no artifacts are deleted. Retry failed requests with the same requestId. Conflicting reuse is rejected. Missing bytes cannot be recovered. Does not change the source declaration of an active or future run.",
"Requires runs:cancel and an interactive tenant owner session. One terminal run per request, limited to 10 attempts per tenant per minute including retries and failures. Projection and result commit atomically; no artifacts are deleted. Retry failed requests with the same requestId. Conflicting reuse is rejected. Missing bytes cannot be recovered. Does not change the source declaration of an active or future run.",
responses: {
"200": {
description: "Durable replay result",
Expand All @@ -925,7 +947,7 @@ export const API_ROUTES: RouteContract[] = [
"400": { description: "Invalid request" },
"401": { description: "Invalid owner session" },
"403": {
description: "Missing runs:write scope or interactive owner session",
description: "Missing runs:cancel scope or interactive owner session",
},
"404": { description: "Run not found within the tenant" },
"409": {
Expand Down Expand Up @@ -1120,7 +1142,7 @@ export function generateOpenApi() {
...route.documentation,
description: [
route.documentation.description,
route.authOperation ? undefined : `Requires the ${route.scope} scope.`,
route.authOperation ? undefined : `Requires the ${Array.isArray(route.scope) ? route.scope.join(" and ") : route.scope.replaceAll("+", " and ")} scope${Array.isArray(route.scope) || route.scope.includes("+") ? "s" : ""}.`,
route.authOperation ? undefined : route.ownerSession
? "An interactive owner session is required; bearer tokens cannot call this operation."
: "Accepts a scoped bearer token or interactive owner session.",
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/auth-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { databaseFor } from "./postgres/database";
import { readSession, requestCookie, signSession, type Session } from "./session";
import type { Env } from "./types";

export const SESSION_SCOPES = ["flows:read", "flows:write", "runs:read", "runs:write"] as const;
export const SESSION_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"] as const;
const email = z.string().trim().toLowerCase().email().max(320);
const password = z.string().min(12).max(200).meta({ writeOnly: true });
const connection = z.uuid().optional();
Expand Down
18 changes: 12 additions & 6 deletions packages/api/src/consent-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ import type { AuthRequest } from "@cloudflare/workers-oauth-provider";
import { hmac } from "./crypto";
import type { Env, OAuthProps } from "./types";
import type { Session } from "./session";
import { ACCESS_SCOPES, normalizeScopes } from "./access-tokens";
export const consentPreviewInput = z.object({ authorizationQuery: z.string().min(1).max(8192) }).strict();
export const consentDecisionInput = z.object({ request: z.string().min(1).max(16384), signature: z.string().min(1).max(256), decision: z.enum(["allow", "deny"]), scopes: z.array(z.enum(["flows:read", "flows:write", "runs:read", "runs:write"])) }).strict();
export const consentDecisionInput = z.object({ request: z.string().min(1).max(16384), signature: z.string().min(1).max(256), decision: z.enum(["allow", "deny"]), scopes: z.array(z.string()) }).strict();
export const consentPreviewResponse = z.object({ clientName: z.string(), scopes: z.array(z.string()), request: z.string(), signature: z.string(), expiresAt: z.string() });
export const consentDecisionResponse = z.object({ redirectTo: z.string() });
const supported = ["flows:read", "flows:write", "runs:read", "runs:write"];
const supported = [...ACCESS_SCOPES, "flows:read", "flows:write", "runs:write"];
const encode = (value: unknown) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(value))));
const decode = (value: string) => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0))));
const binding = (payload: string, session: Session) => `${payload}.${session.tenantId}.${session.userId}.${session.sessionVersion}`;
Expand All @@ -33,7 +34,8 @@ export async function consentPreview(env: Env, session: Session, input: z.infer<
const nonce = crypto.randomUUID();
await databaseFor(env).pool.query("INSERT INTO app.oauth_consent_previews(id,expires_at) VALUES ($1,$2)", [nonce, new Date(expiresAt * 1000)]);
const request = encode({ parsed, expiresAt, nonce, connection: connectionId });
return { clientName: client.clientName ?? "this client", scopes: parsed.scope.filter(scope => supported.includes(scope)), request, signature: await hmac(binding(request, session), env.SESSION_SIGNING_SECRET), expiresAt: new Date(expiresAt * 1000).toISOString() };
const requestedScopes = parsed.scope.filter(scope => supported.includes(scope));
return { clientName: client.clientName ?? "this client", scopes: requestedScopes.some(scope => scope.startsWith("flows:") || scope === "runs:write") ? requestedScopes : normalizeScopes(requestedScopes), request, signature: await hmac(binding(request, session), env.SESSION_SIGNING_SECRET), expiresAt: new Date(expiresAt * 1000).toISOString() };
}
export async function consentDecision(env: Env, session: Session, input: z.infer<typeof consentDecisionInput>) {
if (!env.OAUTH_PROVIDER || !equal(input.signature, await hmac(binding(input.request, session), env.SESSION_SIGNING_SECRET))) return null;
Expand All @@ -44,7 +46,11 @@ export async function consentDecision(env: Env, session: Session, input: z.infer
// Revalidate client registration and redirect URI before grant issuance.
const client = await env.OAUTH_PROVIDER.lookupClient(parsed.clientId);
if (!client || !client.redirectUris.includes(parsed.redirectUri)) return null;
if (input.scopes.some(scope => !parsed.scope.includes(scope) || !supported.includes(scope))) return null;
const allowed = new Set(normalizeScopes(parsed.scope.filter(scope => supported.includes(scope))));
const legacyRequest = parsed.scope.some(scope => scope === "flows:read" || scope === "flows:write" || scope === "runs:write");
const selected = normalizeScopes(input.scopes);
const issuedScopes = legacyRequest ? input.scopes : selected;
if (input.scopes.some(scope => !allowed.has(scope) && !allowed.has(normalizeScopes([scope])[0] ?? "") ) || selected.some(scope => !ACCESS_SCOPES.includes(scope as typeof ACCESS_SCOPES[number]))) return null;
return databaseFor(env).transaction(async transaction => {
const preview = await transaction.query("UPDATE app.oauth_consent_previews SET used_at=now() WHERE id=$1 AND used_at IS NULL AND expires_at>clock_timestamp() RETURNING id", [envelope.nonce]);
if (!preview.rows.length) return null;
Expand All @@ -53,8 +59,8 @@ export async function consentDecision(env: Env, session: Session, input: z.infer
if (!consumed.rows.length) return null;
}
if (input.decision === "deny") { const redirect = new URL(parsed.redirectUri); redirect.searchParams.set("error", "access_denied"); redirect.searchParams.set("state", parsed.state); if (parsed.issuer) redirect.searchParams.set("iss", parsed.issuer); return { redirectTo: redirect.toString() }; }
const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: input.scopes, authMethod: "oauth" };
const { redirectTo } = await env.OAUTH_PROVIDER!.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: input.scopes, props });
const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: issuedScopes, authMethod: "oauth" };
const { redirectTo } = await env.OAUTH_PROVIDER!.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: issuedScopes, props });
return { redirectTo };
});
}
3 changes: 2 additions & 1 deletion packages/api/src/device-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { and, eq, gt } from "drizzle-orm";
import type { DatabaseClient } from "./postgres/database";
import { databaseFor } from "./postgres/database";
import { oauthDeviceAuthorizations } from "./postgres/schema";
import { normalizeScopes } from "./access-tokens";

export const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
const DEVICE_TTL = 600;
Expand Down Expand Up @@ -128,7 +129,7 @@ export async function deviceAuthorization(request: Request, env: Env, oauth: OAu
if (!compactUserCode) return oauthError("server_error", "Could not allocate a user code.", 500);
const now = Math.floor(Date.now() / 1000);
const record: DeviceRecord = {
clientId, clientName: client.clientName ?? "this client", tokenEndpointAuthMethod: client.tokenEndpointAuthMethod ?? "none", scope: requested, resource,
clientId, clientName: client.clientName ?? "this client", tokenEndpointAuthMethod: client.tokenEndpointAuthMethod ?? "none", scope: requested.some(scope => scope === "flows:read" || scope === "flows:write" || scope === "runs:write") ? requested : normalizeScopes(requested), resource,
redirectUri: client.redirectUris[0], codeChallenge: await challenge(codeVerifier),
createdAt: now, expiresAt: now + DEVICE_TTL, interval: DEFAULT_INTERVAL, status: "pending",
};
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/flow-schemas.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { z } from "zod";
import { conditionsSchema, preparedWebhookSchema } from "./webhook-conditions";

export const scopeSchema = z.enum(["flows:read", "flows:write", "runs:read", "runs:write"]);
export const scopeSchema = z.enum(["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"]);
export const runStateSchema = z.enum(["queued", "reserved", "starting", "running", "done", "blocked", "failed", "ignored", "succeeded", "stopping", "stopped"]);
export const matchRuleSchema = z.object({
type: z.enum(["owner", "creator", "status", "label", "assignee"]),
Expand Down
Loading
Loading