From aee8b5daf0dde21f45f9f0c7095e0508a9015e94 Mon Sep 17 00:00:00 2001 From: James Nesbitt Date: Thu, 5 Nov 2026 15:47:58 +0200 Subject: [PATCH 1/3] [PRODENG-3922] Close credential redaction gaps in logging Both plausible readings of rig's redaction API are implemented somewhere in this codebase, and both are wrong: go.mod replaces github.com/k0sproject/rig/v2 with a fork whose cmd.Redact matches literally (strings.ReplaceAll) and whose repeated Redact options compose rather than overwrite. Two classes of call site assumed the opposite of what the fork does. Regex patterns handed to the literal matcher never matched anything, so nothing was redacted: init_swarm.go's `--token \S+` left the swarm manager join token in the log of every cluster init, and mke.go's CA-dump pattern left the full certificate unredacted. Neither secret is known at the call site -- both are in the command's OUTPUT, not its arguments -- so no Redact pattern, literal or regex, can mask them; both now use cmd.HideOutput() instead. The swarm tokens are read back later with `swarm join-token` when needed and the CA PEM is returned to the caller, so nothing is lost. regexp.QuoteMeta applied to a value before handing it to the literal matcher escapes it into a spelling that never appears in the log. This is invisible in testing, because QuoteMeta is the identity function for alphanumeric input: only a credential containing a regex metacharacter exposed it. Seven sites in pkg/configurer's two AuthenticateDocker implementations and two more inside install_mke.go's adminCredentialRedactions helper, which doubly escaped one of its two values (regexp.QuoteMeta(shellescape.Quote(value))). All now pass literal values. pkg/configurer/redaction_semantics_test.go pins the fork's actual behaviour -- a metacharacter-bearing value is masked, the QuoteMeta'd form is not, and two Redact options both take effect -- so a future bump that flips the semantics back toward regex fails this test rather than silently disabling redaction. install_mke_test.go's own redact() harness compiled each value as a regex before this change: production assumed regex, the test assumed regex, they agreed with each other and neither agreed with rig. It now calls the real rig code path. upgrade_msr.go gains redaction for the MKE credentials BuildMKEFlags injects into the command line; nothing covered it before. msr.Destroy has the same gap and is deliberately left to PRODENG-3923, which removes that credential from argv entirely rather than redacting it in place; 3923 rewrites msr.Destroy today and a second hand in that file in the same afternoon is the more expensive mistake. This PR must not merge before PRODENG-3923 (#691). pkg/config/config.go's case-sensitive config-dump regex never matched the schema's camelCase adminUsername/adminPassword and missed keyData/certData entirely. It is replaced with pkg/util/redact.YAML, the key-based masking PRODENG-3921 introduced. A configuration that fails to parse is still dumped -- a debug dump of a broken configuration is exactly when the output is wanted -- using the old regex as a documented best-effort fallback: the log line announcing the fallback states explicitly that the masking is partial, so an operator deciding whether to share the output knows which guarantee they are relying on. install_mke.go's raw `installFlags.Join()` debug line is removed. It ran before rig's own redaction and printed --admin-password and --license with their values; rig already logs the rendered command with the redactions above applied. Trace and Debug records previously reached the persistent log file (~/.mirantis-launchpad/cluster//*.log) on every run regardless of flags, because the file hook was registered for log.AllLevels while the logger itself was set to TraceLevel unconditionally. That is what made every other gap in this PR persistent on disk rather than transient on a terminal. The file hook now receives Trace only with --trace and Debug only with --debug; the logger's level is unchanged, so command behaviour elsewhere is unaffected. .changes/PRODENG-3922.md documents the operator-visible change. Written by AI: claude-opus-5 Signed-off-by: James Nesbitt --- .changes/PRODENG-3922.md | 5 ++ pkg/config/config.go | 32 +++++++++- pkg/config/redact_dump_test.go | 62 ++++++++++++++++++ pkg/configurer/linux.go | 20 +++--- pkg/configurer/redaction_semantics_test.go | 56 +++++++++++++++++ pkg/configurer/windows.go | 22 ++++--- pkg/log/file_hook_test.go | 73 ++++++++++++++++++++++ pkg/log/formatter_hook.go | 28 ++++++++- pkg/mke/mke.go | 8 ++- pkg/product/mke/phase/init_swarm.go | 11 +++- pkg/product/mke/phase/install_mke.go | 28 ++++++--- pkg/product/mke/phase/install_mke_test.go | 32 ++++++---- pkg/product/mke/phase/msr_redactions.go | 52 +++++++++++++++ pkg/product/mke/phase/upgrade_msr.go | 12 +++- 14 files changed, 397 insertions(+), 44 deletions(-) create mode 100644 .changes/PRODENG-3922.md create mode 100644 pkg/config/redact_dump_test.go create mode 100644 pkg/configurer/redaction_semantics_test.go create mode 100644 pkg/log/file_hook_test.go create mode 100644 pkg/product/mke/phase/msr_redactions.go diff --git a/.changes/PRODENG-3922.md b/.changes/PRODENG-3922.md new file mode 100644 index 000000000..c4138bfdd --- /dev/null +++ b/.changes/PRODENG-3922.md @@ -0,0 +1,5 @@ +**The log file no longer records Trace and Debug output unless you ask for it.** Launchpad writes a log for every run to `~/.mirantis-launchpad/cluster//*.log`. Until now that file received every record at every level, including Trace, whatever flags were passed. It now receives Info and above by default; pass `--debug` to include Debug records, or `--trace` to include both. Terminal output is unchanged. + +The reason for the change is what those records contained. Trace and Debug carry the commands launchpad runs on each host and their output, and several of those carried credentials that redaction was failing to mask — so the values were not merely shown once on a terminal, they were written to a file on every run and kept. The masking gaps are fixed alongside this, but a persistent file holding every Trace record is a standing exposure on its own, and nothing was asking for it. + +If you collect launchpad logs for support or for an incident review, add `--debug` to the run, or `--trace` for the fullest output. diff --git a/pkg/config/config.go b/pkg/config/config.go index 380b03384..36e82f425 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -30,6 +30,7 @@ import ( _ "github.com/Mirantis/launchpad/pkg/config/migration/v1beta3" "github.com/Mirantis/launchpad/pkg/product" "github.com/Mirantis/launchpad/pkg/product/mke" + "github.com/Mirantis/launchpad/pkg/util/redact" "github.com/a8m/envsubst" "github.com/k0sproject/rig/v2/cmd" log "github.com/sirupsen/logrus" @@ -83,8 +84,7 @@ func ProductFromYAML(data []byte) (product.Product, error) { //nolint:ireturn cfg := string(plain) if !cmd.DisableRedact { - re := regexp.MustCompile(`(username|password)([:= ]) ?\S+`) - cfg = re.ReplaceAllString(cfg, "$1$2[REDACTED]") + cfg = redactConfigDump(plain) } log.Debugf("loaded configuration:\n%s", cfg) @@ -105,6 +105,34 @@ func ProductFromYAML(data []byte) (product.Product, error) { //nolint:ireturn } } +// legacyRedactRegexp is the pre-PRODENG-3922 masking, kept only as a +// fallback for configurations that cannot be parsed as YAML. +// +// It is case sensitive, so it never matched the schema's camelCase +// adminPassword or adminUsername, and it does not cover keyData, certData, +// configData or host environment variables. That is why it was replaced. +var legacyRedactRegexp = regexp.MustCompile(`(username|password)([:= ]) ?\S+`) + +// redactConfigDump masks credentials in the configuration before it is +// written to the debug log, which persists to disk. +// +// A configuration that fails to parse still gets dumped, because a debug +// dump of a broken configuration is exactly when the output is wanted. It +// gets the old regex instead, and the log says so: that masking is +// best-effort on text nothing could parse, it is not the key-based +// redaction the parsed path gets, and an operator deciding whether to paste +// the output into a ticket needs to know which one they are looking at. +func redactConfigDump(plain []byte) string { + masked, err := redact.YAML(plain) + if err == nil { + return string(masked) + } + + log.Warnf("configuration could not be parsed for redaction (%s); the dump below is masked on a best-effort basis only and may still contain credentials", err) + + return legacyRedactRegexp.ReplaceAllString(string(plain), "$1$2[REDACTED]") +} + var errUnknownConfigKind = errors.New("unknown configuration kind") // Init returns an example cluster configuration. diff --git a/pkg/config/redact_dump_test.go b/pkg/config/redact_dump_test.go new file mode 100644 index 000000000..d551c6d17 --- /dev/null +++ b/pkg/config/redact_dump_test.go @@ -0,0 +1,62 @@ +package config + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// The regex this replaced was case sensitive and matched neither the +// schema's camelCase keys nor the inline data fields, so a configuration +// dumped to the log carried the admin password in clear. +func TestRedactConfigDumpMasksSchemaKeys(t *testing.T) { + dump := redactConfigDump([]byte(`apiVersion: launchpad.mirantis.com/mke/v1.6 +kind: mke +spec: + hosts: + - winRM: + address: 10.0.0.1 + password: fake-host-password + role: manager + environment: + REGISTRY_TOKEN: fake-registry-token + mke: + adminUsername: fake-admin-user + adminPassword: fake-admin-password + keyData: fake-key-material +`)) + + for _, secret := range []string{ + "fake-host-password", + "fake-registry-token", + "fake-admin-user", + "fake-admin-password", + "fake-key-material", + } { + require.NotContainsf(t, dump, secret, "the config dump leaked %q:\n%s", secret, dump) + } + + require.Contains(t, dump, "10.0.0.1", "non-credential configuration must survive, or the dump is useless") +} + +// A configuration that cannot be parsed is still dumped, because a debug +// dump of a broken configuration is exactly when the output is wanted. The +// masking it gets is the old regex, which is best-effort: it is case +// sensitive and knows only two key names. +func TestRedactConfigDumpFallsBackOnUnparseableInput(t *testing.T) { + dump := redactConfigDump([]byte("spec:\n hosts:\n - broken\n\tpassword: fake-host-password\n")) + + require.NotContains(t, dump, "fake-host-password", "the fallback must still mask what it can match") + require.Contains(t, dump, "[REDACTED]") +} + +// The fallback's weakness is the reason it is documented rather than +// trusted: it matches lowercase username and password only, so a camelCase +// key in an unparseable document is not masked. This pins the limit so that +// nobody reads the fallback as equivalent to the parsed path. +func TestRedactConfigDumpFallbackDoesNotCoverSchemaKeys(t *testing.T) { + dump := redactConfigDump([]byte("spec:\n mke:\n - broken\n\tadminPassword: fake-admin-password\n")) + + require.Contains(t, dump, "fake-admin-password", + "if this now masks, the fallback improved and its documented limit should be updated") +} diff --git a/pkg/configurer/linux.go b/pkg/configurer/linux.go index 00f375ebc..4ef71673f 100644 --- a/pkg/configurer/linux.go +++ b/pkg/configurer/linux.go @@ -410,16 +410,20 @@ func (c LinuxConfigurer) AuthorizeDocker(h Host) error { // AuthenticateDocker performs a docker login on the host. func (c LinuxConfigurer) AuthenticateDocker(h Host, user, pass, imageRepo string) error { - dc := c.DockerCmd() - loginCmd := dc.Raw("login -u").Arg(user).Raw("--password-stdin").Arg(imageRepo).String() - // The username reaches the command line quoted; the password only goes in - // over stdin. Patterns are built from both forms so redaction matches - // whichever one is logged. + dockerCmd := c.DockerCmd() + loginCmd := dockerCmd.Raw("login -u").Arg(user).Raw("--password-stdin").Arg(imageRepo).String() + // The username reaches the command line quoted; the password only goes + // in over stdin. Both forms are listed because rig matches redactions + // literally -- cmd/execoptions.go RedactString is strings.ReplaceAll -- + // so a redaction has to be the exact text that appears in the log, and + // the quoting changes that text. regexp.QuoteMeta must not be applied: + // it escapes the value into a spelling that never occurs, which fails + // silently for any value containing a regex metacharacter. if err := h.Exec(loginCmd, cmd.StdinString(pass), - cmd.Redact(regexp.QuoteMeta(dc.Quote(user))), - cmd.Redact(regexp.QuoteMeta(user)), - cmd.Redact(regexp.QuoteMeta(pass)), + cmd.Redact(dockerCmd.Quote(user)), + cmd.Redact(user), + cmd.Redact(pass), ); err != nil { return fmt.Errorf("failed to login to the docker registry: %w", err) } diff --git a/pkg/configurer/redaction_semantics_test.go b/pkg/configurer/redaction_semantics_test.go new file mode 100644 index 000000000..e0ae80f74 --- /dev/null +++ b/pkg/configurer/redaction_semantics_test.go @@ -0,0 +1,56 @@ +package configurer_test + +import ( + "regexp" + "testing" + + rigcmd "github.com/k0sproject/rig/v2/cmd" + "github.com/stretchr/testify/require" +) + +// TestRigRedactionIsLiteral pins how rig treats the values passed to +// cmd.Redact, at the version go.mod resolves to. +// +// Launchpad's redaction sites depend on two properties that are not visible +// from the call site and that both plausible readings of the API get wrong in +// opposite directions: +// +// - the values are matched literally, not as regular expressions, so +// wrapping a credential in regexp.QuoteMeta produces a spelling that +// never appears in the output. That failure is invisible in testing, +// because QuoteMeta is the identity function for alphanumerics: only a +// credential containing a regex metacharacter exposes it. +// - repeated cmd.Redact options compose rather than overwrite, so a call +// site may list the raw and the shell-quoted form of the same value. +// +// go.mod replaces github.com/k0sproject/rig/v2 with a fork, so neither +// property can be assumed from the upstream module's source: the v1 API +// compiled a regexp. If the fork is bumped and the semantics change, this +// test fails rather than the redaction silently doing nothing. +func TestRigRedactionIsLiteral(t *testing.T) { + t.Parallel() + + const password = `p$ss.w*rd` + + opts := rigcmd.Build(rigcmd.Redact(password)) + require.Equal(t, "login -p "+rigcmd.DefaultRedactMask, opts.RedactString("login -p "+password), + "a credential containing regex metacharacters must be matched literally") + + // The same value escaped for a regex matcher is not what appears in the + // command, so it redacts nothing. This is the defect the production + // sites had. + escaped := rigcmd.Build(rigcmd.Redact(regexp.QuoteMeta(password))) + require.Equal(t, "login -p "+password, escaped.RedactString("login -p "+password), + "regexp.QuoteMeta must not be applied to a value handed to cmd.Redact") +} + +func TestRigRedactionsCompose(t *testing.T) { + t.Parallel() + + opts := rigcmd.Build(rigcmd.Redact("alice"), rigcmd.Redact("hunter2")) + + got := opts.RedactString("login -u alice -p hunter2") + + require.NotContains(t, got, "alice", "an earlier cmd.Redact must not be discarded by a later one") + require.NotContains(t, got, "hunter2") +} diff --git a/pkg/configurer/windows.go b/pkg/configurer/windows.go index 40d0b5da0..fd21e066f 100644 --- a/pkg/configurer/windows.go +++ b/pkg/configurer/windows.go @@ -397,15 +397,21 @@ func (c WindowsConfigurer) CheckPrivilege(h Host) error { // AuthenticateDocker performs a docker login on the host. func (c WindowsConfigurer) AuthenticateDocker(h Host, user, pass, imageRepo string) error { // the --pasword-stdin seems to hang in windows - dc := c.DockerCmd() - loginCmd := dc.Raw("login -u").Arg(user).Raw("-p").Arg(pass).Arg(imageRepo).String() - // The command line holds the quoted forms, so patterns built from the raw - // values would not match once quoting alters them. + dockerCmd := c.DockerCmd() + loginCmd := dockerCmd.Raw("login -u").Arg(user).Raw("-p").Arg(pass).Arg(imageRepo).String() + // The command line holds the quoted forms, so the raw values alone + // would not match once quoting alters them; both forms are listed. + // rig matches redactions literally (cmd/execoptions.go RedactString is + // strings.ReplaceAll), so each value must be the exact text that + // appears in the log. regexp.QuoteMeta must not be applied: it escapes + // the value into a spelling that never occurs, and because QuoteMeta is + // the identity function for alphanumerics the failure is invisible + // until a password contains a metacharacter. redactions := []cmd.ExecOption{ - cmd.Redact(regexp.QuoteMeta(dc.Quote(pass))), - cmd.Redact(regexp.QuoteMeta(dc.Quote(user))), - cmd.Redact(regexp.QuoteMeta(pass)), - cmd.Redact(regexp.QuoteMeta(user)), + cmd.Redact(dockerCmd.Quote(pass)), + cmd.Redact(dockerCmd.Quote(user)), + cmd.Redact(pass), + cmd.Redact(user), cmd.AllowWinStderr(), } if err := h.Exec(loginCmd, redactions...); err != nil { diff --git a/pkg/log/file_hook_test.go b/pkg/log/file_hook_test.go new file mode 100644 index 000000000..47c3f9356 --- /dev/null +++ b/pkg/log/file_hook_test.go @@ -0,0 +1,73 @@ +package log_test + +import ( + "os" + "path/filepath" + "testing" + + mcclog "github.com/Mirantis/launchpad/pkg/log" + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/require" +) + +// logThrough writes one record at each level through a logger carrying only +// the file hook, and returns what reached the file. +func logThrough(t *testing.T, message string) string { + t.Helper() + + path := filepath.Join(t.TempDir(), "launchpad.log") + + file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) + require.NoError(t, err) + + logger := logrus.New() + logger.SetLevel(logrus.TraceLevel) + logger.SetOutput(os.NewFile(0, os.DevNull)) + logger.AddHook(mcclog.NewFileHook(file)) + + logger.Trace(message) + logger.Debug(message) + logger.Info("install started") + + require.NoError(t, file.Close()) + + contents, err := os.ReadFile(path) + require.NoError(t, err) + + return string(contents) +} + +// The log file is written for every run and kept on disk, so a credential in +// a Trace record outlives the terminal it would have scrolled past. Trace and +// Debug records reach it only when the operator asked for them. +func TestFileHookPersistsTraceOnlyWhenRequested(t *testing.T) { + const credential = "fake-admin-password" + + t.Run("default", func(t *testing.T) { + mcclog.Debug, mcclog.Trace = false, false + t.Cleanup(func() { mcclog.Debug, mcclog.Trace = false, false }) + + got := logThrough(t, "docker login -p "+credential) + + require.NotContains(t, got, credential, "a trace record reached the log file without --debug or --trace") + require.Contains(t, got, "install started", "the file must still carry the records it is read for") + }) + + t.Run("debug", func(t *testing.T) { + mcclog.Debug, mcclog.Trace = true, false + t.Cleanup(func() { mcclog.Debug, mcclog.Trace = false, false }) + + got := logThrough(t, "debug record") + + require.Contains(t, got, "debug record") + }) + + t.Run("trace", func(t *testing.T) { + mcclog.Debug, mcclog.Trace = true, true + t.Cleanup(func() { mcclog.Debug, mcclog.Trace = false, false }) + + got := logThrough(t, "trace record") + + require.Contains(t, got, "trace record") + }) +} diff --git a/pkg/log/formatter_hook.go b/pkg/log/formatter_hook.go index 05b5e05e8..c8b654a1a 100644 --- a/pkg/log/formatter_hook.go +++ b/pkg/log/formatter_hook.go @@ -67,17 +67,41 @@ func NewStdoutHook() *FormatterWriterHook { return stdoutHook } -// NewFileHook creates logrus hook for logging all levels to file. +// NewFileHook creates a logrus hook for logging to file. +// +// The file is persistent, so the levels it receives are not log.AllLevels. +// Trace and Debug records carry remote command lines and their output, and +// the file is written for every run regardless of flags, so an unredacted +// value in a Trace record outlives the terminal it would otherwise have +// scrolled past. Trace is written only with --trace and Debug only with +// --debug; without either, the file holds Info and above, which is what it +// is read for. See PRODENG-3922. func NewFileHook(logFile *os.File) *FormatterWriterHook { fileFormatter := &log.TextFormatter{ DisableColors: true, FullTimestamp: true, TimestampFormat: time.RFC822, } + + levels := []log.Level{ + log.PanicLevel, + log.FatalLevel, + log.ErrorLevel, + log.WarnLevel, + log.InfoLevel, + } + + switch { + case Trace: + levels = append(levels, log.DebugLevel, log.TraceLevel) + case Debug: + levels = append(levels, log.DebugLevel) + } + fileHook := &FormatterWriterHook{ Writer: logFile, Formatter: fileFormatter, - LogLevels: log.AllLevels, + LogLevels: levels, } return fileHook diff --git a/pkg/mke/mke.go b/pkg/mke/mke.go index 44a976bcf..4a4e9995e 100644 --- a/pkg/mke/mke.go +++ b/pkg/mke/mke.go @@ -159,7 +159,13 @@ func GetTLSConfigFrom(manager *mkeconfig.Host, imageRepo, mkeVersion string) (*t if manager.Configurer.SELinuxEnabled(manager) { runFlags.Add("--security-opt label=disable") } - output, err := manager.ExecOutput(manager.Configurer.DockerCmd().Raw("run").Raw(runFlags.Join()).Arg(fmt.Sprintf("%s/ucp:%s", imageRepo, mkeVersion)).Raw("dump-certs --ca").String(), rigcmd.Redact(`[A-Za-z0-9+/=_\-]{64}`)) + // The CA PEM is the command's output and is not known here, so it + // cannot be given to rigcmd.Redact, which matches literally. The + // previous `[A-Za-z0-9+/=_\-]{64}` was a regex handed to that literal + // matcher: it looked for that pattern as a literal string, matched + // nothing, and the certificate was logged in full. The output is + // returned to the caller, so hiding it from the log costs nothing. + output, err := manager.ExecOutput(manager.Configurer.DockerCmd().Raw("run").Raw(runFlags.Join()).Arg(fmt.Sprintf("%s/ucp:%s", imageRepo, mkeVersion)).Raw("dump-certs --ca").String(), rigcmd.HideOutput()) if err != nil { return nil, fmt.Errorf("%w: error while exec-ing into the container: %w", errGetTLSConfig, err) } diff --git a/pkg/product/mke/phase/init_swarm.go b/pkg/product/mke/phase/init_swarm.go index 8e26d8e2c..fc7300752 100644 --- a/pkg/product/mke/phase/init_swarm.go +++ b/pkg/product/mke/phase/init_swarm.go @@ -26,7 +26,16 @@ func (p *InitSwarm) Run() error { if !swarm.IsSwarmNode(swarmLeader) { log.Infof("%s: initializing swarm", swarmLeader) - err := swarmLeader.Exec(swarmLeader.Configurer.DockerCmd().Raw("swarm init").Arg(fmt.Sprintf("--advertise-addr=%s", swarmLeader.SwarmAddress())).Raw(p.Config.Spec.MCR.SwarmInstallFlags.Join()).String(), cmd.Redact(`--token \S+`)) + // The worker join token is printed by "swarm init" itself, in the + // "docker swarm join --token ..." line of its output, so the value + // is not known here and cannot be given to cmd.Redact, which + // matches literally. The previous `--token \S+` pattern was a + // regex handed to that literal matcher and never matched anything, + // leaving the token in the log of every cluster initialisation. + // The output carries nothing else of use -- the tokens are read + // back with "swarm join-token" when they are needed -- so it is + // kept out of the log entirely. + err := swarmLeader.Exec(swarmLeader.Configurer.DockerCmd().Raw("swarm init").Arg(fmt.Sprintf("--advertise-addr=%s", swarmLeader.SwarmAddress())).Raw(p.Config.Spec.MCR.SwarmInstallFlags.Join()).String(), cmd.HideOutput()) if err != nil { return fmt.Errorf("failed to initialize swarm: %w", err) } diff --git a/pkg/product/mke/phase/install_mke.go b/pkg/product/mke/phase/install_mke.go index a49d6cfd4..c45afeb18 100644 --- a/pkg/product/mke/phase/install_mke.go +++ b/pkg/product/mke/phase/install_mke.go @@ -47,21 +47,28 @@ func adminCredentialFlags(username, password string) []string { return flags } -// adminCredentialRedactions returns regex patterns covering every form the -// admin credentials take in the rendered command: the raw value and the -// shell-quoted value produced by adminCredentialFlags. Redacting only the raw -// value leaks the quoted one: shell-quoting a value that contains a single -// quote rewrites it, so the raw pattern no longer matches what is logged. -// Empty values are skipped, because an empty pattern matches everywhere. +// adminCredentialRedactions returns the literal strings the admin +// credentials take in the rendered command: the raw value and the +// shell-quoted value produced by adminCredentialFlags. Redacting only the +// raw value leaks the quoted one, because shell-quoting a value that +// contains a single quote rewrites it. +// +// The values are returned unescaped. rig matches redactions literally +// (cmd/execoptions.go RedactString is strings.ReplaceAll), so wrapping them +// in regexp.QuoteMeta produced a spelling that never appears in the log -- +// invisibly, since QuoteMeta is the identity function for alphanumerics and +// only a credential containing a regex metacharacter exposed it. +// +// Empty values are skipped, because an empty match would redact everywhere. func adminCredentialRedactions(username, password string) []string { var patterns []string for _, value := range []string{username, password} { if value == "" { continue } - patterns = append(patterns, regexp.QuoteMeta(value)) + patterns = append(patterns, value) if quoted := shellescape.Quote(value); quoted != value { - patterns = append(patterns, regexp.QuoteMeta(quoted)) + patterns = append(patterns, quoted) } } return patterns @@ -137,7 +144,10 @@ func (p *InstallMKE) Run() error { execOpts = append(execOpts, cmd.Redact(pattern)) } - log.Debugf("%s: install flags: %s", p.leader, installFlags.Join()) + // The flag list is deliberately not logged here: it carries + // --admin-password and --license with their values, and this line ran + // before rig's redaction, which applies only to the command rig + // executes. rig logs that command with the redactions above applied. output, err := mke.Bootstrap("install", *p.Config, mke.BootstrapOptions{OperationFlags: installFlags, CleanupDisabled: p.CleanupDisabled(), ExecOptions: execOpts}) if err != nil { return fmt.Errorf("%s: failed to run MKE installer: \n output: %s \n error: %w", p.leader, output, err) diff --git a/pkg/product/mke/phase/install_mke_test.go b/pkg/product/mke/phase/install_mke_test.go index dd05c2c51..8c3c44363 100644 --- a/pkg/product/mke/phase/install_mke_test.go +++ b/pkg/product/mke/phase/install_mke_test.go @@ -1,26 +1,35 @@ package phase import ( - "regexp" "strings" "testing" + rigcmd "github.com/k0sproject/rig/v2/cmd" "github.com/k0sproject/rig/v2/sh/shellescape" "github.com/stretchr/testify/require" ) -// redact applies the patterns the way cmd.Redact does, so the test exercises -// the rendered command rather than the pattern strings in isolation. -func redact(t *testing.T, patterns []string, rendered string) string { +// redact applies the values the way rig does: cmd.Redact appends to a list +// of literal matches, and each is removed with strings.ReplaceAll +// (cmd/execoptions.go). The harness previously compiled each value as a +// regular expression, which is what the production code assumed when it +// wrapped them in regexp.QuoteMeta -- so both sides agreed with each other +// and neither agreed with rig. +func redact(t *testing.T, values []string, rendered string) string { t.Helper() - for _, pattern := range patterns { - re, err := regexp.Compile(pattern) - require.NoError(t, err, "pattern %q does not compile", pattern) - rendered = re.ReplaceAllString(rendered, "[REDACTED]") + opts := rigcmd.Build(values2options(values)...) + + return opts.RedactString(rendered) +} + +func values2options(values []string) []rigcmd.ExecOption { + opts := make([]rigcmd.ExecOption, 0, len(values)) + for _, value := range values { + opts = append(opts, rigcmd.Redact(value)) } - return rendered + return opts } // TestAdminCredentialRedactionsCoverRenderedFlags pins the contract between the @@ -73,9 +82,8 @@ func TestAdminCredentialRedactionsMatchQuotedForm(t *testing.T) { // shellescape closes the quote, emits an escaped quote, and reopens it. require.Contains(t, rendered, `--admin-password 'p@ss'"'"'w0rd'`) - rawOnly := regexp.MustCompile(regexp.QuoteMeta(password)) - require.False(t, rawOnly.MatchString(rendered), - "raw-value-only pattern unexpectedly matches %q; the regression this guards would not be detectable", rendered) + require.NotContains(t, rendered, password, + "the raw value unexpectedly appears in %q; the regression this guards would not be detectable", rendered) require.NotContains(t, redact(t, adminCredentialRedactions("admin", password), rendered), "w0rd") } diff --git a/pkg/product/mke/phase/msr_redactions.go b/pkg/product/mke/phase/msr_redactions.go new file mode 100644 index 000000000..ca7922b42 --- /dev/null +++ b/pkg/product/mke/phase/msr_redactions.go @@ -0,0 +1,52 @@ +package phase + +import ( + commonconfig "github.com/Mirantis/launchpad/pkg/product/common/config" +) + +// msrCredentialFlags are the MSR bootstrapper flags whose values are +// credentials and which launchpad puts on the command line. +var msrCredentialFlags = []string{"--ucp-username", "--ucp-password"} + +// msrCredentialRedactions returns the literal strings to keep out of the log +// for an MSR bootstrapper invocation. +// +// Both the value as it appears in the flag list and the value with its +// surrounding quotes removed are returned: BuildMKEFlags writes +// --ucp-password="secret", so the text in the command is the quoted form, +// while an operator grepping the log for the configured password looks for +// the raw one. rig matches redactions literally, so each spelling has to be +// listed separately; an empty value is skipped, because an empty match +// would redact the entire output. +func msrCredentialRedactions(flags commonconfig.Flags) []string { + var values []string + + for _, flag := range msrCredentialFlags { + quoted := flags.Get(flag) + if quoted == "" { + continue + } + + if value := commonconfig.FlagValue(quoted); value != "" { + values = append(values, value) + } + + if idx := indexOfValue(quoted); idx >= 0 && idx < len(quoted)-1 { + values = append(values, quoted[idx+1:]) + } + } + + return values +} + +// indexOfValue returns the position of the separator between a flag and its +// value, or -1 when the flag carries none. +func indexOfValue(flag string) int { + for i, char := range flag { + if char == '=' || char == ' ' { + return i + } + } + + return -1 +} diff --git a/pkg/product/mke/phase/upgrade_msr.go b/pkg/product/mke/phase/upgrade_msr.go index 3969b85d6..1105fa34b 100644 --- a/pkg/product/mke/phase/upgrade_msr.go +++ b/pkg/product/mke/phase/upgrade_msr.go @@ -7,6 +7,7 @@ import ( "github.com/Mirantis/launchpad/pkg/msr" "github.com/Mirantis/launchpad/pkg/phase" commonconfig "github.com/Mirantis/launchpad/pkg/product/common/config" + "github.com/k0sproject/rig/v2/cmd" "github.com/k0sproject/rig/v2/sh/shellescape" log "github.com/sirupsen/logrus" ) @@ -50,7 +51,16 @@ func (p *UpgradeMSR) Run() error { } upgradeFlags.MergeOverwrite(p.Config.Spec.MSR.UpgradeFlags) - if _, err := msr.Bootstrap("upgrade", *p.Config, msr.BootstrapOptions{OperationFlags: upgradeFlags, CleanupDisabled: p.CleanupDisabled()}); err != nil { + // BuildMKEFlags puts --ucp-username and --ucp-password on the command + // line, so the values are redacted out of the log in both the form + // BuildMKEFlags writes and the raw form. PRODENG-3923 removes them from + // the command line entirely, after which these are no-ops. + execOpts := make([]cmd.ExecOption, 0, len(msrCredentialRedactions(upgradeFlags))) + for _, value := range msrCredentialRedactions(upgradeFlags) { + execOpts = append(execOpts, cmd.Redact(value)) + } + + if _, err := msr.Bootstrap("upgrade", *p.Config, msr.BootstrapOptions{OperationFlags: upgradeFlags, CleanupDisabled: p.CleanupDisabled(), ExecOptions: execOpts}); err != nil { return fmt.Errorf("%s: failed to run MSR upgrader: %w", h, err) } From 67a48a145e03ecfec6835a5b747948ef6c5c6f5e Mon Sep 17 00:00:00 2001 From: James Nesbitt Date: Thu, 5 Nov 2026 16:06:47 +0200 Subject: [PATCH 2/3] [PRODENG-3922] Close review findings on redaction ordering and coverage Three measured defects from the review of #695, plus a strengthened fallback. Registration order decided whether a credential was masked. rig replaces each registered value in turn with strings.ReplaceAll, so a value that is a prefix of another destroys the longer match before it is tried. Measured with the real code path: username "admin" and password "admin!s3cr3t" registered in that order yield "login -u [REDACTED] -p [REDACTED]!s3cr3t", and the distinctive part of the password survives. redact.ByLengthDesc orders values longest first and drops empty ones; every site that registers more than one value now uses it -- both AuthenticateDocker implementations, adminCredentialRedactions, and the MSR helper. msrCredentialRedactions missed two spellings. A flag and its value in separate list elements ("--ucp-password", "split-secret") form a working command once Flags.Join concatenates them, but Flags.Get returns only the flag, so nothing was registered; the value is now read from the following element. And FlagValue uses strconv.Unquote, which does not decode the shell quoting BuildMKEFlags produces, so for a password containing a quote only the rendered spelling was registered and the password itself stayed visible wherever the bootstrapper echoed it back; the shell-decoded form is now registered alongside the rendered one. The unparseable-config fallback no longer uses the old two-word case-sensitive regex. redact.Text applies the same key set and the same environment-variable fragments as the structured path, line by line, so a configuration that fails to parse keeps camelCase and environment coverage instead of losing it. The real limit is now multi-line values rather than key names: a credential in a block scalar is not masked, which is what the log line means by best-effort. That limit is pinned by a test, and the test that pinned the previous weaker limit failed when this landed, which is what it was written to do. Four regression tests for the MSR helper, two for the fallback, one for ordering. The test helper in install_mke_test.go is renamed to applyRedactions to avoid shadowing the redact package. Written by AI: claude-opus-5 Signed-off-by: James Nesbitt --- pkg/config/config.go | 31 ++++---- pkg/config/redact_dump_test.go | 32 ++++---- pkg/configurer/linux.go | 20 +++-- pkg/configurer/windows.go | 17 ++-- pkg/product/mke/phase/install_mke.go | 9 ++- pkg/product/mke/phase/install_mke_test.go | 6 +- pkg/product/mke/phase/msr_redactions.go | 81 ++++++++++++++------ pkg/product/mke/phase/msr_redactions_test.go | 65 ++++++++++++++++ pkg/util/redact/values.go | 75 ++++++++++++++++++ 9 files changed, 265 insertions(+), 71 deletions(-) create mode 100644 pkg/product/mke/phase/msr_redactions_test.go create mode 100644 pkg/util/redact/values.go diff --git a/pkg/config/config.go b/pkg/config/config.go index 36e82f425..8e3eefa9a 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -6,7 +6,6 @@ import ( "io" "os" "path/filepath" - "regexp" "strings" "github.com/Mirantis/launchpad/pkg/config/migration" @@ -105,32 +104,30 @@ func ProductFromYAML(data []byte) (product.Product, error) { //nolint:ireturn } } -// legacyRedactRegexp is the pre-PRODENG-3922 masking, kept only as a -// fallback for configurations that cannot be parsed as YAML. -// -// It is case sensitive, so it never matched the schema's camelCase -// adminPassword or adminUsername, and it does not cover keyData, certData, -// configData or host environment variables. That is why it was replaced. -var legacyRedactRegexp = regexp.MustCompile(`(username|password)([:= ]) ?\S+`) - // redactConfigDump masks credentials in the configuration before it is // written to the debug log, which persists to disk. // -// A configuration that fails to parse still gets dumped, because a debug -// dump of a broken configuration is exactly when the output is wanted. It -// gets the old regex instead, and the log says so: that masking is -// best-effort on text nothing could parse, it is not the key-based -// redaction the parsed path gets, and an operator deciding whether to paste -// the output into a ticket needs to know which one they are looking at. +// A configuration that fails to parse is still dumped, because a debug dump +// of a broken configuration is exactly when the output is wanted. It gets +// redact.Text instead of redact.YAML: the same key set and the same +// environment-variable fragments, applied line by line rather than over a +// parsed structure. +// +// The difference is stated in the log line rather than left for the reader +// to infer. redact.Text cannot see a credential that is not on the same +// line as its key -- a YAML block scalar holding a private key is the case +// that matters -- so the output is masked on a best-effort basis and an +// operator deciding whether to attach it to a ticket needs to know which of +// the two they are looking at. func redactConfigDump(plain []byte) string { masked, err := redact.YAML(plain) if err == nil { return string(masked) } - log.Warnf("configuration could not be parsed for redaction (%s); the dump below is masked on a best-effort basis only and may still contain credentials", err) + log.Warnf("configuration could not be parsed for redaction (%s); the dump below is masked line by line on a best-effort basis and may still contain credentials that span lines", err) - return legacyRedactRegexp.ReplaceAllString(string(plain), "$1$2[REDACTED]") + return string(redact.Text(plain)) } var errUnknownConfigKind = errors.New("unknown configuration kind") diff --git a/pkg/config/redact_dump_test.go b/pkg/config/redact_dump_test.go index d551c6d17..5c52eaa49 100644 --- a/pkg/config/redact_dump_test.go +++ b/pkg/config/redact_dump_test.go @@ -41,22 +41,28 @@ spec: // A configuration that cannot be parsed is still dumped, because a debug // dump of a broken configuration is exactly when the output is wanted. The -// masking it gets is the old regex, which is best-effort: it is case -// sensitive and knows only two key names. +// masking it gets is line oriented rather than structural, but it covers +// the same key set, so camelCase schema keys and credential-named +// environment variables are masked there too. func TestRedactConfigDumpFallsBackOnUnparseableInput(t *testing.T) { - dump := redactConfigDump([]byte("spec:\n hosts:\n - broken\n\tpassword: fake-host-password\n")) + dump := redactConfigDump([]byte( + "spec:\n hosts:\n - broken\n\tpassword: fake-host-password\n" + + "\tadminPassword: fake-admin-password\n" + + "\tREGISTRY_TOKEN: fake-registry-token\n")) - require.NotContains(t, dump, "fake-host-password", "the fallback must still mask what it can match") - require.Contains(t, dump, "[REDACTED]") + for _, secret := range []string{"fake-host-password", "fake-admin-password", "fake-registry-token"} { + require.NotContainsf(t, dump, secret, "the fallback left %q in an unparseable config dump:\n%s", secret, dump) + } } -// The fallback's weakness is the reason it is documented rather than -// trusted: it matches lowercase username and password only, so a camelCase -// key in an unparseable document is not masked. This pins the limit so that -// nobody reads the fallback as equivalent to the parsed path. -func TestRedactConfigDumpFallbackDoesNotCoverSchemaKeys(t *testing.T) { - dump := redactConfigDump([]byte("spec:\n mke:\n - broken\n\tadminPassword: fake-admin-password\n")) +// The fallback's real limit, and the reason the log line calls it +// best-effort: it works a line at a time, so a credential in a block scalar +// is not masked. The parsed path has no such gap. This pins the boundary so +// that nobody reads the two as equivalent. +func TestRedactConfigDumpFallbackCannotSeeBlockScalars(t *testing.T) { + dump := redactConfigDump([]byte( + "spec:\n mke:\n - broken\n\tkeyData: |\n\t fake-key-line-one\n\t fake-key-line-two\n")) - require.Contains(t, dump, "fake-admin-password", - "if this now masks, the fallback improved and its documented limit should be updated") + require.Contains(t, dump, "fake-key-line-one", + "if this now masks, the fallback gained multi-line coverage and the log line's wording should be revisited") } diff --git a/pkg/configurer/linux.go b/pkg/configurer/linux.go index 4ef71673f..9caa24105 100644 --- a/pkg/configurer/linux.go +++ b/pkg/configurer/linux.go @@ -13,6 +13,7 @@ import ( "github.com/Mirantis/launchpad/pkg/constant" commonconfig "github.com/Mirantis/launchpad/pkg/product/common/config" "github.com/Mirantis/launchpad/pkg/util/iputil" + "github.com/Mirantis/launchpad/pkg/util/redact" "github.com/k0sproject/rig/v2/cmd" rigos "github.com/k0sproject/rig/v2/os" "github.com/k0sproject/rig/v2/remotefs" @@ -419,12 +420,19 @@ func (c LinuxConfigurer) AuthenticateDocker(h Host, user, pass, imageRepo string // the quoting changes that text. regexp.QuoteMeta must not be applied: // it escapes the value into a spelling that never occurs, which fails // silently for any value containing a regex metacharacter. - if err := h.Exec(loginCmd, - cmd.StdinString(pass), - cmd.Redact(dockerCmd.Quote(user)), - cmd.Redact(user), - cmd.Redact(pass), - ); err != nil { + // + // Longest first: rig replaces each value in turn, so a username that is + // a prefix of the password would otherwise be substituted first and + // leave the rest of the password in the log. + values := redact.ByLengthDesc(dockerCmd.Quote(user), user, pass) + opts := make([]cmd.ExecOption, 0, len(values)+1) + opts = append(opts, cmd.StdinString(pass)) + + for _, value := range values { + opts = append(opts, cmd.Redact(value)) + } + + if err := h.Exec(loginCmd, opts...); err != nil { return fmt.Errorf("failed to login to the docker registry: %w", err) } return nil diff --git a/pkg/configurer/windows.go b/pkg/configurer/windows.go index fd21e066f..eae3b5a5e 100644 --- a/pkg/configurer/windows.go +++ b/pkg/configurer/windows.go @@ -14,6 +14,7 @@ import ( "github.com/Mirantis/launchpad/pkg/constant" commonconfig "github.com/Mirantis/launchpad/pkg/product/common/config" "github.com/Mirantis/launchpad/pkg/util/iputil" + "github.com/Mirantis/launchpad/pkg/util/redact" "github.com/avast/retry-go" "github.com/hashicorp/go-version" "github.com/k0sproject/rig/v2/cmd" @@ -407,12 +408,16 @@ func (c WindowsConfigurer) AuthenticateDocker(h Host, user, pass, imageRepo stri // the value into a spelling that never occurs, and because QuoteMeta is // the identity function for alphanumerics the failure is invisible // until a password contains a metacharacter. - redactions := []cmd.ExecOption{ - cmd.Redact(dockerCmd.Quote(pass)), - cmd.Redact(dockerCmd.Quote(user)), - cmd.Redact(pass), - cmd.Redact(user), - cmd.AllowWinStderr(), + // + // Longest first: rig replaces each value in turn, so a username that is + // a prefix of the password would otherwise be substituted first and + // leave the rest of the password in the log. + values := redact.ByLengthDesc(dockerCmd.Quote(pass), dockerCmd.Quote(user), pass, user) + redactions := make([]cmd.ExecOption, 0, len(values)+1) + redactions = append(redactions, cmd.AllowWinStderr()) + + for _, value := range values { + redactions = append(redactions, cmd.Redact(value)) } if err := h.Exec(loginCmd, redactions...); err != nil { return fmt.Errorf("failed to login to docker registry: %w", err) diff --git a/pkg/product/mke/phase/install_mke.go b/pkg/product/mke/phase/install_mke.go index c45afeb18..047fc4789 100644 --- a/pkg/product/mke/phase/install_mke.go +++ b/pkg/product/mke/phase/install_mke.go @@ -12,6 +12,7 @@ import ( "github.com/Mirantis/launchpad/pkg/phase" mkeconfig "github.com/Mirantis/launchpad/pkg/product/mke/config" "github.com/Mirantis/launchpad/pkg/util/installutil" + "github.com/Mirantis/launchpad/pkg/util/redact" "github.com/k0sproject/rig/v2/cmd" "github.com/k0sproject/rig/v2/sh/shellescape" log "github.com/sirupsen/logrus" @@ -59,7 +60,11 @@ func adminCredentialFlags(username, password string) []string { // invisibly, since QuoteMeta is the identity function for alphanumerics and // only a credential containing a regex metacharacter exposed it. // -// Empty values are skipped, because an empty match would redact everywhere. +// They are returned longest first. rig replaces each value in turn, so a +// username that is a prefix of the password -- "admin" against +// "admin!s3cr3t" -- would otherwise be substituted first and leave the +// remainder of the password in the log. Empty values are dropped, because +// an empty match would redact everywhere. func adminCredentialRedactions(username, password string) []string { var patterns []string for _, value := range []string{username, password} { @@ -71,7 +76,7 @@ func adminCredentialRedactions(username, password string) []string { patterns = append(patterns, quoted) } } - return patterns + return redact.ByLengthDesc(patterns...) } // Run the installer container. diff --git a/pkg/product/mke/phase/install_mke_test.go b/pkg/product/mke/phase/install_mke_test.go index 8c3c44363..257ebd21a 100644 --- a/pkg/product/mke/phase/install_mke_test.go +++ b/pkg/product/mke/phase/install_mke_test.go @@ -15,7 +15,7 @@ import ( // regular expression, which is what the production code assumed when it // wrapped them in regexp.QuoteMeta -- so both sides agreed with each other // and neither agreed with rig. -func redact(t *testing.T, values []string, rendered string) string { +func applyRedactions(t *testing.T, values []string, rendered string) string { t.Helper() opts := rigcmd.Build(values2options(values)...) @@ -55,7 +55,7 @@ func TestAdminCredentialRedactionsCoverRenderedFlags(t *testing.T) { t.Parallel() rendered := strings.Join(adminCredentialFlags(tc.username, tc.password), " ") - redacted := redact(t, adminCredentialRedactions(tc.username, tc.password), rendered) + redacted := applyRedactions(t, adminCredentialRedactions(tc.username, tc.password), rendered) if tc.username != "" { require.NotContains(t, redacted, tc.username, "username survived redaction of %q", rendered) @@ -85,7 +85,7 @@ func TestAdminCredentialRedactionsMatchQuotedForm(t *testing.T) { require.NotContains(t, rendered, password, "the raw value unexpectedly appears in %q; the regression this guards would not be detectable", rendered) - require.NotContains(t, redact(t, adminCredentialRedactions("admin", password), rendered), "w0rd") + require.NotContains(t, applyRedactions(t, adminCredentialRedactions("admin", password), rendered), "w0rd") } // TestAdminCredentialRedactionsSkipEmptyValues keeps an empty credential from diff --git a/pkg/product/mke/phase/msr_redactions.go b/pkg/product/mke/phase/msr_redactions.go index ca7922b42..845a786ed 100644 --- a/pkg/product/mke/phase/msr_redactions.go +++ b/pkg/product/mke/phase/msr_redactions.go @@ -2,6 +2,8 @@ package phase import ( commonconfig "github.com/Mirantis/launchpad/pkg/product/common/config" + "github.com/Mirantis/launchpad/pkg/util/redact" + "github.com/k0sproject/rig/v2/sh/shellescape" ) // msrCredentialFlags are the MSR bootstrapper flags whose values are @@ -9,44 +11,75 @@ import ( var msrCredentialFlags = []string{"--ucp-username", "--ucp-password"} // msrCredentialRedactions returns the literal strings to keep out of the log -// for an MSR bootstrapper invocation. +// for an MSR bootstrapper invocation, longest first. // -// Both the value as it appears in the flag list and the value with its -// surrounding quotes removed are returned: BuildMKEFlags writes -// --ucp-password="secret", so the text in the command is the quoted form, -// while an operator grepping the log for the configured password looks for -// the raw one. rig matches redactions literally, so each spelling has to be -// listed separately; an empty value is skipped, because an empty match -// would redact the entire output. +// Three spellings of the same credential can reach the log and each has to +// be registered separately, because rig matches literally: +// +// - the rendered form, which is what BuildMKEFlags wrote into the flag +// list and what appears in the command line. BuildMKEFlags shell-quotes +// it, so for a password containing a quote this is not the password. +// - the shell-decoded form, which is the password itself. It reaches the +// log if the bootstrapper echoes it back in its own output. +// - the two-element form, where a flag and its value are separate entries +// in the list. Flags.Join concatenates them into a working command, but +// Flags.Get returns only the flag, so the value has to be read from the +// following element or it is never registered at all. +// +// Ordering matters as much as coverage: rig replaces each value in turn, so +// a username that is a prefix of the password must not be substituted +// first. redact.ByLengthDesc removes that dependence on order. func msrCredentialRedactions(flags commonconfig.Flags) []string { var values []string - for _, flag := range msrCredentialFlags { - quoted := flags.Get(flag) - if quoted == "" { + for _, name := range msrCredentialFlags { + for _, rendered := range renderedFlagValues(flags, name) { + values = append(values, rendered) + + if decoded, err := shellescape.Unquote(rendered); err == nil && decoded != rendered { + values = append(values, decoded) + } + } + } + + return redact.ByLengthDesc(values...) +} + +// renderedFlagValues returns every value the named flag carries in the list, +// covering both "--flag value" or "--flag=value" in one element and a bare +// "--flag" whose value is the next element. +func renderedFlagValues(flags commonconfig.Flags, name string) []string { + var rendered []string + + for i, flag := range flags { + if flag == name { + if i+1 < len(flags) && !isFlagToken(flags[i+1]) { + rendered = append(rendered, flags[i+1]) + } + continue } - if value := commonconfig.FlagValue(quoted); value != "" { - values = append(values, value) + if !isFlagWithValue(flag, name) { + continue } - if idx := indexOfValue(quoted); idx >= 0 && idx < len(quoted)-1 { - values = append(values, quoted[idx+1:]) + if value := flag[len(name)+1:]; value != "" { + rendered = append(rendered, value) } } - return values + return rendered } -// indexOfValue returns the position of the separator between a flag and its -// value, or -1 when the flag carries none. -func indexOfValue(flag string) int { - for i, char := range flag { - if char == '=' || char == ' ' { - return i - } +func isFlagWithValue(flag, name string) bool { + if len(flag) <= len(name) || flag[:len(name)] != name { + return false } - return -1 + return flag[len(name)] == '=' || flag[len(name)] == ' ' +} + +func isFlagToken(value string) bool { + return len(value) > 0 && value[0] == '-' } diff --git a/pkg/product/mke/phase/msr_redactions_test.go b/pkg/product/mke/phase/msr_redactions_test.go new file mode 100644 index 000000000..b302a5e81 --- /dev/null +++ b/pkg/product/mke/phase/msr_redactions_test.go @@ -0,0 +1,65 @@ +package phase + +import ( + "testing" + + commonconfig "github.com/Mirantis/launchpad/pkg/product/common/config" + rigcmd "github.com/k0sproject/rig/v2/cmd" + "github.com/stretchr/testify/require" +) + +// mask applies the values the way rig does, through the real code path. +func mask(values []string, rendered string) string { + opts := make([]rigcmd.ExecOption, 0, len(values)) + for _, value := range values { + opts = append(opts, rigcmd.Redact(value)) + } + + return rigcmd.Build(opts...).RedactString(rendered) +} + +// BuildMKEFlags shell-quotes the credential, so the command line holds the +// quoted spelling while the bootstrapper's own output may echo the raw one. +// Both have to be registered, because rig matches literally. +func TestMSRCredentialRedactionsCoverQuotedAndRawForms(t *testing.T) { + const password = `p@ss'w0rd` + + flags := commonconfig.Flags{`--ucp-username 'admin'`, `--ucp-password 'p@ss'"'"'w0rd'`} + + values := msrCredentialRedactions(flags) + + require.NotContains(t, mask(values, "dtr install "+flags.Join()), "w0rd", + "the rendered command still shows the password") + require.NotContains(t, mask(values, "authentication failed for "+password), "w0rd", + "the raw password still shows where the bootstrapper echoes it") +} + +// Flags.Join concatenates the list, so a flag and its value in separate +// elements form a working command. Flags.Get returns only the flag, so the +// value has to be read from the next element or it is never redacted. +func TestMSRCredentialRedactionsCoverTwoElementForm(t *testing.T) { + flags := commonconfig.Flags{"--ucp-password", "split-secret", "--ucp-node", "host-1"} + + values := msrCredentialRedactions(flags) + + require.NotContains(t, mask(values, "dtr upgrade "+flags.Join()), "split-secret") +} + +// rig replaces each registered value in turn, so a username that is a +// prefix of the password must not be substituted first: doing so destroys +// the longer match and leaves the rest of the password in the log. +func TestMSRCredentialRedactionsOrderLongestFirst(t *testing.T) { + flags := commonconfig.Flags{"--ucp-username admin", "--ucp-password admin!s3cr3t"} + + values := msrCredentialRedactions(flags) + + require.NotContains(t, mask(values, "dtr install "+flags.Join()), "s3cr3t") +} + +// A flag that carries no value registers nothing: an empty redaction would +// match at every position and blank the whole output. +func TestMSRCredentialRedactionsIgnoreValuelessFlags(t *testing.T) { + require.Empty(t, msrCredentialRedactions(commonconfig.Flags{"--ucp-password", "--ucp-node host-1"})) + require.Empty(t, msrCredentialRedactions(commonconfig.Flags{"--ucp-password="})) + require.Empty(t, msrCredentialRedactions(commonconfig.Flags{"--ucp-node host-1"})) +} diff --git a/pkg/util/redact/values.go b/pkg/util/redact/values.go new file mode 100644 index 000000000..a9cc97dc5 --- /dev/null +++ b/pkg/util/redact/values.go @@ -0,0 +1,75 @@ +package redact + +import ( + "fmt" + "regexp" + "sort" + "strings" +) + +// ByLengthDesc orders redaction values longest first and drops empty ones. +// +// rig replaces each registered value in turn with strings.ReplaceAll, so a +// value that is a prefix of another destroys the longer match before it is +// tried: with the username "admin" and the password "admin!s3cr3t" +// registered in that order, the password is rewritten to "[REDACTED]!s3cr3t" +// and the distinctive part of it survives in the log. Registering the +// longest value first removes the dependence on registration order. +// +// An empty value is dropped because it would otherwise match at every +// position; rig skips empty matches too, but a caller should not rely on +// that. +func ByLengthDesc(values ...string) []string { + ordered := make([]string, 0, len(values)) + + for _, value := range values { + if value != "" { + ordered = append(ordered, value) + } + } + + sort.SliceStable(ordered, func(i, j int) bool { + return len(ordered[i]) > len(ordered[j]) + }) + + return ordered +} + +// fallbackPattern matches "" on one line, +// case insensitively, for every key in the sensitive set. It is built from +// the same key set as the structured redaction so the two cannot drift. +var fallbackPattern = buildFallbackPattern() + +func buildFallbackPattern() *regexp.Regexp { + keys := make([]string, 0, len(sensitiveKeys)) + for key := range sensitiveKeys { + keys = append(keys, regexp.QuoteMeta(key)) + } + + sort.Strings(keys) + + // Also catch the environment-variable spellings, which are matched by + // fragment in the structured path and cannot be enumerated here. + fragments := make([]string, 0, len(envSecretFragments)) + for _, fragment := range envSecretFragments { + fragments = append(fragments, `[A-Za-z0-9_]*`+regexp.QuoteMeta(fragment)+`[A-Za-z0-9_]*`) + } + + return regexp.MustCompile(`(?im)^(\s*-?\s*(?:` + strings.Join(keys, "|") + "|" + strings.Join(fragments, "|") + `)\s*[:=]\s*).+$`) +} + +// Text masks credentials in a document that could not be parsed. +// +// This is a best-effort fallback for YAML that fails to load: it is line +// oriented and key driven, so it cannot see a credential that is not on the +// same line as its key, and it masks whatever follows the separator without +// understanding the value. Callers that have a parseable document must use +// YAML, which walks the structure and knows where the credential-bearing +// keys actually are. +// +// It covers the same key set and the same environment-variable fragments as +// the structured path, case insensitively, so a configuration that fails to +// parse does not silently lose coverage the parsed one has. +func Text(doc []byte) []byte { + return fallbackPattern.ReplaceAll(doc, []byte(fmt.Sprintf("${1}%s", Placeholder))) +} From 1d08114be52d7e68d629b3a69b05919de0dfd320 Mon Sep 17 00:00:00 2001 From: James Nesbitt Date: Thu, 12 Nov 2026 13:03:46 +0200 Subject: [PATCH 3/3] Correct the rig fork reference in the redaction semantics test TestRigRedactionIsLiteral's comment said go.mod replaces rig with a fork and that neither property could be assumed from upstream's source. The replace directive is gone (#707) and launchpad builds on upstream v2.2.1. Both properties still hold: the two tests pass unchanged against upstream. That is the point worth recording -- the behaviour the redaction sites depend on is not fork-specific. Written by AI: claude-opus-5 Signed-off-by: James Nesbitt --- pkg/configurer/redaction_semantics_test.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/pkg/configurer/redaction_semantics_test.go b/pkg/configurer/redaction_semantics_test.go index e0ae80f74..23a122675 100644 --- a/pkg/configurer/redaction_semantics_test.go +++ b/pkg/configurer/redaction_semantics_test.go @@ -23,10 +23,12 @@ import ( // - repeated cmd.Redact options compose rather than overwrite, so a call // site may list the raw and the shell-quoted form of the same value. // -// go.mod replaces github.com/k0sproject/rig/v2 with a fork, so neither -// property can be assumed from the upstream module's source: the v1 API -// compiled a regexp. If the fork is bumped and the semantics change, this -// test fails rather than the redaction silently doing nothing. +// Neither property is safe to assume from reading the API: rig's v1 Redact +// compiled a regexp, so the opposite was once true. This branch was written +// against a fork of rig and these tests passed there; they pass unchanged +// against upstream v2.2.1, which launchpad now builds on (#707). If a future +// bump changes the semantics, this fails rather than the redaction silently +// doing nothing. func TestRigRedactionIsLiteral(t *testing.T) { t.Parallel()