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
1 change: 1 addition & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5269,6 +5269,7 @@ export interface operations {
clientId: string;
clientName: string;
appName?: string;
ownerUsername?: string;
scopes: string[];
authorizationDate: string;
expiresAt: string | null;
Expand Down
14 changes: 11 additions & 3 deletions packages/api/src/api-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -677,9 +677,17 @@ export class ApiService {
if (!this.env.OAUTH_PROVIDER) throw new ServiceError(503, "operation_failed", "OAuth management unavailable");
const grants: any[] = []; let cursor: string | undefined;
do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => (grant.metadata as any)?.tenantId === this.auth.tenantId && (!grant.expiresAt || grant.expiresAt > Math.floor(Date.now() / 1000)))); cursor = page.cursor; } while (cursor);
const clients = await Promise.all([...new Set(grants.map(grant => grant.clientId))].map(async clientId => [clientId, await this.env.OAUTH_PROVIDER!.lookupClient(clientId)] as const));
if (!grants.length) return [];
// listUserGrants is scoped to the authenticated owner; do not read account
// information for another user or expose grants from another workspace.
const db = databaseFor(this.env);
const [clients, settings, owner] = await Promise.all([
Promise.all([...new Set(grants.map(grant => grant.clientId))].map(async clientId => [clientId, await this.env.OAUTH_PROVIDER!.lookupClient(clientId)] as const)),
db.pool.query("SELECT subject,display_name,disabled_scopes,scope_overrides,integration_overrides,permissions_revision FROM app.agent_identities WHERE tenant_id=$1 AND user_id=$2 AND kind='oauth' AND subject=ANY($3)", [this.auth.tenantId, this.auth.userId, grants.map(g => g.id)]),
db.pool.query<{ username: string }>("SELECT username FROM app.auth_users WHERE id=$1", [this.auth.userId]),
]);
const byId = new Map(clients);
const settings = await databaseFor(this.env).pool.query("SELECT subject,display_name,disabled_scopes,scope_overrides,integration_overrides,permissions_revision FROM app.agent_identities WHERE tenant_id=$1 AND user_id=$2 AND kind='oauth' AND subject=ANY($3)", [this.auth.tenantId, this.auth.userId, grants.map(g => g.id)]);
const ownerUsername = owner.rows[0]?.username;
const byGrant = new Map(settings.rows.map(row => [row.subject, row]));
const { integrations } = await listAgentPolicies(this.env, this.auth.tenantId);
const globallyAvailable = [...AGENT_SCOPES, ...integrations.filter(row => row.available && row.policy !== "disabled").map(row => row.requiredScope)];
Expand All @@ -696,7 +704,7 @@ export class ApiService {
const availableScopes = [...new Set([...globallyAvailable, ...scopes])];
return { grantId: grant.id, clientId: grant.clientId, clientName: row?.display_name ?? byId.get(grant.clientId)?.clientName ?? grant.clientId, appName: byId.get(grant.clientId)?.clientName ?? grant.clientId,
availableScopes, scopeLabels, scopes, revision: row?.permissions_revision ?? 0,
integrationOverrides, authorizationDate: new Date(grant.createdAt * 1000).toISOString(),
integrationOverrides, ownerUsername, authorizationDate: new Date(grant.createdAt * 1000).toISOString(),
expiresAt: grant.expiresAt ? new Date(grant.expiresAt * 1000).toISOString() : null, lastUsedAt: null };
}));
}
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/settings-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const clientPermissionsInput = z.object({
expectedRevision: z.number().int().nonnegative().optional(),
}).strict().refine(value => value.scopes !== undefined || value.disabledScopes !== undefined || value.integrationOverrides !== undefined, "Supply a scope selection.");
export const clientPermissionsUpdate = clientPermissionsInput;
export const authorizedClient = z.object({ availableScopes: z.array(z.string()), scopeLabels: z.record(z.string(),z.string()).default({}), integrationOverrides: z.record(z.uuid(), z.union([z.string(), z.literal(false)])).default({}), revision: z.number().int(), grantId: z.string(), clientId: z.string(), clientName: z.string(), appName: z.string().optional(), scopes: z.array(z.string()), authorizationDate: timestamp, expiresAt: timestamp.nullable(), lastUsedAt: timestamp.nullable() });
export const authorizedClient = z.object({ availableScopes: z.array(z.string()), scopeLabels: z.record(z.string(),z.string()).default({}), integrationOverrides: z.record(z.uuid(), z.union([z.string(), z.literal(false)])).default({}), revision: z.number().int(), grantId: z.string(), clientId: z.string(), clientName: z.string(), appName: z.string().optional(), ownerUsername: z.string().optional(), scopes: z.array(z.string()), authorizationDate: timestamp, expiresAt: timestamp.nullable(), lastUsedAt: timestamp.nullable() });
export const accessToken = z.object({ id: z.string(), name: z.string(), scopes: z.array(z.enum(ACCESS_SCOPES)), created_at: timestamp, expires_at: timestamp, last_used_at: timestamp.nullable().optional(), revoked_at: timestamp.nullable().optional() });
export const createdAccessToken = accessToken.extend({ token: z.string() });
export const okResult = z.object({ ok: z.boolean() });
Expand Down
21 changes: 14 additions & 7 deletions packages/api/test/connection-permissions.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,19 @@ it.skipIf(!url)("renames only the selected connection and preserves policy befor
try {
const integrationId = crypto.randomUUID(), scope = `integration:${integrationId}:1`;
const grantId = "rename-fixture";
await f.db.pool.query("UPDATE app.auth_users SET username=$1 WHERE id=$2", ["actual-owner", f.userId]);
const now = Math.floor(Date.now() / 1000);
const grants = [
{ id: grantId, metadata: { tenantId: f.tenantId, initialIntegrationDenials: [integrationId] } },
{ id: grantId, metadata: { tenantId: f.tenantId, initialIntegrationDenials: [integrationId] }, expiresAt: now + 86400 },
{ 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) }));
{ id: "expired-grant", metadata: { tenantId: f.tenantId }, expiresAt: now - 1 },
].map(grant => ({ ...grant, clientId: "same-app", scope: ["proxy:use", scope], createdAt: now }));
Object.assign(f.env, { OAUTH_PROVIDER: {
listUserGrants: async () => ({ items: grants }),
listUserGrants: async (userId: string) => {
expect(userId).toBe(f.userId);
return { 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)
Expand All @@ -96,10 +102,11 @@ it.skipIf(!url)("renames only the selected connection and preserves policy befor
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" }),
]));
expect(await clients()).toEqual([
expect.objectContaining({ grantId, clientName: "Release assistant", appName: "Registered app", ownerUsername: "actual-owner", scopes: ["proxy:use"], revision: 0, integrationOverrides: { [integrationId]: false }, authorizationDate: new Date(now * 1000).toISOString(), expiresAt: new Date((now + 86400) * 1000).toISOString() }),
expect.objectContaining({ grantId: "sibling", clientName: "Registered app", ownerUsername: "actual-owner", expiresAt: null }),
]);
expect((await request("/api/v1/access/authorized-clients", undefined, { ...f.auth, authMethod: "oauth" })).status).toBe(403);

const permissions = await request(`/api/v1/access/authorizations/${grantId}/permissions`, { scopes: ["team:read"], expectedRevision: 0 });
expect(permissions.status, await permissions.text()).toBe(200);
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/features/apps/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function ConnectedAppsPage() {
},
onSuccess: () => cache.invalidateQueries({ queryKey: connectedKey }),
});
return <Page><PageHeader title="Connected apps" />
return <Page><PageHeader title="Apps" description="Apps connected to this Team" />
{connected.isPending && <p role="status">Loading connected apps…</p>}
{connected.error && <p role="alert">{connected.error.message}</p>}
{revoke.error && <p role="alert">{revoke.error.message}</p>}
Expand Down
4 changes: 2 additions & 2 deletions packages/app/src/features/events/events.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "factorize-api-client";
import { Button, Page } from "../../shared/ui";
import { Button, Page, PageHeader } from "../../shared/ui";

