Files
seaweedfs/seaweed-block/cmd/sw-block/log_collect_linux_test.go
T
pingqiuandClaude Opus 5.5 c3230efc58 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>
2026-12-01 04:50:31 -08:00

402 lines
16 KiB
Go

//go:build linux
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"golang.org/x/sys/unix"
"google.golang.org/grpc"
)
func TestLogCollectArgumentHelper(t *testing.T) {
if os.Getenv("SWB_LOG_COLLECT_CHILD") == "1" {
time.Sleep(time.Minute)
}
}
func TestLogCollectFindsCredentialsInProcessArgsBeforeWritingLogs(t *testing.T) {
const secret = "process-planted-7a71d6e691"
exe, err := os.Executable()
if err != nil {
t.Fatal(err)
}
child := exec.Command(exe, "-test.run=^TestLogCollectArgumentHelper$", "--", "--api-token", secret)
child.Env = append(os.Environ(), "SWB_LOG_COLLECT_CHILD=1")
if err := child.Start(); err != nil {
t.Fatal(err)
}
defer func() { _ = child.Process.Kill(); _ = child.Wait() }()
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
dir := t.TempDir()
file := filepath.Join(dir, "daemon.log")
bundle := filepath.Join(dir, "bundle")
os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" message "+secret+"\n"), 0600)
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", addr, "-server-id", "host-b", "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s' -pid %d", bundle, file, child.Process.Pid)}, &out, &errout)
if code != 3 {
t.Fatalf("exit%d %s", code, &errout)
}
raw, err := os.ReadFile(filepath.Join(bundle, "process-001-flags.json"))
if err != nil {
t.Fatal(err)
}
var args []string
if json.Unmarshal(raw, &args) != nil || !bytes.Contains(raw, []byte("--api-token")) {
t.Fatalf("invalid process flags: %s", raw)
}
filepath.WalkDir(bundle, func(p string, e os.DirEntry, err error) error {
if err == nil && !e.IsDir() {
b, _ := os.ReadFile(p)
if bytes.Contains(b, []byte(secret)) {
t.Errorf("process credential escaped in %s", e.Name())
}
}
return err
})
}
func TestLogCollectJournalsUseBoundsAndHeadSummaryIsReadOnly(t *testing.T) {
const secret = "unit-planted-2d1bbc76e1"
dir := t.TempDir()
argfile := filepath.Join(dir, "journal-args")
stamp := time.Now().UTC().Format(time.RFC3339Nano)
old := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339Nano)
scripts := map[string]string{
"systemctl": "#!/bin/sh\nprintf '%s\\n' 'ExecStart=/bin/blockvolume --api-token=" + secret + " --volume-id=v1'\n",
"journalctl": "#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$SWB_JOURNAL_ARGS\"\nprintf '%s\\n' '" + old + " old journal record' '" + stamp + " recent journal record " + 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"))
t.Setenv("SWB_JOURNAL_ARGS", argfile)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := grpc.NewServer()
s := inspectionControlServer{}
control.RegisterClusterEvidenceServiceServer(srv, s)
control.RegisterWorkspaceServiceServer(srv, s)
go srv.Serve(ln)
defer srv.Stop()
defer ln.Close()
store := newMemChunkStore()
useMemChunkStore(t, store)
v := cliVolume(t, store, "v1", "daily")
_ = volArgs("volume", v)
_, before, _ := runChunk(cliArgs("show", volArgs("volume", v))...)
holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/status":
fmt.Fprint(w, `{"VolumeID":"v1","ReplicaID":"r2","Epoch":2,"FrontendPrimaryReady":true,"Version":"test-rev"}`)
case "/status/durable":
fmt.Fprintf(w, `{"Volumes":[{"VolumeID":"v1","Impl":"walstore-chunk","Chunk":{"Attached":true,"Stats":{"LastCutNs":%d,"CutsFailed":0,"PendingUnresolved":false},"Maintenance":{"passesOk":1,"inProgress":false,"currentStartNs":0,"lastPass":{"atNs":%d,"planned":0,"removed":0,"plannedChunks":0,"plannedRoots":0,"plannedSegments":0,"removedChunks":0,"removedRoots":0,"removedSegments":0,"error":"","headGen":7,"headGenError":""}}}}]}`, time.Now().UnixNano(), time.Now().UnixNano())
case "/status/nvme":
fmt.Fprint(w, `{"connected":true}`)
default:
http.NotFound(w, r)
}
}))
defer holder.Close()
bundle := filepath.Join(dir, "bundle")
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", ln.Addr().String(), "-filer", "test-filer", "-server-id", "host-b", "-status-addr", holder.URL, "-c", "log.collect -out '" + bundle + "' -unit sw-blockvolume.service -since 1m -o json"}, &out, &errout)
if code != 0 {
m, _ := os.ReadFile(filepath.Join(bundle, "manifest.json"))
t.Fatalf("complete collection exit%d %s %s manifest%s", code, &out, &errout, m)
}
log, err := os.ReadFile(filepath.Join(bundle, "unit-001.log"))
if err != nil {
t.Fatal(err)
}
if !bytes.Contains(log, []byte("recent journal record")) || bytes.Contains(log, []byte("old journal record")) || bytes.Contains(log, []byte(secret)) {
t.Fatalf("journal window or redaction: %s", log)
}
flags, _ := os.ReadFile(filepath.Join(bundle, "unit-001-flags.txt"))
if bytes.Contains(flags, []byte(secret)) || !bytes.Contains(flags, []byte("REDACTED")) {
t.Fatalf("unsafe flags: %s", flags)
}
args, _ := os.ReadFile(argfile)
for _, want := range []string{"--no-pager", "--utc", "--since=", "--until=", "--unit=sw-blockvolume.service"} {
if !bytes.Contains(args, []byte(want)) {
t.Fatalf("journal missing %s: %s", want, args)
}
}
for _, arg := range strings.Split(strings.TrimSpace(string(args)), "\n") {
if strings.HasPrefix(arg, "--since=") || strings.HasPrefix(arg, "--until=") {
if _, err := time.Parse("2006-01-02 15:04:05.000000 UTC", strings.SplitN(arg, "=", 2)[1]); err != nil {
t.Fatalf("journal bound is not systemd UTC form: %q", arg)
}
}
}
_, after, _ := runChunk(cliArgs("show", volArgs("volume", v))...)
if before != after {
t.Fatal("collection changed HEAD")
}
head, err := os.ReadFile(filepath.Join(bundle, "volume-001-head.json"))
if err != nil || !bytes.Contains(head, []byte("daily")) {
t.Fatalf("HEAD summary missing %v: %s", err, head)
}
}
func TestLogCollectJournalDeadlineAndLinkedFileAreUnavailable(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "journalctl")
os.WriteFile(file, []byte("#!/bin/sh\nexec sleep 2\n"), 0700)
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
parent, release := context.WithCancel(context.Background())
defer release()
watchdog := time.AfterFunc(2*time.Second, release)
defer watchdog.Stop()
ctx, cancel := context.WithTimeout(parent, 30*time.Millisecond)
defer cancel()
started := time.Now()
_, err := bundleCommand(ctx, "journalctl", "--no-pager")
if err == nil || time.Since(started) > time.Second {
t.Fatalf("journal was unbounded: %v", err)
}
// The command-level linked-file control must not follow a selected key link.
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
target := filepath.Join(dir, "private-key")
link := filepath.Join(dir, "daemon.log")
os.WriteFile(target, []byte("do-not-copy"), 0600)
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
var out, errout bytes.Buffer
bundle := filepath.Join(dir, "bundle")
code := run([]string{"shell", "-master", addr, "-c", "log.collect -out '" + bundle + "' -log-file '" + link + "'"}, &out, &errout)
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), `"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) {
t.Fatal("linked content copied")
}
}
func TestLogCollectDefaultIncludesEveryTemplateInstanceWithoutAPlainHolder(t *testing.T) {
dir := t.TempDir()
stamp := time.Now().UTC().Format(time.RFC3339Nano)
scripts := map[string]string{
"systemctl": "#!/bin/sh\nif [ \"$1\" = list-units ]; then\n printf '%s\\n' 'sw-blockvolume@first.service loaded active running first' 'sw-blockvolume@second.service loaded inactive dead second'\nelse\n printf '%s\\n' 'ExecStart=/bin/daemon --server-id=host-b'\nfi\n",
"journalctl": "#!/bin/sh\nfor arg in \"$@\"; do\n case \"$arg\" in\n --unit=sw-blockvolume.service) exit 9;;\n --unit=*) printf '%s %s\\n' '" + stamp + "' \"$arg\";;\n esac\ndone\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"))
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
bundle := filepath.Join(dir, "bundle")
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", addr, "-c", "log.collect -out '" + bundle + "'"}, &out, &errout)
if code != 3 {
t.Fatalf("incomplete remote observations result%d %s", code, &errout)
}
var combined bytes.Buffer
for _, name := range []string{"unit-001.log", "unit-002.log", "unit-003.log"} {
raw, err := os.ReadFile(filepath.Join(bundle, name))
if err != nil {
t.Fatalf("missing discovered log%s: %v", name, err)
}
combined.Write(raw)
}
for _, unit := range []string{"sw-blockmaster.service", "sw-blockvolume@first.service", "sw-blockvolume@second.service"} {
if !bytes.Contains(combined.Bytes(), []byte(unit)) {
t.Fatalf("missing default source %s: %s", unit, &combined)
}
}
if bytes.Contains(combined.Bytes(), []byte("--unit=sw-blockvolume.service")) {
t.Fatal("invented a plain holder unit")
}
raw, _ := os.ReadFile(filepath.Join(bundle, "unit-discovery.json"))
if !json.Valid(raw) {
t.Fatalf("missing unit discovery inventory: %s", raw)
}
}
// Model a pathname swapped after the collector's Lstat, before acquisition.
func TestLogCollectChangedSourceCannotBlockAcquisition(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "daemon.log")
if err := os.WriteFile(path, []byte("old regular file"), 0600); err != nil {
t.Fatal(err)
}
before, err := os.Lstat(path)
if err != nil || !before.Mode().IsRegular() {
t.Fatalf("initial source is not regular: %v", err)
}
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
if err := unix.Mkfifo(path, 0600); err != nil {
t.Fatal(err)
}
// This independent release also unblocks the old blocking-open mutant,
// so its failure is observed rather than hanging the package.
released := make(chan struct{})
watchdog := time.AfterFunc(time.Second, func() {
fd, err := unix.Open(path, unix.O_RDWR|unix.O_NONBLOCK, 0)
if err == nil {
unix.Close(fd)
}
close(released)
})
defer watchdog.Stop()
started := time.Now()
f, err := openBundleLog(path)
if err == nil {
info, statErr := f.Stat()
f.Close()
if statErr != nil {
t.Fatal(statErr)
}
// Unlink/create may immediately reuse the same inode on ext4.
// SameFile alone is not a type check: production also checks IsRegular.
if info.Mode().IsRegular() || info.Mode()&os.ModeNamedPipe == 0 {
t.Fatal("replacement descriptor is not the expected non-regular FIFO")
}
}
if time.Since(started) > 500*time.Millisecond {
t.Fatal("changed source needed watchdog to release acquisition")
}
select {
case <-released:
t.Fatal("acquisition reached watchdog")
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)
}
}