Repository navigation
Retry secrets prompts if empty string is provided - #11310
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a retry mechanism for secret prompts when an empty string is provided, ensuring secrets cannot have empty values, and adds a corresponding unit test. The review feedback suggests refactoring the manual retry loop to use the built-in validate option of the password prompt utility to reduce nesting in accordance with the style guide, and updating the unit test to assert the validation logic directly.
| let secretValue = ""; | ||
| while (true) { | ||
| secretValue = await password({ | ||
| message: promptMessage, | ||
| }); | ||
| if (secretValue !== "") { | ||
| break; | ||
| } | ||
| logger.error("Secrets cannot have an empty value. Retrying..."); | ||
| } |
There was a problem hiding this comment.
Instead of implementing a manual while (true) loop with custom error logging, we can leverage the built-in validate option of the password prompt utility. This is more idiomatic, cleaner, and reduces unnecessary nesting in accordance with the Repository Style Guide (line 37: 'Reduce nesting as much as possible').
const secretValue = await password({
message: promptMessage,
validate: (val) => val !== "" || "Secrets cannot have an empty value.",
});References
- Reduce nesting as much as possible: Code should avoid unnecessarily deep nesting or long periods of nesting. (link)
There was a problem hiding this comment.
I think this is a hallucination? Looking at inquirer, I think passing a validate function in opts causes a throw on validation failure, not a retry. We can catch and loop if we did that, but it wouldn't really reduce nesting or make the code more readable.
There was a problem hiding this comment.
It's not a hallucination—@inquirer/password does not throw when validate returns a string or false.
In @inquirer/password's keypress handler:
if (isValid === true) {
setValue(answer);
setStatus('done');
done(answer);
} else {
rl.write(value);
setError(isValid || 'You must provide a valid value');
setStatus('idle');
}When validate returns a string error message (or false), it sets errorMsg, keeps the prompt status as idle, and prompts the user in-place on the same line without rejecting or reprinting prompt headers.
(The comment in src/prompt.ts:294 about throwing only applies to guard(opts) in --non-interactive mode when opts.default is undefined; in interactive mode guard is a no-op and delegates to @inquirer/password).
Existing code in the CLI already uses this pattern, e.g. src/commands/appcheck-debugtokens-create.ts:62-65:
token = await password({
message: "Enter the debug token generated by the SDK:",
validate: (val) => (val.trim().length > 0 ? true : "Debug token cannot be empty."),
});Using validate here avoids an outer while (true) retry loop, eliminates mutable let secretValue, and avoids scrollback thrashing from re-printing the prompt line:
| let secretValue = ""; | |
| while (true) { | |
| secretValue = await password({ | |
| message: promptMessage, | |
| }); | |
| if (secretValue !== "") { | |
| break; | |
| } | |
| logger.error("Secrets cannot have an empty value. Retrying..."); | |
| } | |
| const promptMessage = `Enter ${secretParam.format === "json" ? "a JSON value" : "a value"} for ${label}:`; | |
| const secretValue = await password({ | |
| message: promptMessage, | |
| validate: (val: string) => (val !== "" ? true : "Secrets cannot have an empty value."), | |
| }); |
ajperel
left a comment
There was a problem hiding this comment.
Also need to add a CHANGELOG entry for this one.
| @@ -1,3 +1,4 @@ | |||
| - Ensured the Firebase Hosting API is enabled before deploying and running other Hosting commands. | |||
| - Fixed an issue where empty inputs were accepted for Secret param values in Firebase Functions (#11310) | |||
There was a problem hiding this comment.
Nit. I think we use # for when a PR is fixing a GitHub issue but not self-referentially to refer to the PR that makes the change FWIW.
| } | ||
| }); | ||
|
|
||
| it("retries via validate when blank input is provided", async () => { |
There was a problem hiding this comment.
I did some playing with AI to see if we could improve this test. It seemed good but complicated and took a bit to understand. It's recommendation which looks nice was:
it("validates that secret prompt input is not empty", async () => {
const passwordStub = sinon.stub(prompt, "password").resolves("secret-val");
const getSecretMetadataStub = sinon.stub(secretManager, "getSecretMetadata").resolves({
secret: undefined,
});
const createSecretStub = sinon.stub(secretManager, "createSecret").resolves();
const addVersionStub = sinon.stub(secretManager, "addVersion").resolves();
const paramsToResolve: params.Param[] = [
{
name: "API_KEY",
label: "API Key",
description: "Key used to authenticate with 3rd party API.",
type: "secret",
resourceId: "API_KEY",
},
];
try {
await params.resolveParams({
params: paramsToResolve,
firebaseConfig: fakeConfig,
userEnvs: {},
codebase: "my-codebase",
});
// 1. Verify password prompt was called once
expect(passwordStub).to.have.been.calledOnce;
// 2. Verify the validate contract directly (both empty and valid cases)
const opts = passwordStub.firstCall.args[0] as prompt.PasswordOptions;
expect(opts.validate).to.be.a("function");
expect(opts.validate!("")).to.equal("Secrets cannot have an empty value.");
expect(opts.validate!("secret-val")).to.be.true;
// 3. Verify downstream Secret Manager propagation
expect(createSecretStub).to.have.been.calledOnceWith("foo", "API_KEY", sinon.match.any);
expect(addVersionStub).to.have.been.calledOnceWith("foo", "API_KEY", "secret-val");
} finally {
passwordStub.restore();
getSecretMetadataStub.restore();
createSecretStub.restore();
addVersionStub.restore();
}
});
Why the current one is overengineered: ensureSecret() is not responsible for running Inquirer's interactive keypress loop—@inquirer/password already tests that
Updated version:
- Asserts addVersionStub: Guarantees the resolved password actually reaches Secret Manager with the right project ID, secret name, and payload.
- Eliminates the callsFake harness: Removes the simulated loop, mutable tracking arrays, and artificial throw.
- High-Signal Failures: If the validation error message changes or breaks, Mocha reports the exact string mismatch instead of an array comparison failure.
Cloud Secret Manager rejects secrets with an empty value anyway, and having a retry loop is marginally more comfortable in testing cases where you're mashing enter and push it one too many times.