export function EventsPage() {
const client = useQueryClient();
Expand All @@ -20,7 +20,7 @@ export function EventsPage() {
const result = await api.DELETE("/api/v1/events/{eventId}", { params: { path: { eventId } } });
if (result.error) throw new Error(result.error.error?.message ?? "Could not delete Event");
}, onSuccess: async (_result, eventId) => { if (selected === eventId) setSelected(undefined); await client.invalidateQueries({ queryKey: ["events"] }); } });
return <Page><header className="mb-8"><p className="text-xs font-semibold uppercase tracking-widest text-factorize-700">Event stream</p><h1>Events</h1><p className="mt-2 text-slate-600 dark:text-slate-400">Durable occurrences published by Triggers. Subscribe to an Event’s occurrence resource over MCP.</p></header>
return <Page><PageHeader title="Events" description="MCP Events to help coordinate your agents" />
{events.error && <p role="alert">{events.error.message}</p>}
{remove.error && <p role="alert">{remove.error.message}</p>}
<div className="grid gap-6 lg:grid-cols-2"><section><h2>Defined Events</h2><ul className="mt-3 divide-y divide-stone-200 dark:divide-slate-800">{(events.data ?? []).map(item => <li key={item.id} className="flex items-start justify-between gap-3 py-3"><button className="text-left" onClick={() => setSelected(item.id)}><strong>{item.name}</strong><span className="block text-sm text-slate-500">{item.description || "No description"} · {item.triggerCount} Triggers · {item.occurrenceCount} occurrences</span></button><Button disabled={remove.isPending} onClick={() => {if(window.confirm(`Delete ${item.name}, its Triggers, and all occurrence history?`))remove.mutate(item.id);}}>Delete</Button></li>)}</ul>{events.data?.length === 0 && <p>No Events yet.</p>}</section>
Expand Down
56 changes: 33 additions & 23 deletions packages/app/src/features/settings/authorized-clients.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { Link, useParams } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "factorize-api-client";
import { Dialog } from "../../shared/dialog";
import { Button, Input, Label, Page } from "../../shared/ui";
import {
Button, Input, Label, Page, PageHeader, Table, tableCellClasses, tableHeadClasses, tableRowClasses,
} from "../../shared/ui";
import { messageOf } from "../auth/session";
import { ClientPermissions, type AuthorizedClient } from "./client-permissions";
import { clientsQuery } from "./queries";
Expand Down Expand Up @@ -63,31 +65,30 @@ function RevokeConnection({ client }: { client: AuthorizedClient }) {
</>;
}

