5f5d684c44
`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
219 lines
8.1 KiB
C#
219 lines
8.1 KiB
C#
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."),
|
|
};
|
|
}
|