diff --git a/changes/fix-api-old-keys-refused.md b/changes/fix-api-old-keys-refused.md new file mode 100644 index 000000000..833410c5f --- /dev/null +++ b/changes/fix-api-old-keys-refused.md @@ -0,0 +1,8 @@ +### Changed — may break callers + +- **An old flat `api` key is refused, not honoured: rename it to the key the refusal names.** A config that still names + `api.contacts-list` after the generated `api` group put that command under `api contacts list` no longer has the key + checked beside the new one. Every command refuses to run, `mcp serve` refuses to start, and `config set` refuses the + key, each with `configuration_error` or `validation_error` saying "its command moved, so rename it to + permissions.api.contacts.list". A moved path keeps no alias, its key included (WC-CMD-8). Until a CLI regenerates + with groups, no key moved and nothing changes. diff --git a/src/cli/config-command.ts b/src/cli/config-command.ts index eb9f36385..e05c95274 100644 --- a/src/cli/config-command.ts +++ b/src/cli/config-command.ts @@ -15,6 +15,7 @@ import { knownBeside, knownPermissionKeys, type PermissionKeySource, + renamedPermissionKeys, unknownPermissionIssues, } from "./permission-keys.js" import { profileFree } from "./profile.js" @@ -352,13 +353,19 @@ export const refuseUnknownKey = ( : [] if (keys.length === 0) return const known = knownPermissionKeys(command, permissionKey) + const renamed = renamedPermissionKeys(command) for (const key of keys) { if (known.has(key)) continue const beside = knownBeside(key, known) + const now = renamed.get(key) throw new CliError( "validation_error", `permissions.${key} names no command` + - (beside.length > 0 ? ` — the known ones there are ${beside.join(", ")}` : ""), + (now !== undefined + ? `: its command moved, so use permissions.${now}` + : beside.length > 0 + ? ` — the known ones there are ${beside.join(", ")}` + : ""), ) } } diff --git a/src/cli/config-issues.ts b/src/cli/config-issues.ts index 84d6a602b..8a766e594 100644 --- a/src/cli/config-issues.ts +++ b/src/cli/config-issues.ts @@ -280,10 +280,19 @@ export const permissionIssues = ( saved: readonly { key: string; at: readonly string[] }[], known: ReadonlySet, context: { file: string; tool: string }, + /** Old key → the key of the command it moved to, so the refusal names what to rename it to. */ + renamed: ReadonlyMap = new Map(), ): LocatedIssue[] => saved .filter(({ key }) => !known.has(key)) - .map(({ at }) => locate("unknown_permission", at, context, (key) => `${key} names no command`)) + .map(({ key: name, at }) => + locate("unknown_permission", at, context, (key) => { + const now = renamed.get(name) + return now === undefined + ? `${key} names no command` + : `${key} names no command: its command moved, so rename it to permissions.${now}` + }), + ) const pathId = (path: readonly string[]) => path.join("\u0000") diff --git a/src/cli/permission-keys.ts b/src/cli/permission-keys.ts index ed1d17e80..1daa253c7 100644 --- a/src/cli/permission-keys.ts +++ b/src/cli/permission-keys.ts @@ -118,6 +118,19 @@ export const knownPermissionKeys = ( return known } +const RENAMED = new WeakMap>() + +/** + * Old keys of commands that moved, on the group that moved them (the generated `api` group, `api.contacts-list` → + * `api.contacts.list`): such a key is still refused like any unknown one (WC-CMD-8), and the refusal names the new key. + */ +export const markRenamedPermissionKeys = (command: Command, renamed: ReadonlyMap) => { + if (renamed.size > 0) RENAMED.set(command, renamed) +} + +export const renamedPermissionKeys = (command: Command): Map => + new Map(everyCommand(rootOf(command)).flatMap((one) => [...(RENAMED.get(one) ?? [])])) + /** The known keys one level under the unknown key's parent, to name in the refusal. */ export const knownBeside = (key: PermissionKey, known: ReadonlySet): PermissionKey[] => { const parent = key.split(".").slice(0, -1).join(".") @@ -144,9 +157,12 @@ export const unknownPermissionIssues = ( Object.keys(settings.permissions) .filter((key) => key !== CEILING_KEY && settings.permissionSources[key] !== "flag") .map((key) => ({ key, at: ["profiles", settings.profile, "permissions", key] })) - return permissionIssues(saved, knownPermissionKeys(command, keyOf), { file: settings.configPath, tool }).map( - publicIssue, - ) + return permissionIssues( + saved, + knownPermissionKeys(command, keyOf), + { file: settings.configPath, tool }, + renamedPermissionKeys(command), + ).map(publicIssue) } /** @@ -166,6 +182,11 @@ export const refuseUnknownPermissionKeys = ( Object.fromEntries(flagged.map((one) => [one, true])), knownPermissionKeys(command, keyOf), ) - if (key !== undefined) - throw new CliError("validation_error", `--permission ${key} names no command`, { permission: key }) + if (key === undefined) return + const now = renamedPermissionKeys(command).get(key) + throw new CliError( + "validation_error", + `--permission ${key} names no command${now === undefined ? "" : `: its command moved, so use ${now}`}`, + { permission: key }, + ) } diff --git a/src/cli/service-api-groups.test.ts b/src/cli/service-api-groups.test.ts index 7b0e959f8..125790275 100644 --- a/src/cli/service-api-groups.test.ts +++ b/src/cli/service-api-groups.test.ts @@ -1,11 +1,14 @@ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" +import { PassThrough } from "node:stream" import { captureStreams } from "@wirecat/cli-base" import type { ManifestOperation } from "@wirecat/cli-base/codegen" import { hostFetch } from "@wirecat/cli-base/http" import { describe, expect, it } from "vitest" +import { appMcpCommand } from "./app-mcp-command.js" import { generatedApiCommand } from "./bot/api.js" +import { configCommand } from "./config-command.js" import { commandPermissions } from "./permission-keys.js" import { run } from "./program.js" import { serviceApiPermissions } from "./service-api.js" @@ -77,11 +80,15 @@ const fixture = (saved: Record = {}) => { schemas: async () => ({}), definitions: async () => ({}), }), + configCommand(app, configuration), + appMcpCommand(app, configuration, { name: "CRM", untrusted: ["contact names"], permissionExample: "api=deny" }), ], } const cli = async (...args: string[]) => { const streams = captureStreams() - const code = await run(args, definition, { streams, env, tty: false }) + const stdin = new PassThrough() + stdin.end() + const code = await run(args, definition, { streams, env, tty: false, stdin, stdout: new PassThrough() }) const out = streams.stdout.join("") const err = streams.stderr.join("") return { @@ -133,36 +140,30 @@ describe("api subgroups", () => { expect(sent).toEqual(["GET /pages"]) }) - it("keeps an old flat key as an alias that only tightens, and says to rename it", async () => { - const denied = fixture({ "api.contacts-list": "deny" }) - const refused = await denied.cli("work", "api", "contacts", "list", "--json") - expect(refused.error).toMatchObject({ code: "permission_error" }) - expect(refused.err).toContain("rename it to api.contacts.list") - expect(denied.sent).toEqual([]) - - const loose = fixture({ "api.contacts": "deny", "api.contacts-list": "allow" }) - expect((await loose.cli("work", "api", "contacts", "list", "--json")).error).toMatchObject({ - code: "permission_error", - }) - expect(loose.sent).toEqual([]) - - const readonly = fixture({ "api.contacts-list": "readonly", "api.contacts-create": "readonly" }) - expect((await readonly.cli("work", "api", "contacts", "list", "--json")).code).toBe(0) - expect((await readonly.cli("work", "api", "contacts", "create", "--json")).error).toMatchObject({ - code: "permission_error", - }) - expect(readonly.sent).toEqual(["GET /contacts"]) + it("refuses an old flat key and names the key to rename it to, whatever its level", async () => { + for (const level of ["deny", "allow"]) { + const old = fixture({ "api.contacts-list": level }) + const refused = await old.cli("work", "api", "pages", "list", "--json") + expect(refused.error).toMatchObject({ code: "configuration_error" }) + expect(refused.error?.message).toContain("rename it to permissions.api.contacts.list") + expect(old.sent).toEqual([]) + } + const served = await fixture({ "api.contacts-list": "deny" }).cli("work", "mcp", "serve") + expect(served.code).not.toBe(0) + expect(served.err).toContain("rename it to permissions.api.contacts.list") + const flagged = await fixture().cli("work", "mcp", "serve", "--permission", "api.contacts-list=deny") + expect(flagged.code).not.toBe(0) + expect(flagged.err).toContain("its command moved, so use api.contacts.list") + const set = await fixture().cli("work", "config", "set", "permissions.api.contacts-list", "deny") + expect(set.error?.message).toContain("its command moved, so use permissions.api.contacts.list") }) - it("puts the new key on a delete's default and shows the old key in --dry-run", () => { + it("puts the new key on a delete's default and in --dry-run, and the old key nowhere", () => { const permissions = serviceApiPermissions({ manifest }) expect(permissions.defaults["api.contacts.delete"]).toBe("ask") expect(permissions.defaults["api.contacts-delete"]).toBeUndefined() - expect(permissions.extra).toContain("api.contacts-list") - expect(permissions.alsoChecks(["api", "contacts", "delete"])).toEqual([ - "records.delete", - { key: "api.contacts-delete", when: "while a profile still names this old key" }, - ]) + expect(permissions.extra).not.toContain("api.contacts-list") + expect(permissions.alsoChecks(["api", "contacts", "delete"])).toEqual(["records.delete"]) expect(permissions.alsoChecks(["api", "status"])).toEqual([]) }) diff --git a/src/cli/service-api.ts b/src/cli/service-api.ts index 7ec9e5cb1..8d1aeb74d 100644 --- a/src/cli/service-api.ts +++ b/src/cli/service-api.ts @@ -29,7 +29,7 @@ import { NO_EFFECTS } from "./effects.js" import { itemOf, listOf, renderAnswer } from "./envelope.js" import { queryTerms, termField, withQuery } from "./list-query.js" import { terminalAsker } from "./messenger/ask.js" -import type { ConditionalKey } from "./permission-keys.js" +import { type ConditionalKey, markRenamedPermissionKeys } from "./permission-keys.js" import { manifestBaseUrl, nextPage, @@ -119,9 +119,8 @@ const keyOf = (operation: ManifestOperation): PermissionKey => ["api", ...apiPat const pathOf = (operation: ManifestOperation): string => apiPathOf(operation).join(" ") /** - * The key a grouped operation had while `api` was flat, `api.contacts-list`. A profile that still names it keeps its - * hold on that one command: checked beside the new key, it only ever tightens. A group never takes an old command's - * name (the generator refuses it), so the old key never reaches past its command. + * The key a grouped operation had while `api` was flat, `api.contacts-list`. It checks nothing now: a config that still + * names it is refused as an unknown key, and the refusal names the new key (WC-CMD-8). */ const formerKeyOf = (operation: ManifestOperation): PermissionKey | undefined => { const former = `api.${operation.command}` @@ -208,28 +207,18 @@ export const serviceApiPermissions = ( extra: readonly PermissionKey[] } => { const checks = new Map() - const former: PermissionKey[] = [] for (const operation of input.manifest.operations) { - const old = formerKeyOf(operation) - if (old) former.push(old) checks.set(pathOf(operation), [ ...permissionsOf(operation).map((permission) => { const when = whenOf(permission) return when === undefined ? permission.key : { key: permission.key, when } }), ...(input.bodyPermissions?.[operation.command] ?? []).map(({ key, when }) => ({ key, when })), - ...(old ? [{ key: old, when: "while a profile still names this old key" }] : []), ]) } - const keys = [ - ...new Set( - [...checks.values()] - .flat() - .flatMap((one) => (typeof one === "string" ? [one] : former.includes(one.key) ? [] : [one.key])), - ), - ] + const keys = [...new Set([...checks.values()].flat().map((one) => (typeof one === "string" ? one : one.key)))] return { - extra: [...keys, ...former], + extra: keys, alsoChecks: (path) => (path[0] === "api" ? (checks.get(path.slice(1).join(" ")) ?? []) : []), defaults: { ...Object.fromEntries(keys.map((key) => [key, "ask" as const])), @@ -404,26 +393,12 @@ const serviceApiCore = (options: ServiceApiOptions) => { } } - /** The old flat key, when the profile names it: on a read only its refusal or its question applies. */ - const formerKeys = (command: Command, operation: ManifestOperation): PermissionKey[] => { - const former = formerKeyOf(operation) - if (!former) return [] - const { settings, renderer } = baseContext(command, configuration.resolveSettings) - const level = settings.permissions[former] - if (level === undefined) return [] - renderer.warn( - `permissions name ${former}, the old key of api ${pathOf(operation)}: rename it to ${keyOf(operation)}`, - ) - return operation.effect === "read" && level !== "deny" && level !== "ask" ? [] : [former] - } - - return { operations, left, baseUrlOf, defaults, exchange, formerKeys, operationOf, readsFreely, signed, write } + return { operations, left, baseUrlOf, defaults, exchange, operationOf, readsFreely, signed, write } } export const serviceApiCommand = (options: ServiceApiOptions): Command => { - const { app, configuration } = options - const { operations, baseUrlOf, exchange, formerKeys, operationOf, readsFreely, signed, write } = - serviceApiCore(options) + const { app, configuration, manifest } = options + const { operations, baseUrlOf, exchange, operationOf, readsFreely, signed, write } = serviceApiCore(options) const send = async (command: Command, operation: ManifestOperation, request: HttpApiRequest) => (await exchange(command, operation, request)).answer let schemas: Readonly> | undefined @@ -510,7 +485,7 @@ export const serviceApiCommand = (options: ServiceApiOptions): Command => { command.hook("preAction", load) }, execute: async (command, operation, input) => { - const extra = [...serviceApiKeys(options, operation, input), ...formerKeys(command, operation)] + const extra = serviceApiKeys(options, operation, input) const read = readsFreely(command, operation, extra) if (operation.pagination && command.opts<{ all?: unknown }>().all === true) { if (!read) @@ -570,6 +545,15 @@ export const serviceApiCommand = (options: ServiceApiOptions): Command => { ) group.addCommand(list).addCommand(show) for (const child of [...generated.commands]) group.addCommand(child) + markRenamedPermissionKeys( + group, + new Map( + manifest.operations.flatMap((operation) => { + const former = formerKeyOf(operation) + return former ? [[former, keyOf(operation)] as const] : [] + }), + ), + ) return group } @@ -607,7 +591,7 @@ const writerBody = ( * can be asked. A read that no key guards goes through `serviceApiCall`. */ export const serviceApiWriter = (options: ServiceApiOptions): ServiceApiWrite => { - const { baseUrlOf, formerKeys, operationOf, signed, write } = serviceApiCore(options) + const { baseUrlOf, operationOf, signed, write } = serviceApiCore(options) return async (command, name, input, { confirmed } = {}) => { const operation = operationOf(name) // The api group offers only declared parameters; code must not reach further, as WordPress's `_method` turns a @@ -649,6 +633,6 @@ export const serviceApiWriter = (options: ServiceApiOptions): ServiceApiWrite => operation, httpApiRequest(operation, writerBody(operation, input, schemas), baseUrlOf(command)), ) - return write(command, operation, [...extra, ...formerKeys(command, operation)], request, confirmed) + return write(command, operation, extra, request, confirmed) } }