From b2ba24ee738e518818fd5fe40091c7084bbc1822 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 30 Nov 2026 08:47:54 +0100 Subject: [PATCH] fix(cli): close Hub run gaps for unchecked inputs, expired logins, and retries --- .../cli/src/commands/hub/run/index.test.ts | 103 ++++++++++++++++++ packages/cli/src/commands/hub/run/index.ts | 50 ++++----- .../src/commands/hub/run/internal/failures.ts | 32 ++++-- .../src/commands/hub/run/internal/inputs.ts | 19 ++-- .../hub/run/internal/manual-trigger.ts | 50 ++++----- .../src/commands/hub/run/internal/prompts.ts | 4 +- public-docs/cli.md | 4 +- public-docs/cli.zh-CN.md | 4 +- 8 files changed, 189 insertions(+), 77 deletions(-) diff --git a/packages/cli/src/commands/hub/run/index.test.ts b/packages/cli/src/commands/hub/run/index.test.ts index 5642014f0b..e5f3f7cdb7 100644 --- a/packages/cli/src/commands/hub/run/index.test.ts +++ b/packages/cli/src/commands/hub/run/index.test.ts @@ -476,6 +476,109 @@ legacy_multistep: ); }); + it.each([ + ["a legacy project trigger", "legacy-deploy", [deployTrigger]], + [ + "a trigger document it cannot read", + "odd", + [deployTrigger, trigger("odd", "name: odd\non: nonsense\n")], + ], + ])("says the input names were not checked for %s", async (_case, name, triggers) => { + const hub = await startHub({ triggers }); + const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } }); + + await cli.run(name, undefined, { input: ["environment=staging"] }); + + assert.equal( + cli.progress.at(-1), + `Input names were not checked: no readable organization trigger "${name}".`, + ); + }); + + it("is not blocked by another trigger's unreadable document, and reads YAML merge keys", async () => { + const hub = await startHub({ + triggers: [ + trigger("odd", "name: odd\non: nonsense\n"), + trigger( + "merged", + "name: merged\non:\n manual.run: {}\ninputs:\n a: &text {type: string}\n b: {<<: *text}\n", + ), + ], + }); + const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } }); + + await cli.run("merged", undefined, { input: ["b=two"] }); + + assert.deepEqual( + hub.dispatches().map(({ input }) => input), + ["b=two"], + ); + assert.deepEqual(cli.progress, [`Running merged on ${hub.origin}`]); + }); + + it("adds nothing to the error output when an unchecked run fails", async () => { + const hub = await startHub({ + list: problem(403, "insufficient_scope", "Insufficient scope"), + run: problem(503, "infrastructure_unavailable", "Service unavailable"), + }); + const cli = harness({ env: { PASEO_HUB_URL: hub.origin, PASEO_HUB_API_KEY: "ci-secret" } }); + + await assert.rejects(cli.run("deploy", undefined, { input: ["a=b"], json: true })); + + assert.deepEqual(cli.progress, []); + }); + + it("points at hub login when the credential expired before the triggers were listed", async () => { + const hub = await startHub({ list: problem(401, "unauthorized", "Authentication required") }); + const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } }); + + await assert.rejects(cli.run("deploy", undefined, { input: ["a=b"] }), (error) => { + assert.ok(error instanceof HubCommandError); + assert.match(error.details ?? "", /paseo hub login http/u); + return true; + }); + assert.deepEqual(hub.dispatches(), []); + }); + + it.each([ + problem(403, "actor_forbidden", "Actor forbidden"), + problem(400, "invalid_input", "Invalid trigger input"), + ])("asks for a new delivery key to correct a rejected request: %#", async (response) => { + const hub = await startHub({ run: response }); + const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } }); + const details = async (options: HubRunOptions) => { + let caught: unknown; + await cli.run("deploy", undefined, options).catch((error: unknown) => { + caught = error; + }); + assert.ok(caught instanceof HubCommandError); + return caught.details ?? ""; + }; + + assert.match(await details({ deliveryKey: "build-42" }), /new --delivery-key/u); + assert.doesNotMatch(await details({}), /--delivery-key/u); + }); + + it("does not send a picked choice that Hub would cut at the space", async () => { + const hub = await startHub({ + triggers: [ + trigger( + "region", + "name: region\non:\n manual.run: {}\ninputs:\n region: {type: string, required: true, choices: [us east]}\n", + ), + ], + }); + const cli = harness({ + login: { origin: hub.origin, credential: "stored-secret" }, + interactive: true, + answers: ["us east"], + }); + + await rejectsWith(cli.run("region", undefined), "HUB_RUN_INPUT", /cannot contain spaces/u); + + assert.deepEqual(hub.dispatches(), []); + }); + it("starts nothing when the question is cancelled", async () => { const hub = await startHub({ triggers: [deployTrigger] }); const cli = harness({ diff --git a/packages/cli/src/commands/hub/run/index.ts b/packages/cli/src/commands/hub/run/index.ts index ee8047f0c8..f4460c254d 100644 --- a/packages/cli/src/commands/hub/run/index.ts +++ b/packages/cli/src/commands/hub/run/index.ts @@ -16,7 +16,7 @@ import { HubCommandError } from "../error.js"; import { addHubResolutionHelp } from "../help.js"; import type { HubHttpClient } from "../hub-client/index.js"; import { reportHubProgress, type HubReporter } from "../reporter.js"; -import { availableTriggers, explainRunFailure } from "./internal/failures.js"; +import { availableTriggers, explainRunFailure, explainSignIn } from "./internal/failures.js"; import { assertDeclared, encodeInvocation, @@ -91,10 +91,10 @@ export async function runHubRun( const triggers = organizationTriggers(dependencies.hub, origin, credential); const name = triggerArgument ?? (await pickTrigger(triggers, origin, dependencies.prompts)); - const inputs = + const { inputs, unchecked } = flags.length > 0 || canAsk - ? await completeInputs({ name, flags, prompt, canAsk, options, dependencies, triggers }) - : flags; + ? await completeInputs({ name, flags, prompt, canAsk, dependencies, triggers }) + : { inputs: flags, unchecked: undefined }; reportHubProgress(dependencies.reporter, options, `Running ${name} on ${origin}`); const deliveryKey = options.deliveryKey ?? randomUUID(); @@ -107,6 +107,10 @@ export async function runHubRun( deliveryKey, input: encodeInvocation(inputs, prompt), }); + // Said once Hub has accepted: a failed `--json` run keeps stderr as the error alone. + if (unchecked !== undefined) { + dependencies.reporter.progress(`Input names were not checked: ${unchecked}.`); + } return { type: "single", data: { ...run, origin }, schema }; } catch (error) { throw await explainRunFailure(error, { @@ -114,6 +118,7 @@ export async function runHubRun( origin, project: options.project, deliveryKey, + keyFromCaller: options.deliveryKey !== undefined, triggers, }); } @@ -167,10 +172,11 @@ function organizationTriggers( let listed: Promise | undefined; const list = async () => { try { - return (await hub.listTriggers(origin, credential)).map(readManualTrigger); + const documents = await hub.listTriggers(origin, credential); + return documents.flatMap((document) => readManualTrigger(document) ?? []); } catch (error) { if (error instanceof HubCommandError && error.hubProblem?.status === 403) return null; - throw error; + throw explainSignIn(error, origin); } }; return () => (listed ??= list()); @@ -202,36 +208,26 @@ async function completeInputs(input: { flags: InputValue[]; prompt: string; canAsk: boolean; - options: HubRunOptions; dependencies: HubRunDependencies; triggers: OrganizationTriggers; -}): Promise { - const { name, flags, prompt, canAsk, options, dependencies } = input; +}): Promise<{ inputs: InputValue[]; unchecked?: string }> { + const { name, flags, prompt, canAsk, dependencies } = input; const listed = await input.triggers(); const trigger = listed?.find((candidate) => candidate.name === name); if (trigger === undefined) { - const reason = uncheckedReason(listed, options.project); - if (flags.length > 0 && reason !== undefined) { - dependencies.reporter.progress(`Input names were not checked: ${reason}.`); - } - return flags; + if (flags.length === 0) return { inputs: flags }; + const unchecked = + listed === null + ? "this credential cannot list triggers (configuration:validate)" + : `no readable organization trigger "${name}"`; + return { inputs: flags, unchecked }; } // A trigger that cannot run gets Hub's answer, not questions about its inputs. - if (!isRunnable(trigger)) return flags; + if (!isRunnable(trigger)) return { inputs: flags }; assertDeclared(trigger, flags); - if (!canAsk) return flags; + if (!canAsk) return { inputs: flags }; const missing = missingInputs(trigger, flags, prompt); - return [...flags, ...(await askInputs(dependencies.prompts, missing))]; -} - -/** Why `-i` names went unchecked. Nothing to say when Hub is about to reject the trigger. */ -function uncheckedReason( - listed: readonly ManualTrigger[] | null, - project: string | undefined, -): string | undefined { - if (listed === null) return "this credential cannot list triggers (configuration:validate)"; - if (project !== undefined) return "legacy project triggers cannot be listed"; - return undefined; + return { inputs: [...flags, ...(await askInputs(dependencies.prompts, missing))] }; } async function readPrompt( diff --git a/packages/cli/src/commands/hub/run/internal/failures.ts b/packages/cli/src/commands/hub/run/internal/failures.ts index c177696f7d..16cfa3d92a 100644 --- a/packages/cli/src/commands/hub/run/internal/failures.ts +++ b/packages/cli/src/commands/hub/run/internal/failures.ts @@ -7,6 +7,7 @@ interface RunAttempt { origin: string; project: string | undefined; deliveryKey: string; + keyFromCaller: boolean; /** The organization's triggers, or null when they cannot be listed. */ triggers(): Promise; } @@ -22,19 +23,14 @@ export async function explainRunFailure(error: unknown, attempt: RunAttempt): Pr ) { return explainMissingTrigger(error, attempt); } - if (problem?.code === "invalid_input") return explainInvalidInput(error, attempt); + if (problem?.code === "invalid_input") { + return forCorrection(await explainInvalidInput(error, attempt), attempt); + } if (problem?.code === "actor_forbidden") { - return advise( - error, - "Pass --actor with a name listed in the trigger's filters.from_users.", - ); - } - if (problem?.status === 401) { - return advise( - error, - `Run \`paseo hub login ${attempt.origin}\`, or check --api-key and PASEO_HUB_API_KEY.`, - ); + const advice = "Pass --actor with a name listed in the trigger's filters.from_users."; + return forCorrection(advise(error, advice), attempt); } + if (problem?.status === 401) return explainSignIn(error, attempt.origin); // Hub may hold the request already: only the same delivery key makes a retry safe. if ( problem === undefined || @@ -50,6 +46,20 @@ export async function explainRunFailure(error: unknown, attempt: RunAttempt): Pr return error; } +export function explainSignIn(error: unknown, origin: string): unknown { + if (!(error instanceof HubCommandError) || error.hubProblem?.status !== 401) return error; + return advise( + error, + `Run \`paseo hub login ${origin}\`, or check --api-key and PASEO_HUB_API_KEY.`, + ); +} + +// Hub stores a request before rejecting it, and replays the stored one for the same key. +function forCorrection(error: HubCommandError, attempt: RunAttempt): HubCommandError { + if (!attempt.keyFromCaller) return error; + return advise(error, "Send the corrected request with a new --delivery-key."); +} + async function explainInvalidInput( error: HubCommandError, attempt: RunAttempt, diff --git a/packages/cli/src/commands/hub/run/internal/inputs.ts b/packages/cli/src/commands/hub/run/internal/inputs.ts index bc24dd985a..fdcfa989be 100644 --- a/packages/cli/src/commands/hub/run/internal/inputs.ts +++ b/packages/cli/src/commands/hub/run/internal/inputs.ts @@ -3,7 +3,8 @@ import type { DeclaredInput, ManualTrigger } from "./manual-trigger.js"; // Hub's manual dispatch takes one string: leading `name=value` tokens, then the prompt. A token // it does not recognise ends the inputs and becomes prompt text, and the run starts with defaults. -// These checks stop everything Hub would misread without saying so; Hub validates the rest. +// These checks stop an `-i` value Hub would misread without saying so; Hub validates the rest. +// Pairs at the start of the prompt are Hub's own syntax and pass through. const INPUT_NAME = /^[a-z][a-z0-9_-]*$/u; const LEADING_TOKEN = /^([a-z][a-z0-9_-]*)=[^\s]*(?:\s+|$)/u; @@ -23,15 +24,19 @@ export function parseInputFlags(flags: readonly string[]): InputValue[] { `Input names are lowercase letters, digits, "-" and "_", starting with a letter. Got "${name}".`, ); } - if (/\s/u.test(value)) { - throw invalidInput( - `Input "${name}" cannot contain spaces. Hub separates inputs by spaces; put free text in the prompt.`, - ); - } - return { name, value }; + return sendableInput(name, value); }); } +export function sendableInput(name: string, value: string): InputValue { + if (/\s/u.test(value)) { + throw invalidInput( + `Input "${name}" cannot contain spaces. Hub separates inputs by spaces; put free text in the prompt.`, + ); + } + return { name, value }; +} + export function encodeInvocation(inputs: readonly InputValue[], prompt: string): string { return [...inputs.map(({ name, value }) => `${name}=${value}`), prompt] .filter((part) => part !== "") diff --git a/packages/cli/src/commands/hub/run/internal/manual-trigger.ts b/packages/cli/src/commands/hub/run/internal/manual-trigger.ts index 625d98fc73..d309bfb67d 100644 --- a/packages/cli/src/commands/hub/run/internal/manual-trigger.ts +++ b/packages/cli/src/commands/hub/run/internal/manual-trigger.ts @@ -1,6 +1,5 @@ import YAML from "yaml"; import { z } from "zod"; -import { HubCommandError } from "../../error.js"; import type { HubTrigger } from "../../hub-client/index.js"; const inputsSchema = z @@ -37,36 +36,35 @@ export interface ManualTrigger { inputs: DeclaredInput[]; } -export function readManualTrigger(trigger: HubTrigger): ManualTrigger { - const { manual, inputs } = readDocument(trigger); - return { - name: trigger.name, - enabled: trigger.enabled, - manual, - inputs: Object.entries(inputs ?? {}).map(([name, input]) => Object.assign(input, { name })), - }; +/** `null`: a document this CLI cannot read. Hub still decides whether it runs. */ +export function readManualTrigger(trigger: HubTrigger): ManualTrigger | null { + try { + // Hub's parser follows `<<` merge keys. + const document: unknown = YAML.parse(trigger.yaml, { merge: true }); + const { manual, inputs } = readDocument(trigger.format, document); + return { + name: trigger.name, + enabled: trigger.enabled, + manual, + inputs: Object.entries(inputs ?? {}).map(([name, input]) => Object.assign(input, { name })), + }; + } catch { + return null; + } } export function isRunnable(trigger: ManualTrigger): boolean { return trigger.enabled && trigger.manual; } -function readDocument(trigger: HubTrigger): { - manual: boolean; - inputs: z.infer; -} { - try { - const document: unknown = YAML.parse(trigger.yaml); - if (trigger.format === "legacy_multistep") { - const { on, inputs } = legacyMultistepSchema.parse(document).legacy_multistep.trigger; - return { manual: on === "manual.run", inputs }; - } - const { on, inputs } = singleRunSchema.parse(document); - return { manual: Object.hasOwn(on, "manual.run"), inputs }; - } catch { - throw new HubCommandError( - "HUB_INVALID_RESPONSE", - `Hub returned a trigger document this CLI cannot read: ${trigger.name}.`, - ); +function readDocument( + format: HubTrigger["format"], + document: unknown, +): { manual: boolean; inputs: z.infer } { + if (format === "legacy_multistep") { + const { on, inputs } = legacyMultistepSchema.parse(document).legacy_multistep.trigger; + return { manual: on === "manual.run", inputs }; } + const { on, inputs } = singleRunSchema.parse(document); + return { manual: Object.hasOwn(on, "manual.run"), inputs }; } diff --git a/packages/cli/src/commands/hub/run/internal/prompts.ts b/packages/cli/src/commands/hub/run/internal/prompts.ts index 98baf13430..c537f5ed26 100644 --- a/packages/cli/src/commands/hub/run/internal/prompts.ts +++ b/packages/cli/src/commands/hub/run/internal/prompts.ts @@ -1,6 +1,6 @@ import { isCancel, select, text } from "@clack/prompts"; import { HubCommandError } from "../../error.js"; -import type { InputValue } from "./inputs.js"; +import { sendableInput, type InputValue } from "./inputs.js"; import type { DeclaredInput } from "./manual-trigger.js"; /** Questions asked in a terminal. `null` means the person cancelled. */ @@ -45,7 +45,7 @@ export async function askInputs( validate: (value) => invalidAnswer(input, value), }) : await prompts.select({ message: input.name, options }); - values.push({ name: input.name, value: answered(answer) }); + values.push(sendableInput(input.name, answered(answer))); } return values; } diff --git a/public-docs/cli.md b/public-docs/cli.md index 6772d212a6..e600ce0e56 100644 --- a/public-docs/cli.md +++ b/public-docs/cli.md @@ -475,9 +475,9 @@ paseo hub run deploy -i environment=staging "ship the hotfix" RUN_ID=$(paseo hub run triage --prompt-file report.md --quiet) ``` -Set declared inputs with `-i name=value`, once per input. A value cannot contain spaces; put free text in the prompt or in `--prompt-file`. Hub receives inputs and prompt as one string, so `${{ paseo.prompt }}` starts with the `name=value` pairs. In a terminal, omit the trigger to pick one, and answer for any required input you left out. Non-TTY, `--json`, and `--quiet` runs never prompt. +Set declared inputs with `-i name=value`, once per input. A value cannot contain spaces; put free text in the prompt or in `--prompt-file`. Hub receives inputs and prompt as one string, so `${{ paseo.prompt }}` starts with the `name=value` pairs, and pairs at the start of the prompt or prompt file set inputs too. If that text is untrusted, set every declared input with `-i`; Hub rejects a second value. In a terminal, omit the trigger to pick one, and answer for any required input you left out. Non-TTY, `--json`, and `--quiet` runs never prompt. -The command exits `0` when Hub accepts the run. It does not wait for the run to finish; follow it under **Activity** in Hub. In CI, set `PASEO_HUB_URL` and `PASEO_HUB_API_KEY`. The key needs `runs:dispatch`; add `configuration:validate` so `-i` names are checked before the run starts. The sender name is `paseo-cli`; pass `--actor ` when the trigger's `filters.from_users` restricts senders. If you don't know whether Hub received a request, retry with the `--delivery-key` from the error so the run starts once. +The command exits `0` when Hub accepts the run. It does not wait for the run to finish; follow it under **Activity** in Hub. In CI, set `PASEO_HUB_URL` and `PASEO_HUB_API_KEY`. The key needs `runs:dispatch`; add `configuration:validate` so `-i` names are checked before the run starts. The sender name is `paseo-cli`; pass `--actor ` when the trigger's `filters.from_users` restricts senders. If you don't know whether Hub received a request, retry with the `--delivery-key` from the error so the run starts once. Hub keeps the first request sent with a key, so use a new key when you change anything. Interactive `paseo hub logout` checks for a daemon connected to the same Hub and asks whether to disconnect it before deleting the login. JSON and non-interactive logouts never prompt or disconnect unless you pass `--disconnect-daemon` (with optional `--force`). If disconnection fails, the login stays intact. diff --git a/public-docs/cli.zh-CN.md b/public-docs/cli.zh-CN.md index 82d1745653..7d37f0200a 100644 --- a/public-docs/cli.zh-CN.md +++ b/public-docs/cli.zh-CN.md @@ -454,9 +454,9 @@ paseo hub run deploy -i environment=staging "ship the hotfix" RUN_ID=$(paseo hub run triage --prompt-file report.md --quiet) ``` -用 `-i name=value` 设置声明的输入,每个输入写一次。值不能包含空格;自由文本请放在提示词或 `--prompt-file` 中。Hub 以单个字符串接收输入和提示词,因此 `${{ paseo.prompt }}` 以这些 `name=value` 对开头。在终端中省略触发器名称即可从列表中选择,缺少的必填输入会逐一询问。非 TTY、`--json` 和 `--quiet` 运行不会提示。 +用 `-i name=value` 设置声明的输入,每个输入写一次。值不能包含空格;自由文本请放在提示词或 `--prompt-file` 中。Hub 以单个字符串接收输入和提示词,因此 `${{ paseo.prompt }}` 以这些 `name=value` 对开头;提示词或提示词文件开头的 `name=value` 对同样会设置输入。如果这段文本不可信,请用 `-i` 设置每个声明的输入;Hub 会拒绝同一输入的第二个值。在终端中省略触发器名称即可从列表中选择,缺少的必填输入会逐一询问。非 TTY、`--json` 和 `--quiet` 运行不会提示。 -Hub 接受运行后命令即以 `0` 退出,不会等待运行结束;请在 Hub 的 **Activity** 中查看进展。在 CI 中设置 `PASEO_HUB_URL` 和 `PASEO_HUB_API_KEY`。密钥需要 `runs:dispatch`;再加上 `configuration:validate`,即可在运行开始前检查 `-i` 名称。发送者名称为 `paseo-cli`;当触发器的 `filters.from_users` 限制发送者时,请传入 `--actor `。如果不确定 Hub 是否收到了请求,请用错误信息中的 `--delivery-key` 重试,这样运行只会启动一次。 +Hub 接受运行后命令即以 `0` 退出,不会等待运行结束;请在 Hub 的 **Activity** 中查看进展。在 CI 中设置 `PASEO_HUB_URL` 和 `PASEO_HUB_API_KEY`。密钥需要 `runs:dispatch`;再加上 `configuration:validate`,即可在运行开始前检查 `-i` 名称。发送者名称为 `paseo-cli`;当触发器的 `filters.from_users` 限制发送者时,请传入 `--actor `。如果不确定 Hub 是否收到了请求,请用错误信息中的 `--delivery-key` 重试,这样运行只会启动一次。Hub 保留使用某个键发送的第一个请求,因此修改任何内容时请换用新的键。 交互式 `paseo hub logout` 会检查连接到同一 Hub 的 daemon,并在删除登录前询问是否断开。JSON 和非交互式退出不会提示或断开,除非传入 `--disconnect-daemon`(可配合 `--force`)。如果断开失败,登录凭据会保留。