fix(secrets): CLI set/rotate read the value from stdin or a masked prompt (scadaproj#35)
`secret set`/`rotate` took the plaintext as a positional argument (shell history, process list), and Program handed argv to Host.CreateApplicationBuilder, whose command-line config provider crashed on a value like "-p=Hunter2Secret" with the value in the unhandled FormatException on stderr. - SetCommandLine: `set|rotate <name> [-|--value-stdin]`; no value reads piped stdin or prompts twice (masked) at a TTY; one trailing newline dropped; empty refused. The positional <value> still works and warns on stderr. - host built from HostApplicationBuilderSettings without argv; startup failures print `secret: startup failed: <msg>` and exit 1 - unexpected trailing arguments reported by position, not echoed - tests: SetCommandLineTests incl. two child-process runs of the built CLI; the -p=Hunter2Secret probe fails (leaks) on the old Program.cs - docs: README, clustered-secrets runbook, CHANGELOG - code-reviews: Secrets-017 Resolved; README regenerated Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
@@ -18,18 +18,36 @@ using ZB.MOM.WW.Secrets.MasterKey;
|
||||
if (InteractiveEntry.ShouldEnterInteractive(args, Console.IsInputRedirected, Console.IsOutputRedirected))
|
||||
return await InteractiveEntry.CreateShell(AnsiConsole.Console).RunAsync(CancellationToken.None);
|
||||
|
||||
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
|
||||
builder.Configuration
|
||||
.AddJsonFile("appsettings.json", optional: true)
|
||||
.AddEnvironmentVariables();
|
||||
builder.Services.AddZbSecrets(builder.Configuration, "Secrets");
|
||||
// argv is deliberately NOT handed to the host builder (scadaproj#35). Host.CreateApplicationBuilder(args)
|
||||
// feeds it to the command-line configuration provider, which turned a secret value containing '='
|
||||
// into a configuration key and crashed on one starting with '-' — with the whole argument, i.e. the
|
||||
// secret, in the unhandled FormatException's message. Configuration comes from appsettings.json and
|
||||
// the environment only.
|
||||
IHost host;
|
||||
try
|
||||
{
|
||||
HostApplicationBuilder builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings());
|
||||
builder.Configuration
|
||||
.AddJsonFile("appsettings.json", optional: true)
|
||||
.AddEnvironmentVariables();
|
||||
builder.Services.AddZbSecrets(builder.Configuration, "Secrets");
|
||||
|
||||
using IHost host = builder.Build();
|
||||
host = builder.Build();
|
||||
|
||||
// Ensure the schema exists before any store operation. Resolved through the ISecretsStoreMigrator
|
||||
// seam so the CLI provisions whichever store the app configured (local SQLite or shared SQL Server).
|
||||
await host.Services.GetRequiredService<ISecretsStoreMigrator>()
|
||||
.MigrateAsync(CancellationToken.None);
|
||||
// Ensure the schema exists before any store operation. Resolved through the ISecretsStoreMigrator
|
||||
// seam so the CLI provisions whichever store the app configured (local SQLite or shared SQL Server).
|
||||
await host.Services.GetRequiredService<ISecretsStoreMigrator>()
|
||||
.MigrateAsync(CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// No argv reaches configuration, so this message cannot carry a secret value; print it without
|
||||
// the stack trace an unhandled crash would dump into CI logs and deploy transcripts.
|
||||
Console.Error.WriteLine($"secret: startup failed: {ex.Message}");
|
||||
return 1;
|
||||
}
|
||||
|
||||
using IHost ownedHost = host;
|
||||
|
||||
var commands = new SecretCommands(
|
||||
host.Services.GetRequiredService<ISecretStore>(),
|
||||
@@ -50,19 +68,21 @@ try
|
||||
switch (args[0])
|
||||
{
|
||||
case "set":
|
||||
{
|
||||
if (args.Length < 3)
|
||||
return Usage("set requires <name> and <value>.");
|
||||
(SecretContentType contentType, string? description) = ParseSetOptions(args, startIndex: 3);
|
||||
return await commands.SetAsync(args[1], args[2], contentType, description, actor, ct);
|
||||
}
|
||||
|
||||
case "rotate":
|
||||
{
|
||||
if (args.Length < 3)
|
||||
return Usage("rotate requires <name> and <value>.");
|
||||
(SecretContentType contentType, string? description) = ParseSetOptions(args, startIndex: 3);
|
||||
return await commands.RotateAsync(args[1], args[2], contentType, description, actor, ct);
|
||||
// The value comes from stdin or a masked prompt; the positional form still works but
|
||||
// warns (scadaproj#35). See SetCommandLine for the accepted forms.
|
||||
if (args.Length < 2)
|
||||
return Usage($"{args[0]} requires <name>.");
|
||||
SetCommandLine line = SetCommandLine.Parse(args);
|
||||
string value = line.ReadValue(
|
||||
Console.In,
|
||||
Console.IsInputRedirected,
|
||||
label => AnsiConsole.Prompt(new TextPrompt<string>(label).Secret().AllowEmpty()),
|
||||
Console.Error);
|
||||
return args[0] == "set"
|
||||
? await commands.SetAsync(line.Name, value, line.ContentType, line.Description, actor, ct)
|
||||
: await commands.RotateAsync(line.Name, value, line.ContentType, line.Description, actor, ct);
|
||||
}
|
||||
|
||||
case "get":
|
||||
@@ -134,48 +154,6 @@ catch (ArgumentException ex)
|
||||
|
||||
// --- helpers ---------------------------------------------------------------
|
||||
|
||||
// Parses the optional flags shared by `set` and `rotate`:
|
||||
// [--content-type text|connection-string|json|binary-base64] [--description "..."]
|
||||
static (SecretContentType contentType, string? description) ParseSetOptions(string[] args, int startIndex)
|
||||
{
|
||||
SecretContentType contentType = SecretContentType.Text;
|
||||
string? description = null;
|
||||
|
||||
for (int i = startIndex; i < args.Length; i++)
|
||||
{
|
||||
switch (args[i])
|
||||
{
|
||||
case "--content-type":
|
||||
if (i + 1 >= args.Length)
|
||||
throw new ArgumentException("--content-type requires a value.");
|
||||
contentType = ParseContentType(args[++i]);
|
||||
break;
|
||||
|
||||
case "--description":
|
||||
if (i + 1 >= args.Length)
|
||||
throw new ArgumentException("--description requires a value.");
|
||||
description = args[++i];
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new ArgumentException($"Unknown option '{args[i]}'.");
|
||||
}
|
||||
}
|
||||
|
||||
return (contentType, description);
|
||||
}
|
||||
|
||||
// Maps the CLI content-type token (kebab-case) to the enum.
|
||||
static SecretContentType ParseContentType(string value) => value switch
|
||||
{
|
||||
"text" => SecretContentType.Text,
|
||||
"connection-string" => SecretContentType.ConnectionString,
|
||||
"json" => SecretContentType.Json,
|
||||
"binary-base64" => SecretContentType.BinaryBase64,
|
||||
_ => throw new ArgumentException(
|
||||
$"Unknown --content-type '{value}'; expected text|connection-string|json|binary-base64."),
|
||||
};
|
||||
|
||||
// Reads the value that must follow an option flag at args[i], advancing i past it.
|
||||
static string RequireValue(string[] args, ref int i)
|
||||
{
|
||||
@@ -206,14 +184,19 @@ int Usage(string? error = null)
|
||||
"""
|
||||
Usage: secret <command> [args]
|
||||
|
||||
set <name> <value> [--content-type text|connection-string|json|binary-base64] [--description "..."]
|
||||
rotate <name> <value> [--content-type ...] [--description "..."]
|
||||
set <name> [-|--value-stdin] [--content-type text|connection-string|json|binary-base64] [--description "..."]
|
||||
rotate <name> [-|--value-stdin] [--content-type ...] [--description "..."]
|
||||
get <name>
|
||||
list [--include-deleted]
|
||||
rm <name>
|
||||
rewrap-all --old-key-env <VAR>|--old-key-file <path> [--old-key-id <id>]
|
||||
[--new-key-env <VAR>|--new-key-file <path>] [--new-key-id <id>]
|
||||
|
||||
set/rotate read the value from stdin when it is piped (or with `-` / --value-stdin), and
|
||||
otherwise prompt for it, masked, twice. One trailing newline on stdin is dropped. The old
|
||||
`set <name> <value>` form still works but prints a warning: a value on the command line is
|
||||
kept in shell history and visible in the process list.
|
||||
|
||||
rewrap-all rotates the master KEK: it re-wraps every stored secret's data key from the old
|
||||
KEK to the new one (bodies are never re-encrypted, no plaintext is exposed). The new KEK
|
||||
defaults to the configured Secrets:MasterKey provider. Supply key material only by env-var
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.Secrets.Cli;
|
||||
|
||||
/// <summary>Where a <c>set</c>/<c>rotate</c> invocation takes the secret value from.</summary>
|
||||
public enum SecretValueSource
|
||||
{
|
||||
/// <summary>
|
||||
/// No value on the command line: read standard input when it is redirected, otherwise prompt
|
||||
/// (masked) at the terminal.
|
||||
/// </summary>
|
||||
Implicit,
|
||||
|
||||
/// <summary>Read standard input, requested explicitly with <c>-</c> or <c>--value-stdin</c>.</summary>
|
||||
Stdin,
|
||||
|
||||
/// <summary>
|
||||
/// The legacy positional <c><value></c>. Still accepted, with a warning: it lands in shell
|
||||
/// history and is visible in the process list for the duration of the run.
|
||||
/// </summary>
|
||||
Argument,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parsing and value acquisition for the headless <c>set</c> and <c>rotate</c> verbs (scadaproj#35).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Accepted forms, for <c>set</c> and <c>rotate</c> alike:
|
||||
/// </para>
|
||||
/// <code>
|
||||
/// secret set <name> [options] # value from piped stdin, else a masked prompt
|
||||
/// secret set <name> - [options] # value from stdin
|
||||
/// secret set <name> --value-stdin [options]
|
||||
/// secret set <name> <value> [options] # DEPRECATED: warns, value is exposed on argv
|
||||
/// </code>
|
||||
/// <para>
|
||||
/// The third argument is a positional value unless it is exactly <c>-</c> or one of the option
|
||||
/// flags, so a value that happens to equal <c>--content-type</c>, <c>--description</c> or
|
||||
/// <c>--value-stdin</c> must be supplied through stdin instead.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed record SetCommandLine(
|
||||
string Name,
|
||||
SecretValueSource Source,
|
||||
string? ArgumentValue,
|
||||
SecretContentType ContentType,
|
||||
string? Description)
|
||||
{
|
||||
/// <summary>The flag that requests the value from standard input.</summary>
|
||||
public const string ValueStdinFlag = "--value-stdin";
|
||||
|
||||
/// <summary>Printed to stderr whenever the deprecated positional value form is used.</summary>
|
||||
public const string ArgumentValueWarning =
|
||||
"warning: the secret value was passed on the command line, where it is kept in shell history "
|
||||
+ "and visible in the process list. Pipe it on stdin (`secret set <name> -`) or omit it to be "
|
||||
+ "prompted; the positional form will be removed in a future release.";
|
||||
|
||||
private static readonly HashSet<string> Flags =
|
||||
new(StringComparer.Ordinal) { "--content-type", "--description", ValueStdinFlag };
|
||||
|
||||
/// <summary>
|
||||
/// Parses <c><verb> <name> [<value>|-] [options]</c>. The value itself is
|
||||
/// never part of an exception message.
|
||||
/// </summary>
|
||||
/// <param name="args">The full argument vector, verb first.</param>
|
||||
/// <returns>The parsed command line.</returns>
|
||||
/// <exception cref="ArgumentException">A missing name, an unknown option, or conflicting value sources.</exception>
|
||||
public static SetCommandLine Parse(string[] args)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(args);
|
||||
if (args.Length < 2 || Flags.Contains(args[1]))
|
||||
{
|
||||
throw new ArgumentException($"{(args.Length > 0 ? args[0] : "set")} requires <name>.");
|
||||
}
|
||||
|
||||
string name = args[1];
|
||||
SecretValueSource source = SecretValueSource.Implicit;
|
||||
string? argumentValue = null;
|
||||
int optionsStart = 2;
|
||||
|
||||
if (args.Length > 2 && !Flags.Contains(args[2]))
|
||||
{
|
||||
optionsStart = 3;
|
||||
if (args[2] == "-")
|
||||
{
|
||||
source = SecretValueSource.Stdin;
|
||||
}
|
||||
else
|
||||
{
|
||||
source = SecretValueSource.Argument;
|
||||
argumentValue = args[2];
|
||||
}
|
||||
}
|
||||
|
||||
SecretContentType contentType = SecretContentType.Text;
|
||||
string? description = null;
|
||||
for (int i = optionsStart; i < args.Length; i++)
|
||||
{
|
||||
switch (args[i])
|
||||
{
|
||||
case "--content-type":
|
||||
contentType = ParseContentType(RequireValue(args, ref i));
|
||||
break;
|
||||
|
||||
case "--description":
|
||||
description = RequireValue(args, ref i);
|
||||
break;
|
||||
|
||||
case ValueStdinFlag:
|
||||
if (source == SecretValueSource.Argument)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"{ValueStdinFlag} cannot be combined with a value on the command line.");
|
||||
}
|
||||
|
||||
source = SecretValueSource.Stdin;
|
||||
break;
|
||||
|
||||
default:
|
||||
// Deliberately not echoed: a mistyped invocation can put the secret value here.
|
||||
throw new ArgumentException(
|
||||
$"Unexpected argument at position {i}; expected --content-type, --description or {ValueStdinFlag}.");
|
||||
}
|
||||
}
|
||||
|
||||
return new SetCommandLine(name, source, argumentValue, contentType, description);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Obtains the secret value from the source this command line names.
|
||||
/// </summary>
|
||||
/// <param name="stdin">Standard input.</param>
|
||||
/// <param name="stdinRedirected">Whether standard input is redirected (piped or a file).</param>
|
||||
/// <param name="prompt">Masked terminal prompt: takes a label, returns what was typed.</param>
|
||||
/// <param name="stderr">Where the deprecation warning goes.</param>
|
||||
/// <returns>The plaintext value.</returns>
|
||||
/// <exception cref="ArgumentException">Stdin was empty, or the two prompted entries differ.</exception>
|
||||
public string ReadValue(TextReader stdin, bool stdinRedirected, Func<string, string> prompt, TextWriter stderr)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stdin);
|
||||
ArgumentNullException.ThrowIfNull(prompt);
|
||||
ArgumentNullException.ThrowIfNull(stderr);
|
||||
|
||||
switch (Source)
|
||||
{
|
||||
case SecretValueSource.Argument:
|
||||
stderr.WriteLine(ArgumentValueWarning);
|
||||
return ArgumentValue!;
|
||||
|
||||
case SecretValueSource.Stdin:
|
||||
return ReadStdin(stdin);
|
||||
|
||||
default:
|
||||
if (stdinRedirected)
|
||||
{
|
||||
return ReadStdin(stdin);
|
||||
}
|
||||
|
||||
string first = prompt("Secret value:");
|
||||
string second = prompt("Confirm value:");
|
||||
if (!string.Equals(first, second, StringComparison.Ordinal))
|
||||
{
|
||||
throw new ArgumentException("The two entries do not match; nothing was written.");
|
||||
}
|
||||
|
||||
if (first.Length == 0)
|
||||
{
|
||||
throw new ArgumentException("An empty value was entered; nothing was written.");
|
||||
}
|
||||
|
||||
return first;
|
||||
}
|
||||
}
|
||||
|
||||
// The whole of stdin, less ONE trailing line terminator — what `echo`/`printf '%s\n'`/a heredoc
|
||||
// append, and never part of the secret. Any other whitespace is the operator's and is kept.
|
||||
private static string ReadStdin(TextReader stdin)
|
||||
{
|
||||
string value = stdin.ReadToEnd();
|
||||
if (value.EndsWith("\r\n", StringComparison.Ordinal))
|
||||
{
|
||||
value = value[..^2];
|
||||
}
|
||||
else if (value.EndsWith('\n'))
|
||||
{
|
||||
value = value[..^1];
|
||||
}
|
||||
|
||||
if (value.Length == 0)
|
||||
{
|
||||
throw new ArgumentException("No secret value was read from stdin; nothing was written.");
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private static string RequireValue(string[] args, ref int i)
|
||||
{
|
||||
if (i + 1 >= args.Length)
|
||||
{
|
||||
throw new ArgumentException($"{args[i]} requires a value.");
|
||||
}
|
||||
|
||||
return args[++i];
|
||||
}
|
||||
|
||||
// Maps the CLI content-type token (kebab-case) to the enum.
|
||||
private static SecretContentType ParseContentType(string value) => value switch
|
||||
{
|
||||
"text" => SecretContentType.Text,
|
||||
"connection-string" => SecretContentType.ConnectionString,
|
||||
"json" => SecretContentType.Json,
|
||||
"binary-base64" => SecretContentType.BinaryBase64,
|
||||
_ => throw new ArgumentException(
|
||||
$"Unknown --content-type '{value}'; expected text|connection-string|json|binary-base64."),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user