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
16 changes: 13 additions & 3 deletions packages/api/test/consent-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import { decideDevice, deviceAuthorization, inspectDevice } from "../src/device-
import type { Env } from "../src/types";
const session = { tenantId: "tenant", userId: "owner", email: "owner@example.test", sessionVersion: 2, exp: Math.floor(Date.now() / 1000) + 3600 };
const parsed = { responseType: "code", clientId: "client", redirectUri: "https://client.test/callback", scope: ["team:read", "triggers:read", "integrations:read", "triggers:read", "triggers:write", "triggers:write", "triggers:write"], state: "state", codeChallenge: "challenge", codeChallengeMethod: "S256", resource: "https://factorize.test/mcp", issuer: "https://factorize.test" };
function fixture() {
function fixture(defaultPreset?: string[]) {
const values = new Map<string, string>();
const used = new Set<string>();
const query = vi.fn(async (sql: string, args: unknown[]) => {
if (sql.startsWith("SELECT scopes FROM app.permission_presets")) return { rows: defaultPreset ? [{ scopes: defaultPreset }] : [] };
if (sql.startsWith("INSERT INTO app.oauth_consent_previews") ||
sql.startsWith("DELETE FROM app.oauth_consent_previews") ||
sql.startsWith("SELECT scopes FROM app.permission_presets")) return { rows: [] };
sql.startsWith("DELETE FROM app.oauth_consent_previews")) return { rows: [] };
if (!sql.startsWith("UPDATE app.oauth_consent_previews")) throw new Error(`Unexpected consent query: ${sql}`);
const id = String(args[0]);
if (used.has(id)) return { rows: [] };
Expand All @@ -36,6 +36,16 @@ describe("static consent support", () => {
oauth.lookupClient.mockResolvedValue({ clientId: "client", clientName: "External client", redirectUris: ["https://other.test/callback"], tokenEndpointAuthMethod: "none" });
expect(await consentDecision(env, session, input)).toBeNull();
});
it("issues the approved default preset scopes", async () => {
const { env, oauth } = fixture(["team:read"]);
const preview = (await consentPreview(env, session, { authorizationQuery: "client_id=client" }))!;
expect(preview.selectedScopes).toEqual(["team:read"]);
const input = { request: preview.request, signature: preview.signature, decision: "allow" as const, scopes: preview.selectedScopes };
expect((await consentDecision(env, session, input))?.redirectTo).toContain("code=authorized");
expect(oauth.completeAuthorization).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({
scope: ["team:read"], props: expect.objectContaining({ scopes: ["team:read"] }),
}));
});
it("expires consent bindings and preserves state and issuer on denial", async () => {
const { env } = fixture();
vi.useFakeTimers();
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/features/auth/consent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { messageOf } from "./session";
export function ConsentScreen() {
const authorizationQuery = location.search.slice(1), [selected, setSelected] = useState<string[] | null>(null);
const preview = useQuery({ queryKey: ["consent", authorizationQuery], queryFn: async ({ signal }) => { const { data, error } = await api.POST("/api/v1/oauth/consent/preview", { signal, body: { authorizationQuery } }); if (!data || error) throw new Error(messageOf(error)); return data; }, staleTime: 0, retry: false });
const decision = useMutation({ retry: false, mutationFn: async (value: "allow" | "deny") => { if (!preview.data) throw new Error("Load the authorization request first."); const { data, error } = await api.POST("/api/v1/oauth/consent/decision", { body: { request: preview.data.request, signature: preview.data.signature, decision: value, scopes: selected ?? preview.data.scopes } }); if (!data || error) throw new Error(messageOf(error)); location.assign(data.redirectTo); } });
const scopes = selected ?? preview.data?.selectedScopes ?? preview.data?.scopes ?? [];
const decision = useMutation({ retry: false, mutationFn: async (value: "allow" | "deny") => { if (!preview.data) throw new Error("Load the authorization request first."); const { data, error } = await api.POST("/api/v1/oauth/consent/decision", { body: { request: preview.data.request, signature: preview.data.signature, decision: value, scopes } }); if (!data || error) throw new Error(messageOf(error)); location.assign(data.redirectTo); } });
return <Page className="my-8 flex-none max-w-xl rounded-2xl border border-stone-200 bg-white p-6 shadow-sm dark:border-slate-800 dark:bg-slate-900"><h1 className="text-3xl font-semibold">Authorize {preview.data?.clientName ?? "a client"}</h1>{preview.isPending && <p role="status">Validating authorization request…</p>}{preview.error && <p role="alert">{preview.error.message}</p>}
{preview.data && <><p>This client requests workspace access. Permissions are independent; write does not imply read. Trigger writes may cause future schedule/webhook/lifecycle execution. Request expires {preview.data.expiresAt}.</p><fieldset><legend>Permissions</legend>{preview.data.scopes.map(scope => <Label className="block" key={scope}><Input aria-label={scope} type="checkbox" checked={scopes.includes(scope)} onChange={e => setSelected(e.target.checked ? [...scopes, scope] : scopes.filter(s => s !== scope))} />{preview.data.integrationLabels?.find(label => label.scope === scope)?.name ?? scope}{preview.data.integrationLabels?.find(label => label.scope === scope)?.description && <span className="block text-sm">{preview.data.integrationLabels.find(label => label.scope === scope)?.description}</span>}</Label>)}</fieldset><Button variant="primary" disabled={decision.isPending} onClick={() => decision.mutate("allow")}>Allow</Button><Button disabled={decision.isPending} onClick={() => decision.mutate("deny")}>Deny</Button></>}{decision.error && <p role="alert">{decision.error.message}</p>}
</Page>;
Expand Down
26 changes: 26 additions & 0 deletions packages/app/test/functional/protocol.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,32 @@ test("consent refresh preserves OAuth query, scope selection and server-owned re
await page.goto(origin + "/authorize?client_id=client&state=original&code_challenge=challenge"); await page.getByRole("heading", { name: "Authorize External CLI" }).waitFor(); await page.reload(); await page.getByLabel("triggers:write").uncheck(); await page.getByRole("button", { name: "Allow", exact: true }).click(); await page.waitForURL("**/completed?code=issued");
assert.equal(previews.at(-1).authorizationQuery, "client_id=client&state=original&code_challenge=challenge"); assert.deepEqual(decision, { request: "signed-request", signature: "signature", decision: "allow", scopes: ["team:read", "triggers:read", "integrations:read"] }); await context.close();
});
for (const presetScopes of [["team:read"], []]) {
test(`Allow submits the displayed preset selection (${presetScopes.join(", ") || "empty"}) without any checkbox changes`, async () => {
const { context, page } = await setup();
try {
await page.route("**/api/v1/oauth/consent/preview", route => route.fulfill({ json: {
clientName: "External CLI", scopes: ["team:read", "triggers:write"], selectedScopes: presetScopes,
request: "signed-request", signature: "signature", expiresAt: "2026-10-09T12:00:00Z",
} }));
let decision;
await page.route("**/api/v1/oauth/consent/decision", route => {
decision = route.request().postDataJSON();
return route.fulfill({ json: { redirectTo: origin + "/completed?code=issued" } });
});

await page.goto(origin + "/authorize?client_id=client&state=original&code_challenge=challenge");
await page.getByRole("heading", { name: "Authorize External CLI" }).waitFor();
assert.equal(await page.getByLabel("team:read", { exact: true }).isChecked(), presetScopes.includes("team:read"));
assert.equal(await page.getByLabel("triggers:write", { exact: true }).isChecked(), false);
await page.getByRole("button", { name: "Allow", exact: true }).click();
await page.waitForURL("**/completed?code=issued");
assert.deepEqual(decision, { request: "signed-request", signature: "signature", decision: "allow", scopes: presetScopes });
} finally {
await context.close();
}
});
}
test("device deep link loads metadata and approval sends no protocol tokens", async () => {
const { context, page } = await setup(); let decision;
await page.route("**/api/v1/oauth/device/preview", route => route.fulfill({ json: { userCode: "ABCD-EFGH", clientName: "My CLI", signature: "device-signature", scopes: ["team:read", "triggers:read", "integrations:read"], expiresAt: "2026-10-09T12:00:00Z" } }));
Expand Down
Loading