diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 0b43a584..cecb36ec 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -954,6 +954,30 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/access/authorizations/{grantId}/name": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Rename an authorized OAuth connection + * @description Interactive owner session required. Changes only this connection’s display name, not the registered app name or permissions. + * + * Requires the triggers:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + put: operations["put_api_v1_access_authorizations_grantId_name"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/access/authorizations/{grantId}/permissions": { parameters: { query?: never; @@ -4471,6 +4495,45 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + put_api_v1_access_authorizations_grantId_name: { + parameters: { + query?: never; + header?: never; + path: { + grantId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + name: string; + }; + }; + }; + responses: { + /** @description Connection renamed */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + name: string; + }; + }; + }; + 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"]; + }; + }; put_api_v1_access_authorizations_grantId_permissions: { parameters: { query?: never; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 2d7314e2..b3e84ef5 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -6,7 +6,7 @@ import {queryApiResponseInput,queryApiResponseResult} from "./agent-api-contract import { apiReflection, apiPolicyList, apiPolicyInput, requestApiInput, requestApiResponse, readApiResponseInput, apiResponseChunk } from "./agent-api-contracts"; import { queryOf } from "./query-params"; import { consentPreviewInput, consentPreviewResponse, consentDecisionInput, consentDecisionResponse } from "./consent-api"; -import { exeConnection, integrationStatus, clientPermissionsUpdate, authorizedClient, accessToken, createdAccessToken, savedExe, savedAmp, savedTail, okResult, permissionPreset, permissionPresetInput, permissionPresetList } from "./settings-contracts"; +import { exeConnection, integrationStatus, clientPermissionsUpdate, clientNameInput, authorizedClient, accessToken, createdAccessToken, savedExe, savedAmp, savedTail, okResult, permissionPreset, permissionPresetInput, permissionPresetList } from "./settings-contracts"; import { eventAvailabilityResponse, namedOption, providerOptions, githubInstallation, githubRepository, tailIntegration } from "./editor-contracts"; import { triggerResponse, triggerUpdateInput } from "./trigger-contracts"; import { z } from "zod"; @@ -547,6 +547,11 @@ export const API_ROUTES: RouteContract[] = [ (service, { params }) => service.revokeAccessToken(params.tokenId), { ownerSession: true }, ), + route("PUT", "/api/v1/access/authorizations/{grantId}/name", "triggers:write", { + summary: "Rename an authorized OAuth connection", + description: "Interactive owner session required. Changes only this connection’s display name, not the registered app name or permissions.", + responses: { "200": { description: "Connection renamed", content: { "application/json": { schema: jsonSchema(clientNameInput, "output") } } } }, + }, (service, { params, body }) => service.renameAuthorizedClient(params.grantId, body), { ownerSession: true, body: clientNameInput }), route("PUT", "/api/v1/access/authorizations/{grantId}/permissions", "triggers:write", { summary: "Set an OAuth connection’s effective scopes and integration access", description: "Interactive owner session required. Removing permissions takes effect immediately. A scope not carried by the current token requires a fresh OAuth authorization and token.", diff --git a/packages/api/src/api-service.ts b/packages/api/src/api-service.ts index 73495186..396e4296 100644 --- a/packages/api/src/api-service.ts +++ b/packages/api/src/api-service.ts @@ -554,6 +554,22 @@ export class ApiService { await databaseFor(this.env).pool.query("UPDATE app.agent_identities SET display_name=$3 WHERE tenant_id=$1 AND id=$2", [this.auth.tenantId, identity.id, name]); return { name }; } + async renameAuthorizedClient(grantId: string, input: unknown) { + await this.authorizeOwnerSession("triggers:write"); + const { name } = clientNameInput.parse(input); + const client = (await this.listAuthorizedClients()).find(client => client.grantId === grantId); + if (!client) throw new ServiceError(404, "not_found", "Authorization not found."); + // If this connection has never used its token, materialize its identity + // with the same initial integration blocks as the request path. + const result = await databaseFor(this.env).pool.query(` + INSERT INTO app.agent_identities AS i(tenant_id,kind,subject,user_id,session_version,display_name,integration_overrides) + VALUES($1,'oauth',$2,$3,$4,$5,$6) + ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET display_name=excluded.display_name + WHERE i.revoked_at IS NULL AND i.user_id=excluded.user_id + RETURNING display_name`, [this.auth.tenantId, grantId, this.auth.userId, this.auth.sessionVersion, name, JSON.stringify(client.integrationOverrides)]); + if (!result.rowCount) throw new ServiceError(404, "not_found", "Authorization not found."); + return { name }; + } private async validatePermissionScopes(input: string[]) { const { integrations } = await listAgentPolicies(this.env, this.auth.tenantId); const allowed = new Set([...AGENT_SCOPES, ...integrations.filter(row => row.available && row.policy !== "disabled").map(row => row.requiredScope)]); diff --git a/packages/api/test/connection-permissions.postgres.test.ts b/packages/api/test/connection-permissions.postgres.test.ts index ea652d3b..1b75ba1d 100644 --- a/packages/api/test/connection-permissions.postgres.test.ts +++ b/packages/api/test/connection-permissions.postgres.test.ts @@ -65,3 +65,49 @@ it.skipIf(!url)("preserves blocked integrations through a connection permission await f.cleanup(); } }); + + +it.skipIf(!url)("renames only the selected connection and preserves policy before and after identity creation", async () => { + const f = await loadingFixture(url!); + try { + const integrationId = crypto.randomUUID(), scope = `integration:${integrationId}:1`; + const grantId = "rename-fixture"; + const grants = [ + { id: grantId, metadata: { tenantId: f.tenantId, initialIntegrationDenials: [integrationId] } }, + { id: "sibling", metadata: { tenantId: f.tenantId } }, + { id: "other-team", metadata: { tenantId: f.otherTenant } }, + ].map(grant => ({ ...grant, clientId: "same-app", scope: ["proxy:use", scope], createdAt: Math.floor(Date.now() / 1000) })); + Object.assign(f.env, { OAUTH_PROVIDER: { + listUserGrants: async () => ({ items: grants }), + lookupClient: async () => ({ clientName: "Registered app" }), + } }); + await f.db.pool.query(`INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available,policy) + VALUES ($1,$2,'github','123','GitHub',true,'baseline')`, [f.tenantId, integrationId]); + const request = (path: string, body?: object, auth = f.auth) => protectedApiFetch(new Request(f.env.APP_ORIGIN + path, { + method: body ? "PUT" : "GET", headers: { Cookie: f.cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, + body: body && JSON.stringify(body), + }), f.env, auth, {} as ExecutionContext); + const rename = (id: string, name: string, auth = f.auth) => request(`/api/v1/access/authorizations/${id}/name`, { name }, auth); + const clients = async () => (await request("/api/v1/access/authorized-clients")).json() as Promise; + + expect((await rename("other-team", "Out of scope")).status).toBe(404); + expect((await rename(grantId, " ")).status).toBe(400); + expect((await rename(grantId, "Non-interactive", { ...f.auth, authMethod: "oauth" })).status).toBe(403); + const response = await rename(grantId, " Release assistant "); + expect(response.status, await response.clone().text()).toBe(200); + expect(await response.json()).toEqual({ name: "Release assistant" }); + expect(await clients()).toEqual(expect.arrayContaining([ + expect.objectContaining({ grantId, clientName: "Release assistant", appName: "Registered app", scopes: ["proxy:use"], revision: 0, integrationOverrides: { [integrationId]: false } }), + expect.objectContaining({ grantId: "sibling", clientName: "Registered app" }), + ])); + + const permissions = await request(`/api/v1/access/authorizations/${grantId}/permissions`, { scopes: ["team:read"], expectedRevision: 0 }); + expect(permissions.status, await permissions.text()).toBe(200); + expect((await rename(grantId, "Updated name")).status).toBe(200); + expect(await clients()).toContainEqual(expect.objectContaining({ + grantId, clientName: "Updated name", scopes: ["team:read"], revision: 1, integrationOverrides: { [integrationId]: false }, + })); + } finally { + await f.cleanup(); + } +}); diff --git a/packages/app/src/features/settings/authorized-clients.tsx b/packages/app/src/features/settings/authorized-clients.tsx index 23fcbbbf..bfff9429 100644 --- a/packages/app/src/features/settings/authorized-clients.tsx +++ b/packages/app/src/features/settings/authorized-clients.tsx @@ -2,11 +2,47 @@ import { useState } from "react"; import { Link, useParams } from "@tanstack/react-router"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; -import { Button, Page } from "../../shared/ui"; +import { Dialog } from "../../shared/dialog"; +import { Button, Input, Label, Page } from "../../shared/ui"; import { messageOf } from "../auth/session"; import { ClientPermissions, type AuthorizedClient } from "./client-permissions"; import { clientsQuery } from "./queries"; +function RenameConnection({ client }: { client: AuthorizedClient }) { + const cache = useQueryClient(); + const [editing, setEditing] = useState(false); + const [name, setName] = useState(""); + const rename = useMutation({ + retry: false, + mutationFn: async (name: string) => { + const { data, error } = await api.PUT("/api/v1/access/authorizations/{grantId}/name", { + params: { path: { grantId: client.grantId } }, body: { name }, + }); + if (!data || error) throw new Error(messageOf(error)); + return data; + }, + onSuccess: ({ name }) => { + cache.setQueryData(clientsQuery.queryKey, clients => + clients?.map(row => row.grantId === client.grantId ? { ...row, clientName: name } : row)); + setEditing(false); + return cache.invalidateQueries({ queryKey: clientsQuery.queryKey }); + }, + }); + return <> + + {editing && setEditing(false)}> +
{ + event.preventDefault(); + if (!rename.isPending && name.trim()) rename.mutate(name.trim()); + }}> + + {rename.error &&

{rename.error.message}

} + +
+
} + ; +} + function RevokeConnection({ client }: { client: AuthorizedClient }) { const cache = useQueryClient(); const revoke = useMutation({ @@ -47,7 +83,7 @@ export function ClientsPage() { {client.appName ?? client.clientName} {new Date(client.authorizationDate).toLocaleString()}
- +
)} } @@ -65,7 +101,7 @@ export function ClientPage() {

{client?.clientName ?? "Client connection"}

{clients.error &&

{clients.error.message}

} {client &&
- +
} {editing && client && setEditing(false)} />} ; diff --git a/packages/app/test/functional/client-permissions.spec.mjs b/packages/app/test/functional/client-permissions.spec.mjs index b328a1a0..847db4ed 100644 --- a/packages/app/test/functional/client-permissions.spec.mjs +++ b/packages/app/test/functional/client-permissions.spec.mjs @@ -58,3 +58,46 @@ test("saving client permissions keeps a blocked integration unchecked until expl integrationOverrides: { [integrationId]: integrationScope }, }); }); + + +test("renames a connection from the list and detail without changing the registered app or sibling connection", async ({ page, origin }) => { + const grant = { grantId: "primary", clientId: "same-app", clientName: "Registered app", appName: "Registered app", + availableScopes: ["team:read"], scopes: ["team:read"], revision: 0, scopeLabels: {}, integrationOverrides: {}, + authorizationDate: "2026-10-09T12:00:00Z", expiresAt: null, lastUsedAt: null }; + const writes = []; + await page.route("**/api/v1/session", route => route.fulfill({ json: { + authenticated: true, user: { id: "owner", email: "owner@example.test" }, + team: { id: "workspace", name: "Workspace", role: "owner" }, capabilities: [], + } })); + await page.route("**/api/v1/access/authorized-clients", route => route.fulfill({ json: [grant, + { ...grant, grantId: "sibling", clientName: "Other connection" }] })); + await page.route("**/api/v1/access/authorizations/primary/name", route => { + expect(route.request().method()).toBe("PUT"); + const body = route.request().postDataJSON(); + writes.push(body); + grant.clientName = body.name; + return route.fulfill({ json: body }); + }); + + await page.goto(origin + "/clients"); + const row = page.getByRole("row", { name: /Registered app/ }).filter({ has: page.getByRole("link", { name: "Registered app" }) }); + await row.getByRole("button", { name: "Rename connection" }).click(); + const name = page.getByRole("textbox", { name: "Connection name" }); + await expect(name).toHaveValue("Registered app"); + await name.fill(" "); + await expect(page.getByRole("button", { name: "Save name" })).toBeDisabled(); + await name.fill(" Release assistant "); + await name.press("Enter"); + await expect(page.getByRole("link", { name: "Release assistant" })).toBeVisible(); + await expect(page.getByRole("link", { name: "Other connection" })).toBeVisible(); + await expect(page.getByRole("cell", { name: "Registered app", exact: true })).toHaveCount(2); + + await page.getByRole("link", { name: "Release assistant" }).click(); + await expect(page.getByRole("heading", { name: "Release assistant", exact: true })).toBeVisible(); + await page.getByRole("button", { name: "Rename connection" }).click(); + await expect(name).toHaveValue("Release assistant"); + await name.fill("Updated assistant"); + await page.getByRole("button", { name: "Save name" }).click(); + await expect(page.getByRole("heading", { name: "Updated assistant" })).toBeVisible(); + expect(writes).toEqual([{ name: "Release assistant" }, { name: "Updated assistant" }]); +}); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index f2d05089..40d07f6c 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -4308,6 +4308,76 @@ paths: schema: type: string minLength: 1 + /api/v1/access/authorizations/{grantId}/name: + put: + summary: Rename an authorized OAuth connection + description: |- + Interactive owner session required. Changes only this connection’s display name, not the registered app name or permissions. + + Requires the triggers:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Connection renamed + content: + application/json: + schema: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 120 + required: + - name + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: put_api_v1_access_authorizations_grantId_name + tags: + - access + security: + - cookieAuth: [] + x-required-scope: triggers:write + x-owner-session-required: true + parameters: + - name: grantId + in: path + required: true + schema: + type: string + minLength: 1 + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 120 + required: + - name + additionalProperties: false /api/v1/access/authorizations/{grantId}/permissions: put: summary: Set an OAuth connection’s effective scopes and integration access