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 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-12-01 04:50:37 -08:00
1 parent 4712a47407
commit 7f25b2c451
6 files changed
+176 -62

No files matched your search

+16 -8
View File
@@ -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 {
@@ -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)
}
}
@@ -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
@@ -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 {
+61 -43
View File
@@ -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")
}
}
+2 -2
View File
@@ -1006,8 +1006,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 |