using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.Secrets.Cli;
/// Where a set/rotate invocation takes the secret value from.
public enum SecretValueSource
{
///
/// No value on the command line: read standard input when it is redirected, otherwise prompt
/// (masked) at the terminal.
///
Implicit,
/// Read standard input, requested explicitly with - or --value-stdin.
Stdin,
///
/// The legacy positional <value>. Still accepted, with a warning: it lands in shell
/// history and is visible in the process list for the duration of the run.
///
Argument,
}
///
/// Parsing and value acquisition for the headless set and rotate verbs (scadaproj#35).
///
///
///
/// Accepted forms, for set and rotate alike:
///
///
/// 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
///
///
/// The third argument is a positional value unless it is exactly - or one of the option
/// flags, so a value that happens to equal --content-type, --description or
/// --value-stdin must be supplied through stdin instead.
///
///
public sealed record SetCommandLine(
string Name,
SecretValueSource Source,
string? ArgumentValue,
SecretContentType ContentType,
string? Description)
{
/// The flag that requests the value from standard input.
public const string ValueStdinFlag = "--value-stdin";
/// Printed to stderr whenever the deprecated positional value form is used.
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 -`) or omit it to be "
+ "prompted; the positional form will be removed in a future release.";
private static readonly HashSet Flags =
new(StringComparer.Ordinal) { "--content-type", "--description", ValueStdinFlag };
///
/// Parses <verb> <name> [<value>|-] [options]. The value itself is
/// never part of an exception message.
///
/// The full argument vector, verb first.
/// The parsed command line.
/// A missing name, an unknown option, or conflicting value sources.
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 .");
}
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);
}
///
/// Obtains the secret value from the source this command line names.
///
/// Standard input.
/// Whether standard input is redirected (piped or a file).
/// Masked terminal prompt: takes a label, returns what was typed.
/// Where the deprecation warning goes.
/// The plaintext value.
/// Stdin was empty, or the two prompted entries differ.
public string ReadValue(TextReader stdin, bool stdinRedirected, Func 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."),
};
}