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
72 changes: 72 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1232,6 +1232,28 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/access/authorizations/{grantId}/permissions": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
/**
* Edit an OAuth connection’s scopes and integration access
* @description Requires the jobs:write scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
*/
put: operations["put_api_v1_access_authorizations_grantId_permissions"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/access/authorizations/{grantId}": {
parameters: {
query?: never;
Expand Down Expand Up @@ -6067,6 +6089,12 @@ export interface operations {
};
content: {
"application/json": {
availableScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write" | "proxy:use" | "vm:grant")[];
/** @description Integration ID to approved epoch-bound scope, or false to block. */
integrationOverrides: {
[key: string]: string | false;
};
revision: number;
grantId: string;
clientId: string;
clientName: string;
Expand Down Expand Up @@ -6199,6 +6227,50 @@ export interface operations {
503: components["responses"]["Error503"];
};
};
put_api_v1_access_authorizations_grantId_permissions: {
parameters: {
query?: never;
header?: never;
path: {
grantId: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
disabledScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write" | "proxy:use" | "vm:grant")[];
/** @description Integration ID to approved epoch-bound scope, or false to block. */
integrationOverrides: {
[key: string]: string | false;
};
expectedRevision?: number;
};
};
};
responses: {
/** @description Permissions saved */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
ok: boolean;
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
415: components["responses"]["Error415"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
delete_api_v1_access_authorizations_grantId: {
parameters: {
query?: never;
Expand Down
5 changes: 5 additions & 0 deletions packages/api/migrations/0065_oauth_connection_settings.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
ALTER TABLE app.agent_identities
ADD COLUMN display_name text,
ADD COLUMN disabled_scopes text[] NOT NULL DEFAULT '{}',
ADD COLUMN integration_overrides jsonb NOT NULL DEFAULT '{}',
ADD COLUMN permissions_revision integer NOT NULL DEFAULT 0;
4 changes: 2 additions & 2 deletions packages/api/src/access-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { databaseFor } from "./postgres/database";
import { AccessTokenRepository } from "./postgres/access-token-repository";

export const ACCESS_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:start", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"] as const;
export const AGENT_SCOPES: readonly string[] = [...ACCESS_SCOPES, "proxy:use", "vm:grant"];
export const AGENT_SCOPES = [...ACCESS_SCOPES, "proxy:use", "vm:grant"] as const;
export type AccessScope = typeof ACCESS_SCOPES[number];
export type LegacyScope = "flows:read" | "flows:write";

Expand All @@ -15,7 +15,7 @@ export function normalizeScopes(scopes: readonly string[]): string[] {
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", "runs:write"].forEach(value => result.add(value));
else if (AGENT_SCOPES.includes(scope) || isIntegrationScope(scope)) result.add(scope);
else if ((AGENT_SCOPES as readonly string[]).includes(scope) || isIntegrationScope(scope)) result.add(scope);
}
return [...result];
}
Expand Down
29 changes: 17 additions & 12 deletions packages/api/src/agent-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ export class AgentApiError extends Error {
}
export type AgentIntegration = {id: string; kind: "bearer" | "model" | "github" | "linear" | "fly" | "exe" | "amp" | "clickup" | "x"; credential_id: string; name: string; description: string | null; available: boolean; policy: "baseline" | "requestable" | "disabled"; epoch: number; revision: number};
export const requiredIntegrationScope = (row: AgentIntegration) => `integration:${row.id}:${row.epoch}`;
type ConnectionPolicy = { integration_overrides: Record<string, string | false>; disabled_scopes: string[] };
function connectionAccess(row: AgentIntegration, scopes: string[], policy: ConnectionPolicy) {
const scope = requiredIntegrationScope(row);
if (policy.disabled_scopes.includes("proxy:use") || policy.integration_overrides[row.id] === false || row.policy === "disabled" || !row.available) return "blocked";
return row.policy === "baseline" || policy.integration_overrides[row.id] === scope || scopes.includes(scope) ? "granted" : "requestable";
}
const STORAGE_BLOCK_BYTES = 1024 * 1024;
const forbidden = () => new AgentApiError(403, "forbidden", "This integration is not authorized.");
const invalidIdentity = () => new AgentApiError(401, "invalid_token", "The agent authorization is no longer active.");
Expand Down Expand Up @@ -71,24 +77,23 @@ export class AgentApiService {
config = row.execution_config;
} else if (auth.authMethod === "vm_grant" && auth.vmGrantId) {
kind = "vm"; subject = auth.vmGrantId;
const grant = (await this.database.pool.query(`SELECT g.permissions, g.parent_scopes FROM app.vm_grants g
const grant = (await this.database.pool.query(`SELECT g.permissions, g.parent_scopes, parent.integration_overrides, parent.disabled_scopes, to_jsonb(provider) AS provider FROM app.vm_grants g
JOIN app.agent_identities parent ON parent.tenant_id=g.tenant_id AND parent.id=g.parent_id
JOIN app.agent_integrations provider ON provider.tenant_id=g.tenant_id AND provider.id=g.provider_id
WHERE g.tenant_id=$1 AND g.id=$2 AND parent.user_id=$3 AND parent.session_version=$4
AND parent.revoked_at IS NULL AND g.issuer IS NOT NULL AND g.revoked_at IS NULL AND g.expires_at>now()
AND provider.available AND provider.epoch=g.provider_epoch AND (provider.policy='baseline' OR
(provider.policy='requestable' AND g.parent_scopes @> to_jsonb(ARRAY['integration:' || provider.id::text || ':' || provider.epoch::text])))`,
AND provider.available AND provider.epoch=g.provider_epoch`,
[auth.tenantId, subject, auth.userId, auth.sessionVersion])).rows[0];
if (!grant) throw invalidIdentity();
if (!grant || grant.disabled_scopes.includes("vm:grant") || connectionAccess(grant.provider, grant.parent_scopes, grant as ConnectionPolicy) !== "granted") throw invalidIdentity();
config = grant;
} else if (auth.authMethod === "oauth" && auth.oauthGrantId && auth.oauthClientId && auth.oauthExpiresAt && auth.oauthExpiresAt > Date.now()/1000) {
kind = "oauth"; subject = auth.oauthGrantId;
} else throw invalidIdentity();
const row = (await this.database.pool.query<{id: string; user_id: string; session_version: number; revoked_at: Date | null}>(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version)
const row = (await this.database.pool.query<ConnectionPolicy & {id: string; user_id: string; session_version: number; revoked_at: Date | null}>(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version)
VALUES($1,$2,$3,$4,$5) ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET subject=excluded.subject
RETURNING id,user_id,session_version,revoked_at`, [auth.tenantId, kind, subject, auth.userId, auth.sessionVersion])).rows[0]!;
RETURNING id,user_id,session_version,revoked_at,integration_overrides,disabled_scopes`, [auth.tenantId, kind, subject, auth.userId, auth.sessionVersion])).rows[0]!;
if (row.revoked_at || row.user_id !== auth.userId || row.session_version !== auth.sessionVersion) throw invalidIdentity();
return {id: row.id, kind, config};
return {id: row.id, kind, config, policy: row};
}
private selected(row: AgentIntegration, config: Record<string, any>) {
switch(row.kind) {
Expand All @@ -107,15 +112,15 @@ export class AgentApiService {
if (!row) throw forbidden();
if (identity.kind === "vm") {
const grant = identity.config!;
if (grant.permissions[row.id] !== row.epoch || !row.available || row.policy === "disabled"
|| (row.policy !== "baseline" && !grant.parent_scopes.includes(requiredIntegrationScope(row)))) throw forbidden();
if (grant.permissions[row.id] !== row.epoch || connectionAccess(row, grant.parent_scopes, grant as ConnectionPolicy) !== "granted") throw forbidden();
} else if (identity.kind === "run") {
if (!this.selected(row, identity.config!)) throw forbidden();
const revoked = await this.database.pool.query("SELECT 1 FROM app.run_credential_revocations WHERE tenant_id=$1 AND run_id=$2 AND kind=$3 AND credential_id=$4", [this.auth.tenantId, this.auth.runId, row.kind, row.credential_id]);
if (revoked.rowCount || !row.available) throw forbidden();
} else {
if (row.policy === "disabled" || !row.available) throw forbidden();
if (row.policy !== "baseline" && !this.auth.scopes.includes(requiredIntegrationScope(row))) throw new AgentApiError(403, "insufficient_scope", "Approve this integration before making the request.", requiredIntegrationScope(row));
const access = connectionAccess(row, this.auth.scopes, identity.policy);
if (access === "blocked") throw forbidden();
if (access === "requestable") throw new AgentApiError(403, "insufficient_scope", "Approve this integration before making the request.", requiredIntegrationScope(row));
}
return {identity, integration: row};
}
Expand All @@ -132,7 +137,7 @@ export class AgentApiService {
}
result.push({...publicIntegration(row), access, ...(row.kind === "exe" && identity.kind === "oauth" && access === "granted" ? {vmGrantProvider: "exe.dev" as const} : {}), instructions: row.kind === "x" ? "Use the HTTP request endpoint with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use the HTTP request endpoint with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use the HTTP request endpoint with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use the HTTP request endpoint with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use the HTTP request endpoint with a path relative to /api/v2." : row.kind === "fly" ? "Use the HTTP request endpoint with a Fly Machines API path, such as /v1/apps." : row.kind === "model" ? "Use the HTTP request endpoint with an OpenAI-compatible path relative to /v1." : "Use the HTTP request endpoint with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions."});
}
return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(this.auth.scopes), proxy: {
return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(this.auth.scopes).filter(scope => !identity.policy.disabled_scopes.includes(scope)), proxy: {
requestUrl: this.env.APP_ORIGIN + "/api/v1/agent/requests",
readResponseUrl: this.env.APP_ORIGIN + "/api/v1/agent/responses/read",
authentication: identity.kind === "run" ? "Use your run identity helper." : "POST JSON with integration, method, and path. Use the agent OAuth credential with proxy:use. With the Factorize device launcher, curl -H @\"$FACTORIZE_AGENT_AUTH_FILE\" reads the authorization header.",
Expand Down
6 changes: 5 additions & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { queryOf } from "./query-params";
import { launchPayloadResponse } from "./launch-payload";
import { searchResponse } from "./search-contracts";
import { consentPreviewInput, consentPreviewResponse, consentDecisionInput, consentDecisionResponse } from "./consent-api";
import { exeConnection, integrationStatus, authorizedClient, accessToken, createdAccessToken, savedExe, testedExe, savedAmp, savedTail, okResult } from "./settings-contracts";
import { exeConnection, integrationStatus, clientPermissionsInput, authorizedClient, accessToken, createdAccessToken, savedExe, testedExe, savedAmp, savedTail, okResult } from "./settings-contracts";
import { triggerAvailabilityResponse, namedOption, providerOptions, githubInstallation, githubRepository, tailIntegration } from "./editor-contracts";
import { runSummaryResponse, runPageResponse, runStatusResponse, fullRunResponse, revisionTracePage, revisionTraceQuery, runtimeContextResponse, runtimeIntegrationsResponse } from "./run-read-contracts";
import { jobPageQuery, jobSummaryPage, jobSelectorPage, jobResponse, jobUpdateInput } from "./job-contracts";
Expand Down Expand Up @@ -675,6 +675,10 @@ export const API_ROUTES: RouteContract[] = [
(service, { params }) => service.revokeAccessToken(params.tokenId),
{ ownerSession: true },
),
route("PUT", "/api/v1/access/authorizations/{grantId}/permissions", "jobs:write", {
summary: "Edit an OAuth connection’s scopes and integration access",
responses: {"200": {description: "Permissions saved", content: {"application/json": {schema: jsonSchema(okResult, "output")}}}},
}, (service, {params, body}) => service.updateClientPermissions(params.grantId, body), {ownerSession: true, body: clientPermissionsInput}),
route("DELETE", "/api/v1/access/authorizations/{grantId}", "jobs:write", {summary:"Revoke one isolated OAuth connection", description:"Other connections, including copies of the same client, retain their approvals.",responses:{"200":{description:"Authorization revoked",content:{"application/json":{schema:jsonSchema(z.object({revoked:z.number().int()}),"output")}}}}}, (service,{params})=>service.revokeOAuthAuthorization(params.grantId), {ownerSession:true}),
route(
"DELETE",
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/consent-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export async function consentDecision(env: Env, session: Session, input: z.infer
const legacyRequest = parsed.scope.some(scope => scope === "flows:read" || scope === "flows: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 => !AGENT_SCOPES.includes(scope) && !isIntegrationScope(scope))) return null;
if (input.scopes.some(scope => !allowed.has(scope) && !allowed.has(normalizeScopes([scope])[0] ?? "") ) || selected.some(scope => !(AGENT_SCOPES as readonly string[]).includes(scope) && !isIntegrationScope(scope))) 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 Down
Loading