mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Merge pull request #876 from seaweedfs/fix/log-collect-redaction-fail-closed
log.collect: no artifact is written whose redaction is not proven
This commit is contained in:
commit
7ab755df9a
7 files changed
+511
-22
No files matched your search
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -34,8 +35,16 @@ type logBundle struct {
|
||||
Since time.Time `json:"since"`
|
||||
Until time.Time `json:"until"`
|
||||
Artifacts []bundleArtifact `json:"artifacts"`
|
||||
// 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
|
||||
redactor *bundleRedactor
|
||||
ctx context.Context // the collection's time budget
|
||||
}
|
||||
|
||||
func (b *logBundle) discover(data []byte) {
|
||||
@@ -48,10 +57,38 @@ 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)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// 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,13 +118,30 @@ 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.
|
||||
// Every free-form error goes too: only fixed diagnostics remain.
|
||||
if len(b.Skipped) > 0 {
|
||||
b.Redaction = "not_proven"
|
||||
for i := range b.Artifacts {
|
||||
a := &b.Artifacts[i]
|
||||
if a.data != nil {
|
||||
a.State = "withheld"
|
||||
}
|
||||
a.data, a.Error = nil, "withheld: redaction not proven"
|
||||
}
|
||||
}
|
||||
outputBytes := 0
|
||||
for i := range b.Artifacts {
|
||||
a := &b.Artifacts[i]
|
||||
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"
|
||||
@@ -101,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 {
|
||||
@@ -142,25 +196,46 @@ 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 {
|
||||
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 {
|
||||
fmt.Fprintln(stderr, "cannot write bundle")
|
||||
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": skipped, "manifest": "manifest.json"})
|
||||
} else {
|
||||
named := skipped
|
||||
if len(named) > 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, ", "))
|
||||
}
|
||||
return 3
|
||||
}
|
||||
complete := true
|
||||
for _, a := range b.Artifacts {
|
||||
if a.State != "collected" {
|
||||
@@ -179,8 +254,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")
|
||||
}
|
||||
|
||||
@@ -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,112 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -77,26 +77,31 @@ 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)
|
||||
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.add(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
|
||||
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 +118,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.add(fmt.Sprintf("process-%03d-flags.json", i+1), data, err)
|
||||
b.addSource(name, data, err, true)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -61,13 +64,23 @@ 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. 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) {
|
||||
x[k] = bundleRedacted
|
||||
value = bundleRedacted
|
||||
} else {
|
||||
x[k] = r.jsonValue(value)
|
||||
value = r.jsonValue(value)
|
||||
}
|
||||
key := r.redactText(k)
|
||||
if _, taken := out[key]; taken {
|
||||
r.collided = true
|
||||
}
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
case []any:
|
||||
for i, value := range x {
|
||||
if s, ok := value.(string); ok && strings.HasPrefix(s, "-") {
|
||||
@@ -215,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 {
|
||||
|
||||
@@ -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"
|
||||
@@ -531,3 +533,253 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
}
|
||||
@@ -1042,8 +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-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-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, 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 |
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user