function ConnectionDate({ value }: { value: string | null }) {
return value ? <time dateTime={value}>{new Date(value).toLocaleString()}</time> : "No expiration";
}

export function ClientsPage() {
const clients = useQuery(clientsQuery);
const [editing, setEditing] = useState<AuthorizedClient | null>(null);
return <Page>
<h1 className="mb-4">Clients</h1>
<PageHeader title="Clients" description="All of the connected MCP clients" />
{clients.isPending && <p role="status">Loading clients…</p>}
{clients.error && <p role="alert">{clients.error.message}</p>}
{clients.data?.length === 0 && <p>No authorized clients.</p>}
{!!clients.data?.length && <div className="overflow-x-auto"><table aria-label="MCP connections" className="w-full text-left text-sm">
<thead><tr>
<th className="px-2 py-3">Connection</th>
<th className="px-2 py-3">App</th>
<th className="px-2 py-3">Authorized</th>
<th className="px-2 py-3">Actions</th>
{!!clients.data?.length && <Table aria-label="MCP connections">
<thead className={tableHeadClasses}><tr>
{["Username", "Connection", "App", "Authorized", "Expires"].map(label =>
<th scope="col" className={tableCellClasses} key={label}>{label}</th>)}
</tr></thead>
<tbody>{clients.data.map(client => <tr className="border-t border-stone-200 dark:border-slate-800" key={client.grantId}>
<th scope="row" className="px-2 py-3 font-medium"><Link className="underline" to="/clients/$grantId" params={{ grantId: client.grantId }}>{client.clientName}</Link></th>
<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><RenameConnection client={client} /><RevokeConnection client={client} />
</div></td>
<tbody>{clients.data.map(client => <tr className={tableRowClasses} key={client.grantId}>
<td className={tableCellClasses}>{client.ownerUsername ?? "—"}</td>
<th scope="row" className={`${tableCellClasses} font-medium`}><Link className="underline" to="/clients/$grantId" params={{ grantId: client.grantId }}>{client.clientName}</Link></th>
<td className={tableCellClasses}>{client.appName ?? client.clientName}</td>
<td className={`${tableCellClasses} whitespace-nowrap`}><ConnectionDate value={client.authorizationDate} /></td>
<td className={`${tableCellClasses} whitespace-nowrap`}><ConnectionDate value={client.expiresAt} /></td>
</tr>)}</tbody>
</table></div>}
{editing && <ClientPermissions client={editing} close={() => setEditing(null)} />}
</Table>}
</Page>;
}

Expand All @@ -97,12 +98,21 @@ export function ClientPage() {
const client = clients.data?.find(item => item.grantId === grantId);
const [editing, setEditing] = useState(false);
return <Page>
<Link to="/clients" className="underline">Clients</Link>
<h1 className="my-4">{client?.clientName ?? "Client connection"}</h1>
<PageHeader title={client?.clientName ?? "Client connection"} />
{clients.isPending && <p role="status">Loading client…</p>}
{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><RenameConnection client={client} /><RevokeConnection client={client} />
</div>}
{!clients.isPending && !clients.error && !client && <p>Client connection not found.</p>}
{client && <>
<dl className="mb-5 grid gap-4 text-sm sm:grid-cols-2 lg:grid-cols-4">
<div><dt className="font-semibold">Username</dt><dd>{client.ownerUsername ?? "—"}</dd></div>
<div><dt className="font-semibold">Client</dt><dd>{client.appName ?? client.clientName}</dd></div>
<div><dt className="font-semibold">Authorized</dt><dd><ConnectionDate value={client.authorizationDate} /></dd></div>
<div><dt className="font-semibold">Expires</dt><dd><ConnectionDate value={client.expiresAt} /></dd></div>
</dl>
<div className="mb-4 flex flex-wrap gap-2">
<Button onClick={() => setEditing(true)}>Edit permissions</Button><RenameConnection client={client} /><RevokeConnection client={client} />
</div>
</>}
{editing && client && <ClientPermissions client={client} close={() => setEditing(false)} />}
</Page>;
}
2 changes: 1 addition & 1 deletion packages/app/src/features/workloads/workloads.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export function WorkloadsPage() {
const state = useVmGrants();
const rows = state.canRead ? state.grants.data : undefined;
return <Page>
<PageHeader title="Workloads" description="Workloads with access to Factorize." />
<PageHeader title="Workloads" description="Virtual Machines, VPSs, and other workloads that have been granted permissions" />
<GrantStatus {...state} />
{rows?.length === 0 && <p>No workloads have Factorize permissions.</p>}
{!!rows?.length && <Table aria-label="Workloads">
Expand Down
2 changes: 1 addition & 1 deletion packages/app/test/functional/apps.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ test("Connected apps use the dashboard tab and Registered apps live in Settings"
await page.goto(origin + "/apps");
const dashboard = page.getByRole("navigation", { name: "Dashboard navigation" });
await expect(dashboard.getByRole("link", { name: "Apps", exact: true })).toHaveAttribute("aria-current", "page");
await expect(page.getByRole("heading", { name: "Connected apps" })).toBeVisible();
await expect(page.getByRole("heading", { name: "Apps", level: 1 })).toBeVisible();
await expect(page.getByText("No connected apps.")).toBeVisible();
await expect(page.getByRole("link", { name: "Registered apps" })).toHaveCount(0);

Expand Down
Loading
Loading