From e1225b14061c853547426cd7f3ddddb35537e12f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 04:22:45 -0800 Subject: [PATCH 1/4] log.collect: no artifact is written whose redaction is not proven Credential discovery read the declared log files only while the collection's time budget lasted: a slow run (as under the race detector) skipped the later files, and an earlier file was written with a credential only a skipped one named. The declared log files are now read whole for discovery whatever time is left (each is bounded at 4 MiB, at most 32), after the declared commands and before the status reads. A declared source the budget still cuts (a -unit's commands) makes the bundle hold only its manifest, which says the redaction is not proven and names the cut sources; the command reports it and exits 3. Each log file is discovered once, not twice. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/log_collect.go | 70 ++++++++++++-- .../cmd/sw-block/log_collect_local.go | 8 +- .../cmd/sw-block/log_collect_test.go | 94 +++++++++++++++++++ 3 files changed, 159 insertions(+), 13 deletions(-) diff --git a/seaweed-block/cmd/sw-block/log_collect.go b/seaweed-block/cmd/sw-block/log_collect.go index c71834334f..bfc33e2d3e 100644 --- a/seaweed-block/cmd/sw-block/log_collect.go +++ b/seaweed-block/cmd/sw-block/log_collect.go @@ -34,8 +34,15 @@ type logBundle struct { Since time.Time `json:"since"` Until time.Time `json:"until"` Artifacts []bundleArtifact `json:"artifacts"` + // Redaction is "not_proven" when the collection's time budget ended + // before every declared source (-log-file, -unit, -pid) was read for + // credential discovery; the bundle then holds no artifact but this + // manifest. Skipped names them. + Redaction string `json:"redaction,omitempty"` + Skipped []string `json:"skipped,omitempty"` bytes int redactor *bundleRedactor + ctx context.Context // the collection's time budget } func (b *logBundle) discover(data []byte) { @@ -48,10 +55,32 @@ func (b *logBundle) discover(data []byte) { } b.redactor.discover(data) } + +// add adds a source the bundle collects on its own (the master's and the +// holders' status): one the time budget cut adds no bytes, and none of its +// own reach the bundle. func (b *logBundle) add(name string, data []byte, err error) { + b.addSource(name, data, err, true) +} + +// addDeclared adds a declared source the time budget bounds (a -unit's +// command): one that fails once the budget has ended was cut before its +// credentials could be discovered. +func (b *logBundle) addDeclared(name string, data []byte, err error) { + if err != nil && b.ctx != nil && b.ctx.Err() != nil { + b.Skipped = append(b.Skipped, name) + } + b.addSource(name, data, err, true) +} + +// addSource adds a source; discover says its bytes are still to be +// discovered (a log file's were, whole, as it was read). +func (b *logBundle) addSource(name string, data []byte, err error, discover bool) { // Even a source omitted by the aggregate artifact budget can identify a // credential repeated in a retained artifact. Keep only its bounded secrets. - b.discover(data) + if discover { + b.discover(data) + } if err != nil { b.discover([]byte(err.Error())) } @@ -81,6 +110,16 @@ func (b *logBundle) write(dir string) error { if r.overflow { return errors.New("redaction discovery bound exceeded") } + // A source cut by the time budget may hold a credential repeated in + // another artifact: no artifact is written whose redaction is not proven. + if len(b.Skipped) > 0 { + b.Redaction = "not_proven" + for i := range b.Artifacts { + if a := &b.Artifacts[i]; a.data != nil { + a.data, a.State, a.Error = nil, "withheld", "redaction not proven: the time budget ended before every source was read" + } + } + } outputBytes := 0 for i := range b.Artifacts { a := &b.Artifacts[i] @@ -142,25 +181,38 @@ func (s inspectionShell) collectLogs(args []string, stdout, stderr io.Writer) in b := logBundle{Version: 1, Since: now.Add(-*since), Until: now} ctx, cancel := context.WithTimeout(context.Background(), s.timeout) defer cancel() + b.ctx = ctx if len(files) == 0 && len(units) == 0 { discovered, err := defaultBundleUnits(ctx) units = discovered b.addJSON("unit-discovery.json", map[string]any{"units": discovered}, err) } - for i, p := range files { - if ctx.Err() != nil { - b.add(fmt.Sprintf("file-%03d.log", i+1), nil, ctx.Err()) - continue - } - data, err := readBundleLog(p, b.Since, b.Until, b.discover) - b.add(fmt.Sprintf("file-%03d.log", i+1), data, err) - } + // The declared sources first: the commands the time budget bounds (-unit, + // -pid), then the log files, each read whole for discovery whatever time + // is left (each is bounded at 4 MiB, at most 32 sources), so the budget + // never cuts their discovery. The status reads, not declared, come last. b.collectLocal(ctx, units, pids) + for i, p := range files { + data, err := readBundleLog(p, b.Since, b.Until, b.discover) + b.addSource(fmt.Sprintf("file-%03d.log", i+1), data, err, false) + } b.collectStatus(ctx, s) if err := b.write(dir); err != nil { fmt.Fprintln(stderr, "cannot write bundle") return 1 } + if b.Redaction == "not_proven" { + if *format == "json" { + _ = json.NewEncoder(stdout).Encode(map[string]any{"bundle_written": true, "complete": false, "redaction": "not_proven", "skipped": b.Skipped, "manifest": "manifest.json"}) + } else { + named := b.Skipped + if len(named) > 8 { + named = append(append([]string(nil), named[:8]...), fmt.Sprintf("and %d more", len(b.Skipped)-8)) + } + fmt.Fprintf(stdout, "bundle written; incomplete: redaction not proven (not read in time: %s); only manifest.json was written\n", strings.Join(named, ", ")) + } + return 3 + } complete := true for _, a := range b.Artifacts { if a.State != "collected" { diff --git a/seaweed-block/cmd/sw-block/log_collect_local.go b/seaweed-block/cmd/sw-block/log_collect_local.go index af19929b3a..85678f88d5 100644 --- a/seaweed-block/cmd/sw-block/log_collect_local.go +++ b/seaweed-block/cmd/sw-block/log_collect_local.go @@ -77,17 +77,17 @@ func defaultBundleUnits(ctx context.Context) (bundleStrings, error) { func (b *logBundle) collectLocal(ctx context.Context, units, pids []string) { if len(units) == 0 && len(pids) == 0 { - b.add("startup-flags.json", nil, errors.New("no service unit or local process selected")) + b.addSource("startup-flags.json", nil, errors.New("no service unit or local process selected"), true) } for i, u := range units { flags, err := bundleCommand(ctx, "systemctl", "show", "--property=ExecStart", "--value", "--", u) - b.add(fmt.Sprintf("unit-%03d-flags.txt", i+1), flags, err) + b.addDeclared(fmt.Sprintf("unit-%03d-flags.txt", i+1), flags, err) raw, err := bundleCommand(ctx, "journalctl", "--no-pager", "--utc", "--output=short-iso-precise", "--since="+b.Since.UTC().Format("2006-01-02 15:04:05.000000 UTC"), "--until="+b.Until.UTC().Format("2006-01-02 15:04:05.000000 UTC"), "--unit="+u) b.discover(raw) if err == nil { raw, err = recentBundleLog(raw, b.Since, b.Until) } - b.add(fmt.Sprintf("unit-%03d.log", i+1), raw, err) + b.addDeclared(fmt.Sprintf("unit-%03d.log", i+1), raw, err) } for i, pid := range pids { var raw []byte @@ -116,6 +116,6 @@ func (b *logBundle) collectLocal(ctx context.Context, units, pids []string) { if err != nil { err = errors.New("process startup arguments unavailable") } - b.add(fmt.Sprintf("process-%03d-flags.json", i+1), data, err) + b.addSource(fmt.Sprintf("process-%03d-flags.json", i+1), data, err, true) } } diff --git a/seaweed-block/cmd/sw-block/log_collect_test.go b/seaweed-block/cmd/sw-block/log_collect_test.go index 740fd7b279..62f089fcf6 100644 --- a/seaweed-block/cmd/sw-block/log_collect_test.go +++ b/seaweed-block/cmd/sw-block/log_collect_test.go @@ -531,3 +531,97 @@ func TestLogCollectUsesOneInventoryForChecksAndVolumeArtifacts(t *testing.T) { } } } + +// A time budget spent before the declared log files are read never cuts +// their credential discovery: a credential one file names (a flag) is +// redacted where another file repeats it. +func TestLogCollectSpentBudgetStillDiscoversEveryLogFile(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + const secret = "spent-budget-planted-55120" + opaque := filepath.Join(dir, "opaque.log") + flags := filepath.Join(dir, "flags.log") + if err := os.WriteFile(opaque, []byte(stamp+" opaque "+secret+"\n"), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(flags, []byte(stamp+" --password="+secret+"\n"), 0600); err != nil { + t.Fatal(err) + } + command := fmt.Sprintf("log.collect -out '%s' -log-file '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(opaque), filepath.ToSlash(flags)) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1ns", "-c", command}, &out, &errout) + if code != 3 { + t.Fatalf("exit %d %s %s", code, &out, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")) + if err != nil || !bytes.Contains(raw, []byte("opaque")) { + t.Fatalf("the first log file was not collected: %v %q", err, raw) + } + if n := bundleOccurrences(t, bundle, secret); n != 0 { + t.Fatalf("%d unredacted occurrences of the credential in the bundle", n) + } +} + +// A declared source the time budget cut (a -unit's commands) may hold a +// credential another artifact repeats: the bundle then holds only its +// manifest, says the redaction is not proven, names the cut sources, and +// no byte of the bundle carries the credential. +func TestLogCollectCutDeclaredSourceWithholdsEveryArtifact(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + const secret = "cut-source-planted-77031" + file := filepath.Join(dir, "daemon.log") + if err := os.WriteFile(file, []byte(stamp+" opaque "+secret+"\n"), 0600); err != nil { + t.Fatal(err) + } + command := fmt.Sprintf("log.collect -out '%s' -unit 'sw-blockvolume@v1.service' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file)) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1ns", "-c", command}, &out, &errout) + if code != 3 || !strings.Contains(out.String(), "incomplete: redaction not proven") || !strings.Contains(out.String(), "unit-001.log") { + t.Fatalf("exit %d %q %s", code, &out, &errout) + } + entries, err := os.ReadDir(bundle) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if e.Name() != "manifest.json" { + t.Errorf("artifact %s written although redaction is not proven", e.Name()) + } + } + var m struct { + Redaction string + Skipped []string + } + raw, err := os.ReadFile(filepath.Join(bundle, "manifest.json")) + if err != nil || json.Unmarshal(raw, &m) != nil || m.Redaction != "not_proven" || len(m.Skipped) == 0 { + t.Fatalf("manifest %v %s", err, raw) + } + if n := bundleOccurrences(t, bundle, secret); n != 0 { + t.Fatalf("%d unredacted occurrences of the credential in the bundle", n) + } +} + +// bundleOccurrences counts secret over every byte of every file in the bundle. +func bundleOccurrences(t *testing.T, bundle, secret string) int { + t.Helper() + n := 0 + err := filepath.WalkDir(bundle, func(p string, d os.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + raw, err := os.ReadFile(p) + n += bytes.Count(raw, []byte(secret)) + return err + }) + if err != nil { + t.Fatal(err) + } + return n +} From eefc728c4145d92662b02e4a13f7a27f94359803 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 04:23:40 -0800 Subject: [PATCH 2/4] docs: ledger row for the bundle's unproven-redaction rule Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 450dd45c67..f2e04bfb88 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1043,7 +1043,8 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-CLI-BUNDLE-REDACTION-001` | Recognized credentials are discovered across bounded sources before any artifact is written, and their opaque repeats are masked. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go`; `cmd/sw-block/log_collect.go` `logBundle.write` | `TestLogCollectPlantedSecretsNeverLeaveTheBundle`, `TestLogCollectRecognizedCredentialFormsNeverLeaveTheBundle` | - (pure client sanitization) | ACTIVE | -| `INV-CLI-BUNDLE-DISCOVERY-001` | Credential discovery precedes time filtering and aggregate-budget omission; exhausting the match bound refuses all output. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `discover`, `add`, `readBundleLog`; `cmd/sw-block/log_collect_redact.go` `discoverText` | `TestLogCollectRefusesExhaustedCredentialDiscovery`, `TestLogCollectDiscoversCredentialsBeforeTheTimeWindow`, `TestLogCollectDiscoversCredentialsInSourcesBeyondTheArtifactBudget` | - (bounded discovery) | ACTIVE | +| `INV-CLI-BUNDLE-DISCOVERY-001` | Credential discovery precedes time filtering and aggregate-budget omission; exhausting the match bound refuses all output. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `discover`, `addSource`, `readBundleLog`; `cmd/sw-block/log_collect_redact.go` `discoverText` | `TestLogCollectRefusesExhaustedCredentialDiscovery`, `TestLogCollectDiscoversCredentialsBeforeTheTimeWindow`, `TestLogCollectDiscoversCredentialsInSourcesBeyondTheArtifactBudget` | - (bounded discovery) | ACTIVE | +| `INV-CLI-BUNDLE-UNPROVEN-001` | Declared log files are read whole for discovery whatever time is left; a declared source the time budget cut (a -unit's commands) leaves only the manifest, marked `redaction: not_proven` with the cut sources named, and the command exits 3. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `collectLogs`, `addDeclared`, `logBundle.write` | `TestLogCollectCutDeclaredSourceWithholdsEveryArtifact`, `TestLogCollectSpentBudgetStillDiscoversEveryLogFile`, `TestLogCollectDiscoversCredentialsInSourcesBeyondTheArtifactBudget` | - (pure client sanitization) | ACTIVE | | `INV-CLI-BUNDLE-DIAGNOSTICS-001` | Bare prose does not seed global replacement; ordinary values are excluded so diagnostic words, dates and generations remain readable. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go` `remember`, `discoverText` | `TestLogCollectKeepsOrdinaryWordsAndGenerationsWhileRedactingTokens` | - (pure client sanitization) | ACTIVE | | `INV-CLI-BUNDLE-NUMBERS-001` | Sanitizing structured JSON preserves exact integer evidence, including uint64 counters and positions above 2^53. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go` `bundleDecodeJSON` | `TestLogCollectPreservesExactLargeJSONNumbers` | - (pure client sanitization) | ACTIVE | | `INV-CLI-BUNDLE-LOCAL-RETENTION-001` | Selected local logs are collected before remote observations; an unresponsive master produces an incomplete bundle without discarding those logs. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `collectLogs` | `TestLogCollectKeepsLocalLogsWhenTheMasterDoesNotAnswer` | - (client ordering; no service-availability claim) | ACTIVE | From 241f7981b1e64ed1bcbab215c0920c28305ab8c5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 04:40:32 -0800 Subject: [PATCH 3/4] log.collect: any declared source not read whole makes redaction unproven A declared log file refused before discovery (not a regular file, changed, over 4 MiB, not text, unreadable), a process whose arguments could not be read, and a failed or truncated unit command each make the bundle manifest-only, not only a unit cut by the time budget. A missing file or a gone process holds nothing to discover and stays only unavailable. In an unproven bundle every artifact error is replaced by a fixed one, and the skipped names are printed sanitized. A known credential used as a JSON object key is redacted too. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/log_collect.go | 55 +++++-- .../cmd/sw-block/log_collect_linux_test.go | 38 ++++- .../cmd/sw-block/log_collect_local.go | 11 +- .../cmd/sw-block/log_collect_redact.go | 16 +- .../cmd/sw-block/log_collect_test.go | 140 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 5 +- seaweed-block/docs/design/log-collect.md | 7 + 7 files changed, 250 insertions(+), 22 deletions(-) diff --git a/seaweed-block/cmd/sw-block/log_collect.go b/seaweed-block/cmd/sw-block/log_collect.go index bfc33e2d3e..94f9662034 100644 --- a/seaweed-block/cmd/sw-block/log_collect.go +++ b/seaweed-block/cmd/sw-block/log_collect.go @@ -34,10 +34,11 @@ type logBundle struct { Since time.Time `json:"since"` Until time.Time `json:"until"` Artifacts []bundleArtifact `json:"artifacts"` - // Redaction is "not_proven" when the collection's time budget ended - // before every declared source (-log-file, -unit, -pid) was read for - // credential discovery; the bundle then holds no artifact but this - // manifest. Skipped names them. + // Redaction is "not_proven" when a declared source (-log-file, -unit, + // -pid) was not read whole for credential discovery (cut by the time + // budget, unreadable, over its bound, truncated); the bundle then holds + // no artifact but this manifest, with fixed diagnostics only. Skipped + // names those sources. Redaction string `json:"redaction,omitempty"` Skipped []string `json:"skipped,omitempty"` bytes int @@ -63,16 +64,19 @@ func (b *logBundle) add(name string, data []byte, err error) { b.addSource(name, data, err, true) } -// addDeclared adds a declared source the time budget bounds (a -unit's -// command): one that fails once the budget has ended was cut before its -// credentials could be discovered. +// addDeclared adds a declared source (a -unit's command, a -pid): a failed +// one (cut by the time budget, a failed or truncated command, unreadable +// arguments) was not read whole, so its credentials are not all discovered. func (b *logBundle) addDeclared(name string, data []byte, err error) { - if err != nil && b.ctx != nil && b.ctx.Err() != nil { - b.Skipped = append(b.Skipped, name) + if err != nil { + b.unproven(name) } b.addSource(name, data, err, true) } +// unproven records a declared source whose discovery did not complete. +func (b *logBundle) unproven(name string) { b.Skipped = append(b.Skipped, name) } + // addSource adds a source; discover says its bytes are still to be // discovered (a log file's were, whole, as it was read). func (b *logBundle) addSource(name string, data []byte, err error, discover bool) { @@ -112,12 +116,15 @@ func (b *logBundle) write(dir string) error { } // A source cut by the time budget may hold a credential repeated in // another artifact: no artifact is written whose redaction is not proven. + // Every free-form error goes too: only fixed diagnostics remain. if len(b.Skipped) > 0 { b.Redaction = "not_proven" for i := range b.Artifacts { - if a := &b.Artifacts[i]; a.data != nil { - a.data, a.State, a.Error = nil, "withheld", "redaction not proven: the time budget ended before every source was read" + a := &b.Artifacts[i] + if a.data != nil { + a.State = "withheld" } + a.data, a.Error = nil, "withheld: redaction not proven" } } outputBytes := 0 @@ -193,8 +200,12 @@ func (s inspectionShell) collectLogs(args []string, stdout, stderr io.Writer) in // never cuts their discovery. The status reads, not declared, come last. b.collectLocal(ctx, units, pids) for i, p := range files { - data, err := readBundleLog(p, b.Since, b.Until, b.discover) - b.addSource(fmt.Sprintf("file-%03d.log", i+1), data, err, false) + name, discovered := fmt.Sprintf("file-%03d.log", i+1), false + data, err := readBundleLog(p, b.Since, b.Until, func(raw []byte) { b.discover(raw); discovered = true }) + if !discovered && !errors.Is(err, errBundleLogMissing) { + b.unproven(name) // refused before discovery: not a regular file, changed, over 4 MiB, not text, unreadable + } + b.addSource(name, data, err, false) } b.collectStatus(ctx, s) if err := b.write(dir); err != nil { @@ -202,12 +213,16 @@ func (s inspectionShell) collectLogs(args []string, stdout, stderr io.Writer) in return 1 } if b.Redaction == "not_proven" { + skipped := make([]string, len(b.Skipped)) // printed as sanitized as the manifest + for i, name := range b.Skipped { + skipped[i] = b.redactor.redactText(name) + } if *format == "json" { - _ = json.NewEncoder(stdout).Encode(map[string]any{"bundle_written": true, "complete": false, "redaction": "not_proven", "skipped": b.Skipped, "manifest": "manifest.json"}) + _ = json.NewEncoder(stdout).Encode(map[string]any{"bundle_written": true, "complete": false, "redaction": "not_proven", "skipped": skipped, "manifest": "manifest.json"}) } else { - named := b.Skipped + named := skipped if len(named) > 8 { - named = append(append([]string(nil), named[:8]...), fmt.Sprintf("and %d more", len(b.Skipped)-8)) + named = append(append([]string(nil), named[:8]...), fmt.Sprintf("and %d more", len(skipped)-8)) } fmt.Fprintf(stdout, "bundle written; incomplete: redaction not proven (not read in time: %s); only manifest.json was written\n", strings.Join(named, ", ")) } @@ -231,8 +246,16 @@ func (s inspectionShell) collectLogs(args []string, stdout, stderr io.Writer) in } return 0 } + +// errBundleLogMissing: a declared log file that does not exist holds +// nothing to discover; it is unavailable, not unproven. +var errBundleLogMissing = errors.New("log file is unavailable") + func readBundleLog(path string, since, until time.Time, discover ...func([]byte)) ([]byte, error) { before, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + return nil, errBundleLogMissing + } if err != nil { return nil, errors.New("log file is unavailable") } diff --git a/seaweed-block/cmd/sw-block/log_collect_linux_test.go b/seaweed-block/cmd/sw-block/log_collect_linux_test.go index 220867fbb0..d442835146 100644 --- a/seaweed-block/cmd/sw-block/log_collect_linux_test.go +++ b/seaweed-block/cmd/sw-block/log_collect_linux_test.go @@ -185,8 +185,10 @@ func TestLogCollectJournalDeadlineAndLinkedFileAreUnavailable(t *testing.T) { if code != 3 { t.Fatalf("link certified: exit%d", code) } + // The refused link was never read whole: redaction is not proven, so the + // manifest names it and carries only fixed diagnostics. raw, _ := os.ReadFile(filepath.Join(bundle, "manifest.json")) - if !strings.Contains(string(raw), "regular file") { + if !strings.Contains(string(raw), `"redaction": "not_proven"`) || !strings.Contains(string(raw), `"file-001.log"`) || strings.Contains(string(raw), "do-not-copy") { t.Fatalf("link refusal missing: %s", raw) } if _, err := os.Stat(filepath.Join(bundle, "file-001.log")); !os.IsNotExist(err) { @@ -288,3 +290,37 @@ func TestLogCollectChangedSourceCannotBlockAcquisition(t *testing.T) { default: } } + +// A declared unit whose journal output is truncated at its bound, with the +// collection's time budget still live: the credential named past the bound +// is never discovered, so no artifact repeating it is written. +func TestLogCollectTruncatedUnitWithholdsEveryArtifact(t *testing.T) { + const secret = "truncated-planted-60617" + dir := t.TempDir() + stamp := time.Now().UTC().Format(time.RFC3339Nano) + scripts := map[string]string{ + "systemctl": "#!/bin/sh\nprintf '%s\n' 'ExecStart=/bin/blockvolume --volume-id=v1'\n", + "journalctl": "#!/bin/sh\nhead -c 5000000 /dev/zero | tr '\\0' 'x'\nprintf '\\n%s --password=%s\\n' '" + stamp + "' '" + secret + "'\n", + } + for name, script := range scripts { + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0700); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + file := filepath.Join(dir, "daemon.log") + if err := os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" opaque "+secret+"\n"), 0600); err != nil { + t.Fatal(err) + } + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + bundle := filepath.Join(dir, "bundle") + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", "log.collect -out '" + bundle + "' -unit 'sw-blockvolume@v1.service' -log-file '" + file + "'"}, &out, &errout) + if code != 3 || !strings.Contains(out.String(), "redaction not proven") { + t.Fatalf("exit %d %q %s", code, &out, &errout) + } + if n := bundleOccurrences(t, bundle, secret); n != 0 { + t.Fatalf("%d unredacted occurrences of the credential in the bundle", n) + } +} diff --git a/seaweed-block/cmd/sw-block/log_collect_local.go b/seaweed-block/cmd/sw-block/log_collect_local.go index 85678f88d5..727796ceac 100644 --- a/seaweed-block/cmd/sw-block/log_collect_local.go +++ b/seaweed-block/cmd/sw-block/log_collect_local.go @@ -92,11 +92,13 @@ func (b *logBundle) collectLocal(ctx context.Context, units, pids []string) { for i, pid := range pids { var raw []byte var err error + gone := false // the process does not exist: nothing to discover if runtime.GOOS != "linux" { err = errors.New("process startup arguments require this Linux host") } else { f, e := os.Open("/proc/" + pid + "/cmdline") err = e + gone = errors.Is(e, os.ErrNotExist) if err == nil { raw, err = io.ReadAll(io.LimitReader(f, bundleSourceLimit+1)) f.Close() @@ -113,9 +115,16 @@ func (b *logBundle) collectLocal(ctx context.Context, units, pids []string) { if err == nil { data, err = json.Marshal(strings.Split(strings.TrimRight(string(raw), "\x00"), "\x00")) } + name := fmt.Sprintf("process-%03d-flags.json", i+1) + // A process that is gone, or an empty command line (a kernel thread), + // holds nothing to discover; any other failure left the arguments + // unread (over the bound, unreadable, not this Linux host). + if err != nil && !gone && !(len(raw) == 0 && err.Error() == "process has no startup arguments") { + b.unproven(name) + } if err != nil { err = errors.New("process startup arguments unavailable") } - b.addSource(fmt.Sprintf("process-%03d-flags.json", i+1), data, err, true) + b.addSource(name, data, err, true) } } diff --git a/seaweed-block/cmd/sw-block/log_collect_redact.go b/seaweed-block/cmd/sw-block/log_collect_redact.go index 3ab9807242..e0ff96ec8b 100644 --- a/seaweed-block/cmd/sw-block/log_collect_redact.go +++ b/seaweed-block/cmd/sw-block/log_collect_redact.go @@ -61,13 +61,25 @@ func (r *bundleRedactor) remember(s string) { func (r *bundleRedactor) jsonValue(v any) any { switch x := v.(type) { case map[string]any: + // A key can carry a known credential too: keys are redacted like + // text, and a key that then collides with another gets a suffix. + out := make(map[string]any, len(x)) for k, value := range x { if bundleSensitiveKey(k) { - x[k] = bundleRedacted + value = bundleRedacted } else { - x[k] = r.jsonValue(value) + value = r.jsonValue(value) } + key := r.redactText(k) + for n := 2; ; n++ { + if _, taken := out[key]; !taken { + break + } + key = r.redactText(k) + "#" + strconv.Itoa(n) + } + out[key] = value } + return out case []any: for i, value := range x { if s, ok := value.(string); ok && strings.HasPrefix(s, "-") { diff --git a/seaweed-block/cmd/sw-block/log_collect_test.go b/seaweed-block/cmd/sw-block/log_collect_test.go index 62f089fcf6..577bb842d0 100644 --- a/seaweed-block/cmd/sw-block/log_collect_test.go +++ b/seaweed-block/cmd/sw-block/log_collect_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "github.com/seaweedfs/seaweed-block/core/rpc/control" "google.golang.org/grpc" @@ -12,6 +13,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "runtime" "strings" "sync" "sync/atomic" @@ -625,3 +627,141 @@ func bundleOccurrences(t *testing.T, bundle, secret string) int { } return n } + +// collectUnproven runs log.collect over a small opaque log that repeats +// secret and the given extra arguments, and checks the bundle holds only its +// manifest, marked not proven, and no byte carrying secret. +func collectUnproven(t *testing.T, secret string, extra string) (stdout string) { + t.Helper() + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle") + opaque := filepath.Join(dir, "opaque.log") + if err := os.WriteFile(opaque, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" opaque "+secret+"\n"), 0600); err != nil { + t.Fatal(err) + } + extra = strings.ReplaceAll(extra, "DIR", filepath.ToSlash(dir)) + command := fmt.Sprintf("log.collect -out '%s' -log-file '%s' %s", filepath.ToSlash(bundle), filepath.ToSlash(opaque), extra) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", command}, &out, &errout) + if code != 3 || !strings.Contains(out.String(), "redaction not proven") { + t.Fatalf("exit %d %q %s", code, &out, &errout) + } + entries, err := os.ReadDir(bundle) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if e.Name() != "manifest.json" { + t.Errorf("artifact %s written although redaction is not proven", e.Name()) + } + } + if n := bundleOccurrences(t, bundle, secret); n != 0 { + t.Fatalf("%d unredacted occurrences of the credential in the bundle", n) + } + return out.String() +} + +// A declared log file over its 4 MiB bound is the only source naming a +// credential another file repeats: it is never read whole, so nothing is written. +func TestLogCollectOversizedDeclaredFileWithholdsEveryArtifact(t *testing.T) { + const secret = "oversized-planted-31744" + dir := t.TempDir() + big := filepath.Join(dir, "flags.log") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + if err := os.WriteFile(big, []byte(stamp+" --password="+secret+"\n"+strings.Repeat("x", 5<<20)+"\n"), 0600); err != nil { + t.Fatal(err) + } + collectUnproven(t, secret, fmt.Sprintf("-log-file '%s'", filepath.ToSlash(big))) +} + +// A declared log file that is not text is refused before discovery: its +// discovery did not complete. +func TestLogCollectRefusedDeclaredFileWithholdsEveryArtifact(t *testing.T) { + dir := t.TempDir() + bad := filepath.Join(dir, "binary.log") + if err := os.WriteFile(bad, []byte{0xff, 0xfe, 0x00, '\n'}, 0600); err != nil { + t.Fatal(err) + } + collectUnproven(t, "refused-planted-90215", fmt.Sprintf("-log-file '%s'", filepath.ToSlash(bad))) +} + +// A declared log file that does not exist holds nothing to discover: it is +// unavailable, and the others are still written, redacted. +func TestLogCollectMissingDeclaredFileIsOnlyUnavailable(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle") + file := filepath.Join(dir, "daemon.log") + if err := os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" local diagnostic\n"), 0600); err != nil { + t.Fatal(err) + } + command := fmt.Sprintf("log.collect -out '%s' -log-file '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file), filepath.ToSlash(filepath.Join(dir, "no-such.log"))) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", command}, &out, &errout) + if code != 3 || strings.Contains(out.String(), "redaction not proven") { + t.Fatalf("exit %d %q %s", code, &out, &errout) + } + if raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")); err != nil || !bytes.Contains(raw, []byte("local diagnostic")) { + t.Fatalf("the readable log was not written: %v %q", err, raw) + } +} + +// A declared process whose arguments cannot be read leaves its discovery +// incomplete (off Linux they cannot be read at all); a process that is gone +// holds nothing to discover and is only unavailable. +func TestLogCollectUnreadablePIDWithholdsEveryArtifact(t *testing.T) { + if runtime.GOOS == "linux" { + t.Skip("off Linux a process's arguments cannot be read; on Linux a gone process is only unavailable") + } + collectUnproven(t, "pid-planted-41102", "-pid 1") +} + +// The names printed for skipped sources are sanitized like the manifest: a +// credential equal to a generated name is not printed. +func TestLogCollectSkippedNamesArePrintedSanitized(t *testing.T) { + dir := t.TempDir() + flags := filepath.Join(dir, "flags.log") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + if err := os.WriteFile(flags, []byte(stamp+" --password=file-003.log\n"), 0600); err != nil { + t.Fatal(err) + } + bad := filepath.Join(dir, "binary.log") // refused before discovery: file-003.log is skipped + if err := os.WriteFile(bad, []byte{0xff, 0xfe, 0x00, '\n'}, 0600); err != nil { + t.Fatal(err) + } + out := collectUnproven(t, "label-planted-27719", fmt.Sprintf("-log-file '%s' -log-file '%s'", filepath.ToSlash(flags), filepath.ToSlash(bad))) + if strings.Contains(out, "file-003.log") { + t.Fatalf("a known credential was printed as a skipped name: %q", out) + } +} + +// Unproven redaction replaces every free-form error in the manifest, also +// on entries that hold no data. +func TestLogCollectUnprovenManifestKeepsOnlyFixedErrors(t *testing.T) { + const secret = "error-planted-58810" + b := logBundle{Version: 1} + b.add("cluster.json", nil, errors.New("request failed: "+secret)) + b.unproven("file-001.log") + bundle := filepath.Join(t.TempDir(), "bundle") + if err := b.write(bundle); err != nil { + t.Fatal(err) + } + if n := bundleOccurrences(t, bundle, secret); n != 0 { + t.Fatalf("%d occurrences of a free-form error in the unproven manifest", n) + } +} + +// A known credential used as a JSON object key is redacted too, and the +// output stays valid JSON. +func TestLogCollectRedactsKnownCredentialsInJSONKeys(t *testing.T) { + const secret = "key-planted-77031" + r := &bundleRedactor{secrets: map[string]bool{}} + r.discover([]byte("--password=" + secret)) + out := r.redact([]byte(`{"` + secret + `":"opaque","other":{"` + secret + `":1}}`)) + if bytes.Contains(out, []byte(secret)) || !json.Valid(out) { + t.Fatalf("redacted JSON: %s", out) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index f2e04bfb88..e87b2b563a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1042,9 +1042,10 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-CLI-BUNDLE-REDACTION-001` | Recognized credentials are discovered across bounded sources before any artifact is written, and their opaque repeats are masked. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go`; `cmd/sw-block/log_collect.go` `logBundle.write` | `TestLogCollectPlantedSecretsNeverLeaveTheBundle`, `TestLogCollectRecognizedCredentialFormsNeverLeaveTheBundle` | - (pure client sanitization) | ACTIVE | +| `INV-CLI-BUNDLE-REDACTION-001` | Recognized credentials are discovered across bounded sources before any artifact is written, and their opaque repeats are masked. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go`; `cmd/sw-block/log_collect.go` `logBundle.write` | `TestLogCollectPlantedSecretsNeverLeaveTheBundle`, `TestLogCollectRecognizedCredentialFormsNeverLeaveTheBundle`, `TestLogCollectRedactsKnownCredentialsInJSONKeys` | - (pure client sanitization) | ACTIVE | | `INV-CLI-BUNDLE-DISCOVERY-001` | Credential discovery precedes time filtering and aggregate-budget omission; exhausting the match bound refuses all output. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `discover`, `addSource`, `readBundleLog`; `cmd/sw-block/log_collect_redact.go` `discoverText` | `TestLogCollectRefusesExhaustedCredentialDiscovery`, `TestLogCollectDiscoversCredentialsBeforeTheTimeWindow`, `TestLogCollectDiscoversCredentialsInSourcesBeyondTheArtifactBudget` | - (bounded discovery) | ACTIVE | -| `INV-CLI-BUNDLE-UNPROVEN-001` | Declared log files are read whole for discovery whatever time is left; a declared source the time budget cut (a -unit's commands) leaves only the manifest, marked `redaction: not_proven` with the cut sources named, and the command exits 3. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `collectLogs`, `addDeclared`, `logBundle.write` | `TestLogCollectCutDeclaredSourceWithholdsEveryArtifact`, `TestLogCollectSpentBudgetStillDiscoversEveryLogFile`, `TestLogCollectDiscoversCredentialsInSourcesBeyondTheArtifactBudget` | - (pure client sanitization) | ACTIVE | +| `INV-CLI-BUNDLE-UNPROVEN-001` | A declared source (-log-file, -unit, -pid) whose discovery did not complete (cut by the time budget, refused or over its bound, a failed or truncated command; a missing file or gone process is only unavailable) leaves only the manifest, marked `redaction: not_proven`; the command exits 3. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `collectLogs`, `addDeclared`, `unproven`, `logBundle.write`; `cmd/sw-block/log_collect_local.go` `collectLocal` | `TestLogCollectCutDeclaredSourceWithholdsEveryArtifact`, `TestLogCollectOversizedDeclaredFileWithholdsEveryArtifact`, `TestLogCollectRefusedDeclaredFileWithholdsEveryArtifact`, `TestLogCollectMissingDeclaredFileIsOnlyUnavailable`, `TestLogCollectUnreadablePIDWithholdsEveryArtifact`, `TestLogCollectTruncatedUnitWithholdsEveryArtifact` (Linux) | - (pure client sanitization) | ACTIVE | +| `INV-CLI-BUNDLE-UNPROVEN-002` | In an unproven bundle every artifact error is replaced by a fixed one, and the cut sources are named in the manifest and printed sanitized like it. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `logBundle.write`, `collectLogs` | `TestLogCollectUnprovenManifestKeepsOnlyFixedErrors`, `TestLogCollectSkippedNamesArePrintedSanitized` | - (pure client sanitization) | ACTIVE | | `INV-CLI-BUNDLE-DIAGNOSTICS-001` | Bare prose does not seed global replacement; ordinary values are excluded so diagnostic words, dates and generations remain readable. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go` `remember`, `discoverText` | `TestLogCollectKeepsOrdinaryWordsAndGenerationsWhileRedactingTokens` | - (pure client sanitization) | ACTIVE | | `INV-CLI-BUNDLE-NUMBERS-001` | Sanitizing structured JSON preserves exact integer evidence, including uint64 counters and positions above 2^53. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go` `bundleDecodeJSON` | `TestLogCollectPreservesExactLargeJSONNumbers` | - (pure client sanitization) | ACTIVE | | `INV-CLI-BUNDLE-LOCAL-RETENTION-001` | Selected local logs are collected before remote observations; an unresponsive master produces an incomplete bundle without discarding those logs. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `collectLogs` | `TestLogCollectKeepsLocalLogsWhenTheMasterDoesNotAnswer` | - (client ordering; no service-availability claim) | ACTIVE | diff --git a/seaweed-block/docs/design/log-collect.md b/seaweed-block/docs/design/log-collect.md index 091ce665c8..7a06072372 100644 --- a/seaweed-block/docs/design/log-collect.md +++ b/seaweed-block/docs/design/log-collect.md @@ -87,6 +87,8 @@ Local file acquisition is supported on Linux and Windows; other platforms mark selected files unavailable. Structured JSON keeps exact integer values. The shell timeout bounds status and journal collection; the reused store command's name resolution and reads share the same deadline. No unbounded subprocess output is buffered. +Each `-log-file` is read whole for credential discovery whatever the timeout has left +(each is bounded at 4 MiB, at most 32 sources); a missing file is only unavailable. ## Credential handling @@ -94,6 +96,11 @@ All retained source data stays in bounded memory until credential discovery finishes. Bounded log inputs are scanned before the time filter; credentials in sources omitted by the aggregate artifact budget still teach redaction of their repeats. A discovery scan that exhausts its match bound refuses all output. +**Redaction not proven:** when a declared source (`-log-file`, `-unit`, `-pid`) was not +read whole for discovery (cut by the timeout, over its bound, not text, a link or pipe, +unreadable, a failed or truncated command), the bundle holds only `manifest.json` +(`"redaction": "not_proven"`, the sources named in `skipped`, fixed diagnostics only), +and the command prints `incomplete: redaction not proven` and exits 3. Only sanitized artifacts are written; raw sources are never staged in the bundle. The same boundary sanitizes structured status, startup arguments, logs and manifest errors. Sensitive key/value and flag names include password, token, From c3230efc58b438b363e3ab660eee48ddab28c995 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 04:50:31 -0800 Subject: [PATCH 4/4] log.collect: only a unit command's own failure is unproven; colliding JSON keys withhold A unit journal read whole with no records in the window (or a command the host does not have) is only unavailable; only the command's own failure (cut, nonzero exit, truncated) makes the bundle unproven. Two JSON keys that collide once sanitized are no longer told apart by a suffix, which could itself be a known credential and cost quadratic probes: that artifact is withheld as not proven, checked after its redaction. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/log_collect.go | 24 ++-- .../cmd/sw-block/log_collect_linux_test.go | 75 +++++++++++++ .../cmd/sw-block/log_collect_local.go | 9 +- .../cmd/sw-block/log_collect_redact.go | 22 +++- .../cmd/sw-block/log_collect_test.go | 104 ++++++++++-------- seaweed-block/docs/design/invariants.md | 4 +- 6 files changed, 176 insertions(+), 62 deletions(-) diff --git a/seaweed-block/cmd/sw-block/log_collect.go b/seaweed-block/cmd/sw-block/log_collect.go index 94f9662034..40529436bc 100644 --- a/seaweed-block/cmd/sw-block/log_collect.go +++ b/seaweed-block/cmd/sw-block/log_collect.go @@ -9,6 +9,7 @@ import ( "fmt" "io" "os" + "os/exec" "path/filepath" "strings" "time" @@ -64,11 +65,14 @@ func (b *logBundle) add(name string, data []byte, err error) { b.addSource(name, data, err, true) } -// addDeclared adds a declared source (a -unit's command, a -pid): a failed -// one (cut by the time budget, a failed or truncated command, unreadable -// arguments) was not read whole, so its credentials are not all discovered. -func (b *logBundle) addDeclared(name string, data []byte, err error) { - if err != nil { +// addCommand adds a declared -unit's command output. The command's own +// failure (cut by the time budget, a nonzero exit, output truncated at its +// bound) left it not read whole, so its credentials are not all discovered; +// a command this host does not have read nothing, and is only unavailable. +// err is the artifact's error (the command's, or the time filter's after a +// whole read). +func (b *logBundle) addCommand(name string, data []byte, cmdErr, err error) { + if cmdErr != nil && !errors.Is(cmdErr, exec.ErrNotFound) { b.unproven(name) } b.addSource(name, data, err, true) @@ -133,7 +137,11 @@ func (b *logBundle) write(dir string) error { if a.data == nil { continue } - clean := r.redact(a.data) + clean, proven := r.redactChecked(a.data) + if !proven { + a.data, a.State, a.Error = nil, "withheld", "withheld: redaction not proven" + continue + } if len(clean) > bundleSourceLimit || outputBytes+len(clean) > bundleTotalLimit { a.data = nil a.State = "unavailable" @@ -147,8 +155,8 @@ func (b *logBundle) write(dir string) error { if err != nil { return err } - meta = r.redact(meta) - if len(meta) > bundleSourceLimit { + meta, proven := r.redactChecked(meta) + if !proven || len(meta) > bundleSourceLimit { return errors.New("manifest exceeds collection bound") } if err = os.Mkdir(dir, 0700); err != nil { diff --git a/seaweed-block/cmd/sw-block/log_collect_linux_test.go b/seaweed-block/cmd/sw-block/log_collect_linux_test.go index d442835146..04f49b3aa2 100644 --- a/seaweed-block/cmd/sw-block/log_collect_linux_test.go +++ b/seaweed-block/cmd/sw-block/log_collect_linux_test.go @@ -324,3 +324,78 @@ func TestLogCollectTruncatedUnitWithholdsEveryArtifact(t *testing.T) { t.Fatalf("%d unredacted occurrences of the credential in the bundle", n) } } + +// fakeUnitCommands puts systemctl and journalctl scripts on PATH; journal +// is what journalctl prints. +func fakeUnitCommands(t *testing.T, journal string) { + t.Helper() + dir := t.TempDir() + scripts := map[string]string{ + "systemctl": "#!/bin/sh\nprintf '%s\\n' 'ExecStart=/bin/blockvolume --volume-id=v1'\n", + "journalctl": "#!/bin/sh\nprintf '%s\\n' '" + journal + "'\n", + } + for name, script := range scripts { + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0700); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +// A declared source the time budget cut (a -unit's commands) may hold a +// credential another artifact repeats: the bundle then holds only its +// manifest, says the redaction is not proven, names the cut sources, and +// no byte of the bundle carries the credential. +func TestLogCollectCutDeclaredSourceWithholdsEveryArtifact(t *testing.T) { + fakeUnitCommands(t, "-- No entries --") + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle") + const secret = "cut-source-planted-77031" + file := filepath.Join(dir, "daemon.log") + if err := os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" opaque "+secret+"\n"), 0600); err != nil { + t.Fatal(err) + } + command := fmt.Sprintf("log.collect -out '%s' -unit 'sw-blockvolume@v1.service' -log-file '%s'", bundle, file) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1ns", "-c", command}, &out, &errout) + if code != 3 || !strings.Contains(out.String(), "incomplete: redaction not proven") || !strings.Contains(out.String(), "unit-001.log") { + t.Fatalf("exit %d %q %s", code, &out, &errout) + } + entries, err := os.ReadDir(bundle) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if e.Name() != "manifest.json" { + t.Errorf("artifact %s written although redaction is not proven", e.Name()) + } + } + if n := bundleOccurrences(t, bundle, secret); n != 0 { + t.Fatalf("%d unredacted occurrences of the credential in the bundle", n) + } +} + +// A quiet unit (its journal read whole: no records in the window, exit 0) +// is only unavailable: it does not withhold the bundle. +func TestLogCollectQuietUnitIsOnlyUnavailable(t *testing.T) { + fakeUnitCommands(t, "-- No entries --") + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle") + file := filepath.Join(dir, "daemon.log") + if err := os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" local diagnostic\n"), 0600); err != nil { + t.Fatal(err) + } + command := fmt.Sprintf("log.collect -out '%s' -unit 'sw-blockvolume@v1.service' -log-file '%s'", bundle, file) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", command}, &out, &errout) + if code != 3 || strings.Contains(out.String(), "redaction not proven") { + t.Fatalf("exit %d %q %s", code, &out, &errout) + } + if raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")); err != nil || !bytes.Contains(raw, []byte("local diagnostic")) { + t.Fatalf("a quiet unit withheld the bundle: %v %q", err, raw) + } +} diff --git a/seaweed-block/cmd/sw-block/log_collect_local.go b/seaweed-block/cmd/sw-block/log_collect_local.go index 727796ceac..3db4abfa06 100644 --- a/seaweed-block/cmd/sw-block/log_collect_local.go +++ b/seaweed-block/cmd/sw-block/log_collect_local.go @@ -81,13 +81,16 @@ func (b *logBundle) collectLocal(ctx context.Context, units, pids []string) { } for i, u := range units { flags, err := bundleCommand(ctx, "systemctl", "show", "--property=ExecStart", "--value", "--", u) - b.addDeclared(fmt.Sprintf("unit-%03d-flags.txt", i+1), flags, err) - raw, err := bundleCommand(ctx, "journalctl", "--no-pager", "--utc", "--output=short-iso-precise", "--since="+b.Since.UTC().Format("2006-01-02 15:04:05.000000 UTC"), "--until="+b.Until.UTC().Format("2006-01-02 15:04:05.000000 UTC"), "--unit="+u) + b.addCommand(fmt.Sprintf("unit-%03d-flags.txt", i+1), flags, err, err) + raw, cmdErr := bundleCommand(ctx, "journalctl", "--no-pager", "--utc", "--output=short-iso-precise", "--since="+b.Since.UTC().Format("2006-01-02 15:04:05.000000 UTC"), "--until="+b.Until.UTC().Format("2006-01-02 15:04:05.000000 UTC"), "--unit="+u) b.discover(raw) + err = cmdErr if err == nil { + // The whole output was discovered: a window with no records is + // only unavailable, not unproven. raw, err = recentBundleLog(raw, b.Since, b.Until) } - b.addDeclared(fmt.Sprintf("unit-%03d.log", i+1), raw, err) + b.addCommand(fmt.Sprintf("unit-%03d.log", i+1), raw, cmdErr, err) } for i, pid := range pids { var raw []byte diff --git a/seaweed-block/cmd/sw-block/log_collect_redact.go b/seaweed-block/cmd/sw-block/log_collect_redact.go index e0ff96ec8b..2d77745b62 100644 --- a/seaweed-block/cmd/sw-block/log_collect_redact.go +++ b/seaweed-block/cmd/sw-block/log_collect_redact.go @@ -24,6 +24,9 @@ type bundleRedactor struct { secrets map[string]bool overflow bool replacer *strings.Replacer + // collided: two keys of one JSON object sanitized to the same key in + // the value being redacted; that value's redaction is not proven. + collided bool } func bundleSensitiveKey(k string) bool { @@ -62,7 +65,8 @@ func (r *bundleRedactor) jsonValue(v any) any { switch x := v.(type) { case map[string]any: // A key can carry a known credential too: keys are redacted like - // text, and a key that then collides with another gets a suffix. + // text. Two keys that then collide are not told apart (a suffix + // could itself be a credential): the value is refused. out := make(map[string]any, len(x)) for k, value := range x { if bundleSensitiveKey(k) { @@ -71,11 +75,8 @@ func (r *bundleRedactor) jsonValue(v any) any { value = r.jsonValue(value) } key := r.redactText(k) - for n := 2; ; n++ { - if _, taken := out[key]; !taken { - break - } - key = r.redactText(k) + "#" + strconv.Itoa(n) + if _, taken := out[key]; taken { + r.collided = true } out[key] = value } @@ -227,6 +228,15 @@ func (r *bundleRedactor) rememberValue(v any) { } } } + +// redactChecked is redact, and false when the redaction is not proven (two +// JSON keys collided once sanitized): the caller then writes nothing of it. +func (r *bundleRedactor) redactChecked(raw []byte) ([]byte, bool) { + r.collided = false + clean := r.redact(raw) + return clean, !r.collided +} + func (r *bundleRedactor) redact(raw []byte) []byte { var v any if bundleDecodeJSON(raw, &v) == nil { diff --git a/seaweed-block/cmd/sw-block/log_collect_test.go b/seaweed-block/cmd/sw-block/log_collect_test.go index 577bb842d0..0d143037ee 100644 --- a/seaweed-block/cmd/sw-block/log_collect_test.go +++ b/seaweed-block/cmd/sw-block/log_collect_test.go @@ -567,49 +567,6 @@ func TestLogCollectSpentBudgetStillDiscoversEveryLogFile(t *testing.T) { } } -// A declared source the time budget cut (a -unit's commands) may hold a -// credential another artifact repeats: the bundle then holds only its -// manifest, says the redaction is not proven, names the cut sources, and -// no byte of the bundle carries the credential. -func TestLogCollectCutDeclaredSourceWithholdsEveryArtifact(t *testing.T) { - addr, closeMaster := startInspectionMaster(t) - defer closeMaster() - dir := t.TempDir() - bundle := filepath.Join(dir, "bundle") - stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") - const secret = "cut-source-planted-77031" - file := filepath.Join(dir, "daemon.log") - if err := os.WriteFile(file, []byte(stamp+" opaque "+secret+"\n"), 0600); err != nil { - t.Fatal(err) - } - command := fmt.Sprintf("log.collect -out '%s' -unit 'sw-blockvolume@v1.service' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file)) - var out, errout bytes.Buffer - code := run([]string{"shell", "-master", addr, "-timeout", "1ns", "-c", command}, &out, &errout) - if code != 3 || !strings.Contains(out.String(), "incomplete: redaction not proven") || !strings.Contains(out.String(), "unit-001.log") { - t.Fatalf("exit %d %q %s", code, &out, &errout) - } - entries, err := os.ReadDir(bundle) - if err != nil { - t.Fatal(err) - } - for _, e := range entries { - if e.Name() != "manifest.json" { - t.Errorf("artifact %s written although redaction is not proven", e.Name()) - } - } - var m struct { - Redaction string - Skipped []string - } - raw, err := os.ReadFile(filepath.Join(bundle, "manifest.json")) - if err != nil || json.Unmarshal(raw, &m) != nil || m.Redaction != "not_proven" || len(m.Skipped) == 0 { - t.Fatalf("manifest %v %s", err, raw) - } - if n := bundleOccurrences(t, bundle, secret); n != 0 { - t.Fatalf("%d unredacted occurrences of the credential in the bundle", n) - } -} - // bundleOccurrences counts secret over every byte of every file in the bundle. func bundleOccurrences(t *testing.T, bundle, secret string) int { t.Helper() @@ -765,3 +722,64 @@ func TestLogCollectRedactsKnownCredentialsInJSONKeys(t *testing.T) { t.Fatalf("redacted JSON: %s", out) } } + +// Two JSON keys that collide once sanitized are not told apart by a suffix +// (the suffix could itself be a credential): that artifact is withheld, and +// no byte of the bundle carries any of the known credentials. +func TestLogCollectCollidingJSONKeysAreWithheld(t *testing.T) { + creds := []string{"alphaAAA", "betaBBBB", "#2"} + b := logBundle{Version: 1} + for _, c := range creds { + b.discover([]byte("--password=" + c)) + } + b.add("cluster.json", []byte(`{"alphaAAA":1,"betaBBBB":2,"plain":3}`), nil) + bundle := filepath.Join(t.TempDir(), "bundle") + if err := b.write(bundle); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(bundle, "cluster.json")); !os.IsNotExist(err) { + t.Fatal("an artifact whose keys collided once sanitized was written") + } + for _, c := range creds { + if n := bundleOccurrences(t, bundle, c); n != 0 { + t.Fatalf("%d occurrences of the known credential %q in the bundle", n, c) + } + } +} + +// Many keys that all sanitize to one (65,536 keys of a and b, both known) +// stop at the first collision: bounded work, and the artifact is withheld. +func TestLogCollectManyCollidingJSONKeysStopAtTheFirst(t *testing.T) { + b := logBundle{Version: 1} + b.discover([]byte("--password=a")) + b.discover([]byte("--password=b")) + var obj strings.Builder + obj.WriteByte('{') + for i := 0; i < 1<<16; i++ { + if i > 0 { + obj.WriteByte(',') + } + obj.WriteByte('"') + for bit := 15; bit >= 0; bit-- { + if i>>bit&1 == 1 { + obj.WriteByte('b') + } else { + obj.WriteByte('a') + } + } + obj.WriteString(`":1`) + } + obj.WriteByte('}') + b.add("cluster.json", []byte(obj.String()), nil) + bundle := filepath.Join(t.TempDir(), "bundle") + started := time.Now() + if err := b.write(bundle); err != nil { + t.Fatal(err) + } + if d := time.Since(started); d > 30*time.Second { + t.Fatalf("sanitizing colliding keys took %s", d) + } + if _, err := os.Stat(filepath.Join(bundle, "cluster.json")); !os.IsNotExist(err) { + t.Fatal("an artifact whose keys collided once sanitized was written") + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e87b2b563a..dadfbbb081 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1044,8 +1044,8 @@ Notes: |---|---|---|---|---|---|---| | `INV-CLI-BUNDLE-REDACTION-001` | Recognized credentials are discovered across bounded sources before any artifact is written, and their opaque repeats are masked. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go`; `cmd/sw-block/log_collect.go` `logBundle.write` | `TestLogCollectPlantedSecretsNeverLeaveTheBundle`, `TestLogCollectRecognizedCredentialFormsNeverLeaveTheBundle`, `TestLogCollectRedactsKnownCredentialsInJSONKeys` | - (pure client sanitization) | ACTIVE | | `INV-CLI-BUNDLE-DISCOVERY-001` | Credential discovery precedes time filtering and aggregate-budget omission; exhausting the match bound refuses all output. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `discover`, `addSource`, `readBundleLog`; `cmd/sw-block/log_collect_redact.go` `discoverText` | `TestLogCollectRefusesExhaustedCredentialDiscovery`, `TestLogCollectDiscoversCredentialsBeforeTheTimeWindow`, `TestLogCollectDiscoversCredentialsInSourcesBeyondTheArtifactBudget` | - (bounded discovery) | ACTIVE | -| `INV-CLI-BUNDLE-UNPROVEN-001` | A declared source (-log-file, -unit, -pid) whose discovery did not complete (cut by the time budget, refused or over its bound, a failed or truncated command; a missing file or gone process is only unavailable) leaves only the manifest, marked `redaction: not_proven`; the command exits 3. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `collectLogs`, `addDeclared`, `unproven`, `logBundle.write`; `cmd/sw-block/log_collect_local.go` `collectLocal` | `TestLogCollectCutDeclaredSourceWithholdsEveryArtifact`, `TestLogCollectOversizedDeclaredFileWithholdsEveryArtifact`, `TestLogCollectRefusedDeclaredFileWithholdsEveryArtifact`, `TestLogCollectMissingDeclaredFileIsOnlyUnavailable`, `TestLogCollectUnreadablePIDWithholdsEveryArtifact`, `TestLogCollectTruncatedUnitWithholdsEveryArtifact` (Linux) | - (pure client sanitization) | ACTIVE | -| `INV-CLI-BUNDLE-UNPROVEN-002` | In an unproven bundle every artifact error is replaced by a fixed one, and the cut sources are named in the manifest and printed sanitized like it. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `logBundle.write`, `collectLogs` | `TestLogCollectUnprovenManifestKeepsOnlyFixedErrors`, `TestLogCollectSkippedNamesArePrintedSanitized` | - (pure client sanitization) | ACTIVE | +| `INV-CLI-BUNDLE-UNPROVEN-001` | A declared source (-log-file, -unit, -pid) whose discovery did not complete (cut by the time budget, refused or over its bound, a failed or truncated command; a missing file, process or command, or an empty window, is only unavailable) leaves only the manifest, `redaction: not_proven`; exit 3. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `collectLogs`, `addCommand`, `unproven`, `logBundle.write`; `cmd/sw-block/log_collect_local.go` `collectLocal` | `TestLogCollectCutDeclaredSourceWithholdsEveryArtifact`, `TestLogCollectOversizedDeclaredFileWithholdsEveryArtifact`, `TestLogCollectRefusedDeclaredFileWithholdsEveryArtifact`, `TestLogCollectMissingDeclaredFileIsOnlyUnavailable`, `TestLogCollectUnreadablePIDWithholdsEveryArtifact`, `TestLogCollectTruncatedUnitWithholdsEveryArtifact`, `TestLogCollectQuietUnitIsOnlyUnavailable` (Linux) | - (pure client sanitization) | ACTIVE | +| `INV-CLI-BUNDLE-UNPROVEN-002` | In an unproven bundle every artifact error is replaced by a fixed one, and the cut sources are named in the manifest and printed sanitized like it; a JSON artifact whose keys collide once sanitized is withheld. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `logBundle.write`, `collectLogs` | `TestLogCollectUnprovenManifestKeepsOnlyFixedErrors`, `TestLogCollectSkippedNamesArePrintedSanitized`, `TestLogCollectCollidingJSONKeysAreWithheld` | - (pure client sanitization) | ACTIVE | | `INV-CLI-BUNDLE-DIAGNOSTICS-001` | Bare prose does not seed global replacement; ordinary values are excluded so diagnostic words, dates and generations remain readable. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go` `remember`, `discoverText` | `TestLogCollectKeepsOrdinaryWordsAndGenerationsWhileRedactingTokens` | - (pure client sanitization) | ACTIVE | | `INV-CLI-BUNDLE-NUMBERS-001` | Sanitizing structured JSON preserves exact integer evidence, including uint64 counters and positions above 2^53. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go` `bundleDecodeJSON` | `TestLogCollectPreservesExactLargeJSONNumbers` | - (pure client sanitization) | ACTIVE | | `INV-CLI-BUNDLE-LOCAL-RETENTION-001` | Selected local logs are collected before remote observations; an unresponsive master produces an incomplete bundle without discarding those logs. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `collectLogs` | `TestLogCollectKeepsLocalLogsWhenTheMasterDoesNotAnswer` | - (client ordering; no service-availability claim) | ACTIVE |