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
63 changes: 63 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
7 changes: 6 additions & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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.",
Expand Down
16 changes: 16 additions & 0 deletions packages/api/src/api-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)]);
Expand Down
46 changes: 46 additions & 0 deletions packages/api/test/connection-permissions.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<unknown[]>;

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();
}
});
42 changes: 39 additions & 3 deletions packages/app/src/features/settings/authorized-clients.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <>
<Button disabled={rename.isPending} onClick={() => { rename.reset(); setName(client.clientName); setEditing(true); }}>Rename connection</Button>
{editing && <Dialog title="Rename connection" close={() => setEditing(false)}>
<form className="grid gap-3" onSubmit={event => {
event.preventDefault();
if (!rename.isPending && name.trim()) rename.mutate(name.trim());
}}>
<Label>Connection name<Input value={name} onChange={event => setName(event.target.value)} maxLength={120} required disabled={rename.isPending} /></Label>
{rename.error && <p role="alert">{rename.error.message}</p>}
<Button type="submit" variant="primary" disabled={rename.isPending || !name.trim()}>Save name</Button>
</form>
</Dialog>}
</>;
}

function RevokeConnection({ client }: { client: AuthorizedClient }) {
const cache = useQueryClient();
const revoke = useMutation({
Expand Down Expand Up @@ -47,7 +83,7 @@ export function ClientsPage() {
<td className="px-2 py-3">{client.appName ?? client.clientName}</td>
<td className="px-2 py-3">{new Date(client.authorizationDate).toLocaleString()}</td>
<td className="px-2 py-3"><div className="flex flex-wrap gap-2">
<Button onClick={() => setEditing(client)}>Edit permissions</Button><RevokeConnection client={client} />
<Button onClick={() => setEditing(client)}>Edit permissions</Button><RenameConnection client={client} /><RevokeConnection client={client} />
</div></td>
</tr>)}</tbody>
</table></div>}
Expand All @@ -65,7 +101,7 @@ export function ClientPage() {
<h1 className="my-4">{client?.clientName ?? "Client connection"}</h1>
{clients.error && <p role="alert">{clients.error.message}</p>}
{client && <div className="mb-4 flex flex-wrap gap-2">
<Button onClick={() => setEditing(true)}>Edit permissions</Button><RevokeConnection client={client} />
<Button onClick={() => setEditing(true)}>Edit permissions</Button><RenameConnection client={client} /><RevokeConnection client={client} />
</div>}
{editing && client && <ClientPermissions client={client} close={() => setEditing(false)} />}
</Page>;
Expand Down
43 changes: 43 additions & 0 deletions packages/app/test/functional/client-permissions.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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" }]);
});
70 changes: 70 additions & 0 deletions packages/docs/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading