diff --git a/seaweed-block/cmd/sw-block/chunk_b.go b/seaweed-block/cmd/sw-block/chunk_b.go index a9448d72c5..32cd74616e 100644 --- a/seaweed-block/cmd/sw-block/chunk_b.go +++ b/seaweed-block/cmd/sw-block/chunk_b.go @@ -96,7 +96,7 @@ func (v volumeFlags) ref(flagName string) (chunkstore.VolumeRef, error) { if v.cmd.master == "" { return chunkstore.VolumeRef{}, errors.New("--master is required (it resolves the volume's layout id)") } - ctx, cancel := context.WithTimeout(context.Background(), v.cmd.timeout) + ctx, cancel := context.WithTimeout(v.cmd.operationContext(), v.cmd.timeout) defer cancel() id, err := resolveVolumeID(ctx, v.cmd.master, v.name) if err != nil { @@ -108,6 +108,7 @@ func (v volumeFlags) ref(flagName string) (chunkstore.VolumeRef, error) { // bCommand parses a catalog command's flags (with --chunk-filer, // --chunk-path and --timeout) and opens the catalog. type bCommand struct { + parent context.Context fs *flag.FlagSet filer, base, master string timeout time.Duration @@ -123,6 +124,15 @@ func newBCommand(name string, timeout time.Duration, stdout, stderr io.Writer) * return c } +// operationContext preserves the standalone commands' background context while +// allowing a composite read-only command to share its caller's deadline. +func (c *bCommand) operationContext() context.Context { + if c.parent != nil { + return c.parent + } + return context.Background() +} + // run parses args, resolves the refs, opens the catalog and calls do. func (c *bCommand) run(args []string, writes bool, refs func() error, do func(context.Context, *chunkstore.BCatalog) (any, error)) int { name := chunkName(c.fs) @@ -140,7 +150,7 @@ func (c *bCommand) run(args []string, writes bool, refs func() error, do func(co return exit } defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), c.timeout) + ctx, cancel := context.WithTimeout(c.operationContext(), c.timeout) defer cancel() v, err := do(ctx, cat) return chunkResult(name, v, err, c.stdout, c.stderr) @@ -210,7 +220,12 @@ func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { // chunkShow prints a volume's VOLUME record and HEAD. func chunkShow(args []string, stdout, stderr io.Writer) int { + return chunkShowContext(context.Background(), args, stdout, stderr) +} + +func chunkShowContext(ctx context.Context, args []string, stdout, stderr io.Writer) int { c := newBCommand("show", 30*time.Second, stdout, stderr) + c.parent = ctx var vol volumeFlags c.bindVolume(&vol, "volume", "volume") var ref chunkstore.VolumeRef diff --git a/seaweed-block/cmd/sw-block/log_collect.go b/seaweed-block/cmd/sw-block/log_collect.go new file mode 100644 index 0000000000..c71834334f --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect.go @@ -0,0 +1,250 @@ +package main + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "time" + "unicode/utf8" +) + +const bundleSourceLimit = 4 << 20 +const bundleTotalLimit = 32 << 20 + +type bundleStrings []string + +func (v *bundleStrings) String() string { return strings.Join(*v, ",") } +func (v *bundleStrings) Set(s string) error { *v = append(*v, s); return nil } + +type bundleArtifact struct { + Name string `json:"name"` + State string `json:"state"` + Error string `json:"error,omitempty"` + data []byte +} +type logBundle struct { + Version int `json:"version"` + Since time.Time `json:"since"` + Until time.Time `json:"until"` + Artifacts []bundleArtifact `json:"artifacts"` + bytes int + redactor *bundleRedactor +} + +func (b *logBundle) discover(data []byte) { + if b.redactor == nil { + b.redactor = &bundleRedactor{secrets: map[string]bool{}} + } + if len(data) > bundleSourceLimit { + b.redactor.overflow = true + return + } + b.redactor.discover(data) +} +func (b *logBundle) add(name string, data []byte, err error) { + // 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 err != nil { + b.discover([]byte(err.Error())) + } + a := bundleArtifact{Name: name, State: "collected", data: data} + if !utf8.Valid(data) { + err = errors.New("source is not UTF-8 text") + a.data = nil + } + if len(data) > bundleSourceLimit || b.bytes+len(data) > bundleTotalLimit { + err = errors.New("collection byte bound exceeded") + a.data = nil + } + if err != nil { + a.State = "unavailable" + a.Error = err.Error() + if len(a.Error) > 2048 { + a.Error = a.Error[:2048] + " (truncated)" + } + } + b.bytes += len(a.data) + b.Artifacts = append(b.Artifacts, a) +} +func (b *logBundle) write(dir string) error { + // All discovery completes in memory. No raw artifact is ever staged on disk. + b.discover(nil) + r := b.redactor + if r.overflow { + return errors.New("redaction discovery bound exceeded") + } + outputBytes := 0 + for i := range b.Artifacts { + a := &b.Artifacts[i] + if a.data == nil { + continue + } + clean := r.redact(a.data) + if len(clean) > bundleSourceLimit || outputBytes+len(clean) > bundleTotalLimit { + a.data = nil + a.State = "unavailable" + a.Error = "sanitized output exceeds collection bound" + continue + } + a.data = clean + outputBytes += len(clean) + } + meta, err := json.MarshalIndent(b, "", " ") + if err != nil { + return err + } + meta = r.redact(meta) + if len(meta) > bundleSourceLimit { + return errors.New("manifest exceeds collection bound") + } + if err = os.Mkdir(dir, 0700); err != nil { + return errors.New("cannot create a new bundle directory") + } + for _, a := range b.Artifacts { + if a.data == nil { + continue + } + if err = os.WriteFile(filepath.Join(dir, a.Name), a.data, 0600); err != nil { + return errors.New("cannot write sanitized bundle artifact") + } + } + return os.WriteFile(filepath.Join(dir, "manifest.json"), meta, 0600) +} +func (s inspectionShell) collectLogs(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("log.collect", flag.ContinueOnError) + // Invalid input can itself contain a secret. Do not echo the parser's text. + fs.SetOutput(io.Discard) + var dir string + var files, units, pids bundleStrings + fs.StringVar(&dir, "out", "", "new bundle directory") + since := fs.Duration("since", 15*time.Minute, "recent log window (at most 24h)") + format := fs.String("o", "text", "text or json result") + fs.Var(&files, "log-file", "local daemon log file; repeatable") + fs.Var(&units, "unit", "local journal service unit; repeatable") + fs.Var(&pids, "pid", "local process whose startup arguments to include; repeatable") + if fs.Parse(args) != nil || fs.NArg() != 0 || dir == "" || *since <= 0 || *since > 24*time.Hour || len(files)+len(units)+len(pids) > 32 || !validBundleLocalSources(units, pids) || (*format != "text" && *format != "json") { + fmt.Fprintln(stderr, "usage: log.collect -out NEW_DIR [-since 15m] [-log-file PATH ...] [-unit UNIT ...] [-pid PID ...]") + return 2 + } + if _, err := os.Lstat(dir); !errors.Is(err, os.ErrNotExist) { + fmt.Fprintln(stderr, "bundle output must not exist") + return 2 + } + now := time.Now().UTC() + b := logBundle{Version: 1, Since: now.Add(-*since), Until: now} + ctx, cancel := context.WithTimeout(context.Background(), s.timeout) + defer cancel() + 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) + } + b.collectLocal(ctx, units, pids) + b.collectStatus(ctx, s) + if err := b.write(dir); err != nil { + fmt.Fprintln(stderr, "cannot write bundle") + return 1 + } + complete := true + for _, a := range b.Artifacts { + if a.State != "collected" { + complete = false + } + } + if *format == "json" { + _ = json.NewEncoder(stdout).Encode(map[string]any{"bundle_written": true, "complete": complete, "manifest": "manifest.json"}) + } else if complete { + fmt.Fprintln(stdout, "bundle written; collection complete (not a health verdict)") + } else { + fmt.Fprintln(stdout, "bundle written; collection incomplete (see manifest.json)") + } + if !complete { + return 3 + } + return 0 +} +func readBundleLog(path string, since, until time.Time, discover ...func([]byte)) ([]byte, error) { + before, err := os.Lstat(path) + if err != nil { + return nil, errors.New("log file is unavailable") + } + if !before.Mode().IsRegular() { + return nil, errors.New("log source must be a regular file, not a link or pipe") + } + f, err := openBundleLog(path) + if err != nil { + return nil, errors.New("cannot open log file") + } + defer f.Close() + after, err := f.Stat() + if err != nil || !after.Mode().IsRegular() || !os.SameFile(before, after) { + return nil, errors.New("log source changed during open") + } + if after.Size() > bundleSourceLimit { + return nil, errors.New("log file exceeds 4 MiB; use a bounded journal time window or rotate the log") + } + raw, err := io.ReadAll(io.LimitReader(f, bundleSourceLimit+1)) + if err != nil || len(raw) > bundleSourceLimit { + return nil, errors.New("log exceeds read bound") + } + if !utf8.Valid(raw) { + return nil, errors.New("log source is not UTF-8 text") + } + for _, observe := range discover { + observe(raw) + } + return recentBundleLog(raw, since, until) +} +func recentBundleLog(raw []byte, since, until time.Time) ([]byte, error) { + var out strings.Builder + active := false + seenStamp := false + scan := bufio.NewScanner(strings.NewReader(string(raw))) + scan.Buffer(make([]byte, 4096), 1<<20) + for scan.Scan() { + line := scan.Text() + fields := strings.Fields(line) + var at time.Time + var err error + if len(fields) >= 2 { + at, err = time.ParseInLocation("2006/01/02 15:04:05.999999", fields[0]+" "+fields[1], time.UTC) + } + if at.IsZero() && len(fields) > 0 { + at, err = time.Parse(time.RFC3339Nano, fields[0]) + if err != nil { + at, err = time.Parse("2006-01-02T15:04:05.999999-0700", fields[0]) + } + } + if !at.IsZero() && err == nil { + seenStamp = true + active = !at.Before(since) && !at.After(until) + } + if active { + out.WriteString(line) + out.WriteByte('\n') + } + } + if scan.Err() != nil { + return nil, errors.New("log record exceeds line bound") + } + if len(raw) > 0 && !seenStamp { + return nil, errors.New("no timestamped records; log window unavailable") + } + return []byte(out.String()), 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 new file mode 100644 index 0000000000..220867fbb0 --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_linux_test.go @@ -0,0 +1,290 @@ +//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) + } + raw, _ := os.ReadFile(filepath.Join(bundle, "manifest.json")) + if !strings.Contains(string(raw), "regular file") { + 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: + } +} diff --git a/seaweed-block/cmd/sw-block/log_collect_local.go b/seaweed-block/cmd/sw-block/log_collect_local.go new file mode 100644 index 0000000000..af19929b3a --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_local.go @@ -0,0 +1,121 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "regexp" + "runtime" + "sort" + "strings" + "time" +) + +var bundleUnitName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.@:-]*$`) +var bundlePID = regexp.MustCompile(`^[1-9][0-9]{0,9}$`) + +func validBundleLocalSources(units, pids []string) bool { + for _, u := range units { + if len(u) > 256 || !bundleUnitName.MatchString(u) { + return false + } + } + for _, p := range pids { + if !bundlePID.MatchString(p) { + return false + } + } + return true +} +func bundleCommand(ctx context.Context, command string, args ...string) ([]byte, error) { + var out bundleBuffer + cmd := exec.CommandContext(ctx, command, args...) + cmd.Stdout = &out + cmd.Stderr = &out + cmd.WaitDelay = time.Second + err := cmd.Run() + return out.Bytes(), err +} + +// Discover running and inactive template instances without reading settings files. +func defaultBundleUnits(ctx context.Context) (bundleStrings, error) { + raw, err := bundleCommand(ctx, "systemctl", "list-units", "sw-blockvolume*.service", "--all", "--plain", "--no-legend", "--no-pager") + found := map[string]bool{} + for _, line := range strings.Split(string(raw), "\n") { + fields := strings.Fields(line) + if len(fields) == 0 { + continue + } + unit := fields[0] + if !strings.HasPrefix(unit, "sw-blockvolume") || !strings.HasSuffix(unit, ".service") { + continue + } + if !validBundleLocalSources([]string{unit}, nil) { + err = errors.New("a holder unit name could not be collected") + continue + } + found[unit] = true + } + holders := make([]string, 0, len(found)) + for unit := range found { + holders = append(holders, unit) + } + sort.Strings(holders) + if len(holders) > 31 { + holders = holders[:31] + err = errors.New("holder unit discovery exceeds collection bound") + } + if len(holders) == 0 { + holders = []string{"sw-blockvolume.service"} + } + return append(bundleStrings{"sw-blockmaster.service"}, holders...), err +} + +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")) + } + 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.discover(raw) + if err == nil { + raw, err = recentBundleLog(raw, b.Since, b.Until) + } + b.add(fmt.Sprintf("unit-%03d.log", i+1), raw, err) + } + for i, pid := range pids { + var raw []byte + var err error + if runtime.GOOS != "linux" { + err = errors.New("process startup arguments require this Linux host") + } else { + f, e := os.Open("/proc/" + pid + "/cmdline") + err = e + if err == nil { + raw, err = io.ReadAll(io.LimitReader(f, bundleSourceLimit+1)) + f.Close() + } + if len(raw) > bundleSourceLimit { + raw = nil + err = errors.New("process arguments exceed collection bound") + } + } + var data []byte + if len(raw) == 0 && err == nil { + err = errors.New("process has no startup arguments") + } + if err == nil { + data, err = json.Marshal(strings.Split(strings.TrimRight(string(raw), "\x00"), "\x00")) + } + if err != nil { + err = errors.New("process startup arguments unavailable") + } + b.add(fmt.Sprintf("process-%03d-flags.json", i+1), data, err) + } +} diff --git a/seaweed-block/cmd/sw-block/log_collect_open_linux.go b/seaweed-block/cmd/sw-block/log_collect_open_linux.go new file mode 100644 index 0000000000..d48c6c9222 --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_open_linux.go @@ -0,0 +1,15 @@ +package main + +import ( + "golang.org/x/sys/unix" + "os" +) + +// A renamed FIFO cannot block acquisition; a substituted link is never followed. +func openBundleLog(path string) (*os.File, error) { + fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0) + if err != nil { + return nil, err + } + return os.NewFile(uintptr(fd), path), nil +} diff --git a/seaweed-block/cmd/sw-block/log_collect_open_other.go b/seaweed-block/cmd/sw-block/log_collect_open_other.go new file mode 100644 index 0000000000..6ca23104fa --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_open_other.go @@ -0,0 +1,12 @@ +//go:build !linux && !windows + +package main + +import ( + "errors" + "os" +) + +func openBundleLog(path string) (*os.File, error) { + return nil, errors.New("safe local log acquisition is unavailable on this platform") +} diff --git a/seaweed-block/cmd/sw-block/log_collect_open_windows.go b/seaweed-block/cmd/sw-block/log_collect_open_windows.go new file mode 100644 index 0000000000..22f59dcbe5 --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_open_windows.go @@ -0,0 +1,33 @@ +package main + +import ( + "errors" + "golang.org/x/sys/windows" + "os" +) + +func openBundleLog(path string) (*os.File, error) { + name, err := windows.UTF16PtrFromString(path) + if err != nil { + return nil, err + } + handle, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) + if err != nil { + return nil, err + } + kind, err := windows.GetFileType(handle) + if err != nil || kind != windows.FILE_TYPE_DISK { + windows.CloseHandle(handle) + return nil, errors.New("not a disk file") + } + var info windows.ByHandleFileInformation + if err := windows.GetFileInformationByHandle(handle, &info); err != nil { + windows.CloseHandle(handle) + return nil, err + } + if info.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 { + windows.CloseHandle(handle) + return nil, errors.New("not a regular file") + } + return os.NewFile(uintptr(handle), path), nil +} diff --git a/seaweed-block/cmd/sw-block/log_collect_redact.go b/seaweed-block/cmd/sw-block/log_collect_redact.go new file mode 100644 index 0000000000..3ab9807242 --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_redact.go @@ -0,0 +1,265 @@ +package main + +import ( + "encoding/json" + "io" + "net/url" + "regexp" + "sort" + "strconv" + "strings" + "time" +) + +const bundleRedacted = "[REDACTED]" + +// The same pass covers log text, structured status, startup arguments and errors. +// Claim IDs are public process identifiers, not authorization credentials. +var bundleSecretValue = regexp.MustCompile(`(?im)((?:--)?[a-z0-9_.-]*(?:password|passwd|token|secret|credential|api[_-]?key|access[_-]?key|private[_-]?key|control[_-]?key|tls[_-]?key|client[_-]?key|signing[_-]?key|jwt[a-z0-9_.-]*|hmac[a-z0-9_.-]*|key)[a-z0-9_.-]*["']?\s*(?:=|:|\s)\s*)(?:"((?:\\.|[^"\\\r\n])*)(?:"|\\?\r?$)|'([^'\r\n]*)(?:'|$)|([^\s,"';}]+))`) +var bundleAuthorization = regexp.MustCompile(`(?i)(\bauthorization["']?\s*[:=]\s*["']?(?:bearer|basic)\s+)([^\s"';,]+)`) +var bundlePrivateKey = regexp.MustCompile(`(?s)-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(?:-----END [A-Z ]*PRIVATE KEY-----|\z)`) +var bundleURLUser = regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9+.-]*://)([^\s/@]+)@`) + +type bundleRedactor struct { + secrets map[string]bool + overflow bool + replacer *strings.Replacer +} + +func bundleSensitiveKey(k string) bool { + k = strings.ToLower(strings.NewReplacer("-", "", "_", "", ".", "").Replace(k)) + for _, part := range []string{"password", "passwd", "token", "secret", "credential", "authorization", "apikey", "accesskey", "privatekey", "controlkey", "tlskey", "clientkey", "signingkey", "jwt", "hmac", "keyfile"} { + if strings.Contains(k, part) { + return true + } + } + return k == "key" +} +func (r *bundleRedactor) remember(s string) { + ordinary := strings.ToLower(s) + switch ordinary { + case "", "true", "false", "yes", "no", "null": + return + } + if s == bundleRedacted { + return + } + if len(s) < 8 && strings.Trim(s, "0123456789") == "" { + return + } + if len(r.secrets) > 4096 { + r.overflow = true + return + } + r.secrets[s] = true + // An escaped appearance of an already identified secret is still a secret. + if b, err := json.Marshal(s); err == nil { + r.secrets[string(b[1:len(b)-1])] = true + } + r.secrets[url.QueryEscape(s)] = true +} +func (r *bundleRedactor) jsonValue(v any) any { + switch x := v.(type) { + case map[string]any: + for k, value := range x { + if bundleSensitiveKey(k) { + x[k] = bundleRedacted + } else { + x[k] = r.jsonValue(value) + } + } + case []any: + for i, value := range x { + if s, ok := value.(string); ok && strings.HasPrefix(s, "-") { + flag, _, equals := strings.Cut(s, "=") + if bundleSensitiveKey(flag) { + if equals { + x[i] = flag + "=" + bundleRedacted + continue + } + if i+1 < len(x) { + if _, ok := x[i+1].(string); ok { + x[i+1] = bundleRedacted + } + } + } + } + x[i] = r.jsonValue(x[i]) + } + case string: + return r.redactText(x) + } + return v +} +func (r *bundleRedactor) discover(raw []byte) { + var v any + if bundleDecodeJSON(raw, &v) == nil { + r.discoverValue(v) + } + r.discoverText(string(raw)) +} +func (r *bundleRedactor) discoverValue(v any) { + switch x := v.(type) { + case map[string]any: + for k, v := range x { + if bundleSensitiveKey(k) { + r.rememberValue(v) + } else { + r.discoverValue(v) + } + } + case []any: + for i, v := range x { + if arg, ok := v.(string); ok && strings.HasPrefix(arg, "-") { + flag, value, equals := strings.Cut(arg, "=") + if bundleSensitiveKey(flag) { + if equals { + r.rememberValue(value) + } else if i+1 < len(x) { + r.rememberValue(x[i+1]) + } + } + } + r.discoverValue(v) + } + case string: + r.discoverText(x) + } +} +func (r *bundleRedactor) discoverText(text string) { + matches := bundleSecretValue.FindAllStringSubmatch(text, 4097) + if len(matches) == 4097 { + r.overflow = true + return + } + for _, m := range matches { + prefix := strings.TrimSpace(m[1]) + // Bare prose is masked in place, but is not a source of global secrets. + if !strings.ContainsAny(prefix, "=:") && !strings.HasPrefix(prefix, "-") { + continue + } + for _, s := range m[2:] { + r.remember(s) + if decoded, e := strconv.Unquote(`"` + s + `"`); e == nil { + r.remember(decoded) + } + } + } + matches = bundleAuthorization.FindAllStringSubmatch(text, 4097) + if len(matches) == 4097 { + r.overflow = true + return + } + for _, m := range matches { + r.remember(m[2]) + } + matches = bundleURLUser.FindAllStringSubmatch(text, 4097) + if len(matches) == 4097 { + r.overflow = true + return + } + for _, m := range matches { + if pair := strings.SplitN(m[2], ":", 2); len(pair) == 2 { + r.remember(m[2]) + r.remember(pair[1]) + if decoded, err := url.PathUnescape(pair[1]); err == nil { + r.remember(decoded) + } + } + } + for _, block := range bundlePrivateKey.FindAllString(text, -1) { + // A PEM embedded in a JSON log carries escaped line separators. + block = strings.NewReplacer(`\r\n`, "\n", `\n`, "\n", `\r`, "\n").Replace(block) + for _, line := range strings.Split(block, "\n") { + line = strings.TrimSpace(line) + if line != "" && !strings.Contains(line, "PRIVATE KEY-----") { + r.remember(line) + fields := strings.Fields(line) + if len(fields) >= 3 { + if _, err := time.Parse("2006/01/02 15:04:05.999999", fields[0]+" "+fields[1]); err == nil { + r.remember(strings.Join(fields[2:], " ")) + } + } + if len(fields) >= 2 { + if _, err := time.Parse(time.RFC3339Nano, fields[0]); err == nil { + r.remember(strings.Join(fields[1:], " ")) + } + } + } + } + } +} +func (r *bundleRedactor) rememberValue(v any) { + switch x := v.(type) { + case string: + r.remember(x) + // Sensitive JSON keys identify the whole value; Authorization also + // identifies the credential independently of its scheme. + fields := strings.Fields(x) + if len(fields) == 2 && (strings.EqualFold(fields[0], "Bearer") || strings.EqualFold(fields[0], "Basic")) { + r.remember(fields[1]) + } + r.discoverText(x) + case []any: + for _, v := range x { + r.rememberValue(v) + } + case map[string]any: + for _, v := range x { + r.rememberValue(v) + } + default: + if v != nil { + raw, _ := json.Marshal(v) + r.remember(string(raw)) + } + } +} +func (r *bundleRedactor) redact(raw []byte) []byte { + var v any + if bundleDecodeJSON(raw, &v) == nil { + if b, err := json.MarshalIndent(r.jsonValue(v), "", " "); err == nil { + return append(b, '\n') + } + } + return []byte(r.redactText(string(raw))) +} +func (r *bundleRedactor) redactText(text string) string { + text = bundlePrivateKey.ReplaceAllString(text, "[REDACTED PRIVATE KEY]") + text = bundleAuthorization.ReplaceAllString(text, "${1}"+bundleRedacted) + text = bundleSecretValue.ReplaceAllString(text, "${1}"+`"`+bundleRedacted+`"`) + text = bundleURLUser.ReplaceAllString(text, "${1}"+bundleRedacted+"@") + if r.replacer == nil { + secrets := make([]string, 0, len(r.secrets)) + for s := range r.secrets { + if s != "" { + secrets = append(secrets, s) + } + } + sort.Slice(secrets, func(i, j int) bool { return len(secrets[i]) > len(secrets[j]) }) + pairs := make([]string, 0, 2*len(secrets)) + for _, secret := range secrets { + pairs = append(pairs, secret, bundleRedacted) + } + r.replacer = strings.NewReplacer(pairs...) + } + text = r.replacer.Replace(text) + return text +} + +// Preserve uint64 counters and positions exactly when sanitizing JSON. +func bundleDecodeJSON(raw []byte, v *any) error { + d := json.NewDecoder(strings.NewReader(string(raw))) + d.UseNumber() + if err := d.Decode(v); err != nil { + return err + } + var trailing any + if err := d.Decode(&trailing); err != io.EOF { + if err != nil { + return err + } + return io.ErrUnexpectedEOF + } + return nil +} diff --git a/seaweed-block/cmd/sw-block/log_collect_status.go b/seaweed-block/cmd/sw-block/log_collect_status.go new file mode 100644 index 0000000000..e97c95b24d --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_status.go @@ -0,0 +1,110 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "time" + + "github.com/seaweedfs/seaweed-block/internal/buildinfo" +) + +// A bounded writer is also used for existing command encoders and subprocesses. +type bundleBuffer struct{ buf bytes.Buffer } + +func (b *bundleBuffer) Len() int { return b.buf.Len() } +func (b *bundleBuffer) Bytes() []byte { return b.buf.Bytes() } +func (b *bundleBuffer) String() string { return b.buf.String() } +func (b *bundleBuffer) WriteString(s string) (int, error) { return b.Write([]byte(s)) } + +func (b *bundleBuffer) Write(p []byte) (int, error) { + left := bundleSourceLimit - b.Len() + if len(p) > left { + n, _ := b.buf.Write(p[:left]) + return n, errors.New("source exceeds collection bound") + } + return b.buf.Write(p) +} +func (b *logBundle) addJSON(name string, v any, err error) { + raw, e := json.Marshal(v) + if err == nil { + err = e + } + b.add(name, raw, err) +} +func (b *logBundle) collectStatus(ctx context.Context, s inspectionShell) { + started := time.Now() + cluster, err := readMasterClusterEvidence(ctx, s.master) + ended := time.Now() + b.addJSON("versions.json", map[string]string{"client": buildinfo.Version("sw-block"), "master": cluster.ProductRevision}, nil) + b.addJSON("cluster.json", cluster, err) + var check, diagnostic bundleBuffer + code := s.checkObservation(ctx, &inspectionObservation{shell: s, cluster: cluster, masterErr: err, started: started, ended: ended}, "json", &check, &diagnostic, 32) + var rows []inspectionResult + checkErr := json.Unmarshal(check.Bytes(), &rows) + if len(cluster.Volumes) > 32 { + checkErr = errors.New("cluster checks limited to the first 32 volumes") + } + if code == 2 { + checkErr = errors.New("cluster checks could not run") + } + for _, r := range rows { + if r.Status == "not checked here" { + checkErr = errors.New("some cluster checks were not checked here") + } + } + b.add("cluster-check.json", check.Bytes(), checkErr) + if err != nil { + return + } + for i, v := range cluster.Volumes { + if i >= 32 { + b.add("remaining-volumes.json", nil, errors.New("volume inventory exceeds collection bound")) + break + } + prefix := fmt.Sprintf("volume-%03d-", i+1) + for _, route := range []struct{ suffix, path string }{{"status", "/status"}, {"durable", "/status/durable"}, {"nvme", "/status/nvme"}} { + var raw json.RawMessage + var e error + if primaryInspectionHost(v) == "" || primaryInspectionHost(v) != s.serverID { + e = fmt.Errorf("not checked here: run on %s", primaryInspectionHost(v)) + } else { + e = s.readHolder(ctx, route.path, v.VolumeID, &raw) + } + b.add(prefix+route.suffix+".json", raw, e) + } + if s.filer == "" { + b.add(prefix+"head.json", nil, errors.New("filer not configured for HEAD summary")) + continue + } + if ctx.Err() != nil { + b.add(prefix+"head.json", nil, ctx.Err()) + continue + } + // Reuse the admitted name resolution and read-only HEAD summary command. + // The same caller context also bounds name resolution and store reads. + remaining := s.timeout + if end, ok := ctx.Deadline(); ok { + remaining = time.Until(end) + } + var out, errout bundleBuffer + code := chunkShowContext(ctx, []string{"--master", s.master, "--chunk-filer", s.filer, "--chunk-path", s.chunkPath, "--volume", v.VolumeID, "--timeout", remaining.String()}, &out, &errout) + var e error + if code != 0 { + e = errors.New("HEAD summary unavailable") + if errout.Len() > 0 { + b.add(prefix+"head-diagnostic.txt", errout.Bytes(), nil) + } + } + if !json.Valid(out.Bytes()) { + b.add(prefix+"head.json", nil, errors.New("HEAD summary did not return JSON")) + } else { + b.add(prefix+"head.json", out.Bytes(), e) + } + } +} + +var _ io.Writer = (*bundleBuffer)(nil) diff --git a/seaweed-block/cmd/sw-block/log_collect_test.go b/seaweed-block/cmd/sw-block/log_collect_test.go new file mode 100644 index 0000000000..740fd7b279 --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_test.go @@ -0,0 +1,533 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestLogCollectPlantedSecretsNeverLeaveTheBundle(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + input := filepath.Join(dir, "daemon.log") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + const token = "planted-token-7c88293bd9" + const private = "planted-private-key-5e700b96" + const auth = "authorization-planted-2b1176e08" + const password = "url-password-planted-1ce197ac" + const signing = "signing-key-planted-37cfe8cb" + log := fmt.Sprintf("%s safe diagnostic claim_id=claim-for-support\n%s api_token=%s\n%s replayed opaque %s\n%s -----BEGIN PRIVATE KEY-----\n%s\n-----END PRIVATE KEY-----\n", stamp, stamp, token, stamp, token, stamp, private) + log += fmt.Sprintf("%s Authorization: Bearer %s\n%s fetch http://support:%s@localhost/metrics\n%s repeated opaque %s\n", stamp, auth, stamp, password, stamp, password) + log += fmt.Sprintf("%s -jwt.signing.key=%s\n%s opaque signing value %s\n", stamp, signing, stamp, signing) + if err := os.WriteFile(input, []byte(log), 0600); err != nil { + t.Fatal(err) + } + outDir := filepath.Join(dir, "bundle") + 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' -since 15m -o json", filepath.ToSlash(outDir), filepath.ToSlash(input))}, &out, &errout) + if code != 0 && code != 3 { + t.Fatalf("collect exit%d: %s %s", code, &out, &errout) + } + var result map[string]any + if json.Unmarshal(out.Bytes(), &result) != nil || result["bundle_written"] != true { + t.Fatalf("invalid collection result: %s", &out) + } + var combined bytes.Buffer + entries := 0 + err := filepath.WalkDir(outDir, func(path string, entry os.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() { + return nil + } + entries++ + b, err := os.ReadFile(path) + if err != nil { + return err + } + combined.Write(b) + return nil + }) + if err != nil || entries < 2 { + t.Fatalf("missing real bundle: entries%d err%v", entries, err) + } + combined.Write(out.Bytes()) + combined.Write(errout.Bytes()) + for _, secret := range []string{token, private, auth, password, signing} { + if bytes.Contains(combined.Bytes(), []byte(secret)) { + t.Fatalf("planted secret left collection: %q", secret) + } + } + for _, safe := range []string{"safe diagnostic", "claim-for-support", "REDACTED"} { + if !strings.Contains(combined.String(), safe) { + t.Fatalf("lost useful evidence %q", safe) + } + } + raw, _ := os.ReadFile(input) + if string(raw) != log { + t.Fatal("collector changed source log") + } +} + +func TestLogCollectIncludesStatusAndReportsUnavailableSources(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + const secret = "status-planted-credential-8b942d" + holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + fmt.Fprintf(w, `{"VolumeID":"v1","ReplicaID":"r2","Epoch":2,"FrontendPrimaryReady":true,"Version":"test-rev","api_token":%q}`, secret) + case "/status/durable": + fmt.Fprintf(w, `{"ProcessID":"test-process","Volumes":[],"claim_id":"support-claim","credentials":{"password":%q}}`, secret) + case "/status/nvme": + fmt.Fprint(w, `{"connected":true}`) + default: + http.NotFound(w, r) + } + })) + defer holder.Close() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" diagnostic\n"), 0600) + bundle := filepath.Join(dir, "bundle") + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-server-id", "host-b", "-status-addr", holder.URL, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 3 { + t.Fatalf("missing filer/start flags must be incomplete: exit%d %s", code, &errout) + } + for _, name := range []string{"versions.json", "cluster.json", "cluster-check.json", "volume-001-status.json", "volume-001-durable.json", "volume-001-nvme.json", "manifest.json"} { + raw, err := os.ReadFile(filepath.Join(bundle, name)) + if err != nil { + t.Fatalf("missing %s: %v", name, err) + } + var value any + if json.Unmarshal(raw, &value) != nil { + t.Fatalf("invalid JSON %s: %s", name, raw) + } + if bytes.Contains(raw, []byte(secret)) { + t.Fatalf("status secret escaped in %s", name) + } + } + raw, _ := os.ReadFile(filepath.Join(bundle, "volume-001-durable.json")) + if !bytes.Contains(raw, []byte("support-claim")) { + t.Fatal("lost claim identifier") + } + var m struct { + Artifacts []struct{ Name, State, Error string } + } + raw, _ = os.ReadFile(filepath.Join(bundle, "manifest.json")) + json.Unmarshal(raw, &m) + found := map[string]bool{} + for _, a := range m.Artifacts { + if a.State == "unavailable" { + found[a.Name] = a.Error != "" + } + } + for _, name := range []string{"volume-001-head.json", "startup-flags.json"} { + if !found[name] { + t.Fatalf("missing explicit incomplete source %s", name) + } + } +} + +func TestLogCollectUsesTheWindowAndRefusesExistingOutput(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + input := filepath.Join(dir, "events.log") + now := time.Now().UTC() + text := now.Add(-time.Hour).Format("2006/01/02 15:04:05.000000") + " old record\nold continuation\n" + now.Format("2006/01/02 15:04:05.000000") + " recent record\nrecent continuation\n" + now.Add(time.Hour).Format(time.RFC3339Nano) + " future record\n" + os.WriteFile(input, []byte(text), 0600) + bundle := filepath.Join(dir, "bundle") + args := []string{"shell", "-master", addr, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s' -since 1m", filepath.ToSlash(bundle), filepath.ToSlash(input))} + var out, errout bytes.Buffer + if code := run(args, &out, &errout); code != 3 { + t.Fatalf("partial bundle exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(raw, []byte("recent record\nrecent continuation")) || bytes.Contains(raw, []byte("old record")) || bytes.Contains(raw, []byte("future record")) { + t.Fatalf("wrong window: %s", raw) + } + before, _ := os.ReadFile(filepath.Join(bundle, "manifest.json")) + if code := run(args, &out, &errout); code != 2 { + t.Fatalf("existing output replaced: exit%d", code) + } + after, _ := os.ReadFile(filepath.Join(bundle, "manifest.json")) + if !bytes.Equal(before, after) { + t.Fatal("existing bundle changed") + } +} + +func TestLogCollectReportsUnreadableAndUnboundedInputs(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + for _, kind := range []string{"missing", "oversized", "unparseable", "binary"} { + t.Run(kind, func(t *testing.T) { + dir := t.TempDir() + input := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + var data []byte + switch kind { + case "oversized": + data = bytes.Repeat([]byte("x"), (4<<20)+1) + case "unparseable": + data = []byte("no timestamp and token=do-not-copy-this\n") + case "binary": + data = []byte{0xff, 0xfe, 0, 1} + } + if kind != "missing" { + if err := os.WriteFile(input, data, 0600); err != nil { + t.Fatal(err) + } + } + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(input))}, &out, &errout) + if code != 3 { + t.Fatalf("source failure became success: exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "manifest.json")) + if err != nil { + t.Fatal(err) + } + var m struct { + Artifacts []struct{ Name, State, Error string } + } + if json.Unmarshal(raw, &m) != nil { + t.Fatal("manifest is not JSON") + } + found := false + for _, a := range m.Artifacts { + if a.Name == "file-001.log" { + found = a.State == "unavailable" && a.Error != "" + } + } + if !found { + t.Fatal("unavailable source disappeared") + } + if _, err := os.Stat(filepath.Join(bundle, "file-001.log")); !os.IsNotExist(err) { + t.Fatal("unsafe source was copied") + } + }) + } +} +func TestLogCollectInvalidArgumentsNeverEchoSecretValues(t *testing.T) { + for _, args := range []string{"-unit 'bad;api_token=planted-value'", "-pid 'password=planted-value'", "-since planted-value", "-unknown planted-value"} { + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", "127.0.0.1:1", "-c", "log.collect -out unused " + args}, &out, &errout) + if code != 2 || strings.Contains(out.String()+errout.String(), "planted-value") { + t.Fatalf("invalid input leaked: exit%d %s %s", code, &out, &errout) + } + } +} + +func TestLogCollectKeepsLocalLogsWhenTheMasterDoesNotAnswer(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + done := make(chan struct{}) + var release sync.Once + releaseFixture := func() { release.Do(func() { close(done); _ = ln.Close() }) } + defer releaseFixture() + watchdog := time.AfterFunc(2*time.Second, releaseFixture) + defer watchdog.Stop() + defer ln.Close() + exited := make(chan struct{}) + defer func() { releaseFixture(); <-exited }() + go func() { + defer close(exited) + c, err := ln.Accept() + if err != nil { + return + } + defer c.Close() + <-done + }() + 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")+" local diagnostic\n"), 0600) + var out, errout bytes.Buffer + started := time.Now() + code := run([]string{"shell", "-master", ln.Addr().String(), "-timeout", "50ms", "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if time.Since(started) > time.Second { + t.Fatal("collection needed the independent fixture watchdog") + } + if code != 3 { + t.Fatalf("stalled master result%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")) + if err != nil || !bytes.Contains(raw, []byte("local diagnostic")) { + t.Fatalf("master failure lost local logs: %v %s", err, raw) + } +} + +func TestLogCollectKeepsOrdinaryWordsAndGenerationsWhileRedactingTokens(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + const secret = "7e0adc2391fa44d09d6f0a77b8c2f196" + text := fmt.Sprintf("%s lease token is stale for volume v1 / deletion tokens=2 gen=12->13 / this is fine\n%s token=%s\n%s opaque %s\n", stamp, stamp, secret, stamp, secret) + text += stamp + " lease token unavailable / status remains unavailable\n" + os.WriteFile(file, []byte(text), 0600) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")) + if err != nil { + t.Fatal(err) + } + for _, safe := range []string{stamp, "this is fine", "gen=12->13", "status remains unavailable"} { + if !bytes.Contains(raw, []byte(safe)) { + t.Fatalf("ordinary evidence %q destroyed: %s", safe, raw) + } + } + if bytes.Contains(raw, []byte(secret)) { + t.Fatalf("planted token escaped: %s", raw) + } +} + +// Each case teaches the collector exactly one credential, without another +// format accidentally supplying its value to discovery. +func TestLogCollectRecognizedCredentialFormsNeverLeaveTheBundle(t *testing.T) { + cases := []struct{ name, record, status, secret string }{ + {"short flag", `--password pw6abc`, "", "pw6abc"}, + {"embedded authorization", `{"Authorization":"Bearer embed-auth-376123"}`, "", "embed-auth-376123"}, + {"structured authorization", "diagnostic", `{"Authorization":"Basic structured-auth-82791"}`, "structured-auth-82791"}, + {"equals argv", "diagnostic", `["daemon","--password=multi word credential-82731"]`, "multi word credential-82731"}, + {"incomplete quoted", `password="incomplete credential-93812`, "", "incomplete credential-93812"}, + {"incomplete escape", `password="incomplete escaped-371982\`, "", "incomplete escaped-371982"}, + {"escaped pem", `{"message":"-----BEGIN PRIVATE KEY-----\nbody-planted-894123\n-----END PRIVATE KEY-----"}`, "", "body-planted-894123"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if tc.status != "" { + fmt.Fprint(w, tc.status) + } else { + fmt.Fprint(w, `{}`) + } + })) + defer holder.Close() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + text := stamp + " " + tc.record + "\n" + stamp + " opaque repeat " + tc.secret + "\n" + if err := os.WriteFile(file, []byte(text), 0600); err != nil { + t.Fatal(err) + } + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-server-id", "host-b", "-status-addr", holder.URL, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + count := 0 + err := filepath.WalkDir(bundle, func(p string, e os.DirEntry, err error) error { + if err != nil { + return err + } + if e.IsDir() { + return nil + } + count++ + raw, err := os.ReadFile(p) + if err != nil { + return err + } + if bytes.Contains(raw, []byte(tc.secret)) { + t.Errorf("credential survived in %s", e.Name()) + } + return nil + }) + if err != nil || count < 2 { + t.Fatalf("missing bundle: %d %v", count, err) + } + if strings.Contains(out.String()+errout.String(), tc.secret) { + t.Fatal("credential escaped command output") + } + }) + } +} + +func TestLogCollectPreservesExactLargeJSONNumbers(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"generation":18446744073709551615,"position":9007199254740993,"token":"number-test-credential"}`) + })) + defer holder.Close() + 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")+" safe\n"), 0600) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-server-id", "host-b", "-status-addr", holder.URL, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "volume-001-status.json")) + if err != nil { + t.Fatal(err) + } + var got struct { + Generation uint64 + Position uint64 + Token string + } + if err := json.Unmarshal(raw, &got); err != nil { + t.Fatal(err) + } + if got.Generation != 18446744073709551615 || got.Position != 9007199254740993 || got.Token != "[REDACTED]" { + t.Fatalf("changed numeric evidence: %s", raw) + } +} + +func TestLogCollectRefusesExhaustedCredentialDiscovery(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + text := strings.Repeat(stamp+" token=repeat\n", 4097) + stamp + " token=last-planted-73821\n" + stamp + " opaque last-planted-73821\n" + os.WriteFile(file, []byte(text), 0600) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 1 { + t.Fatalf("incomplete credential discovery wrote a bundle: exit%d", code) + } + if _, err := os.Stat(bundle); !os.IsNotExist(err) { + t.Fatal("discovery overflow wrote output") + } +} + +func TestLogCollectDiscoversCredentialsBeforeTheTimeWindow(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + now := time.Now().UTC() + stamp := now.Format("2006/01/02 15:04:05.000000") + old := now.Add(-time.Hour).Format("2006/01/02 15:04:05.000000") + const secret = "window-body-923817" + text := old + " -----BEGIN PRIVATE KEY-----\n" + stamp + " " + secret + "\n" + stamp + " -----END PRIVATE KEY-----\n" + stamp + " opaque " + secret + "\n" + old + " old diagnostic\n" + os.WriteFile(file, []byte(text), 0600) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s' -since 1m", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(raw, []byte(secret)) || bytes.Contains(raw, []byte("old diagnostic")) { + t.Fatal("window leaked key body or retained an old record") + } +} + +func TestLogCollectDiscoversCredentialsInSourcesBeyondTheArtifactBudget(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 = "budget-planted-381927" + line := stamp + " " + strings.Repeat(" ", 65500) + "\n" + text := stamp + " opaque " + secret + "\n" + strings.Repeat(line, 63) + text += strings.Repeat(" ", (4<<20)-len(text)-1) + "\n" + command := fmt.Sprintf("log.collect -out '%s'", filepath.ToSlash(bundle)) + for i := 0; i < 8; i++ { + file := filepath.Join(dir, fmt.Sprintf("log%d", i)) + if err := os.WriteFile(file, []byte(text), 0600); err != nil { + t.Fatal(err) + } + command += fmt.Sprintf(" -log-file '%s'", filepath.ToSlash(file)) + } + file := filepath.Join(dir, "flags.log") + os.WriteFile(file, []byte(stamp+" --password="+secret+"\n"), 0600) + command += fmt.Sprintf(" -log-file '%s'", filepath.ToSlash(file)) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", command}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(raw, []byte(secret)) { + t.Fatal("discarding later source lost credential discovery") + } + if _, err := os.Stat(filepath.Join(bundle, "file-009.log")); !os.IsNotExist(err) { + t.Fatal("artifact byte limit was not preserved") + } +} + +type logCollectCountedInventory struct { + inspectionControlServer + reads atomic.Int32 +} + +func (s *logCollectCountedInventory) GetClusterStatus(ctx context.Context, q *control.GetClusterStatusRequest) (*control.ClusterStatusResponse, error) { + s.reads.Add(1) + return s.inspectionControlServer.GetClusterStatus(ctx, q) +} +func TestLogCollectUsesOneInventoryForChecksAndVolumeArtifacts(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + counted := &logCollectCountedInventory{} + control.RegisterClusterEvidenceServiceServer(server, counted) + control.RegisterWorkspaceServiceServer(server, counted) + go server.Serve(ln) + defer server.Stop() + defer ln.Close() + 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")+" safe\n"), 0600) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", ln.Addr().String(), "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + if counted.reads.Load() != 1 { + t.Fatalf("bundle used %d inventories", counted.reads.Load()) + } + for _, name := range []string{"cluster.json", "cluster-check.json"} { + raw, err := os.ReadFile(filepath.Join(bundle, name)) + if err != nil || !json.Valid(raw) { + t.Fatalf("missing inventory/check artifact %s: %v", name, err) + } + } +} diff --git a/seaweed-block/cmd/sw-block/shell.go b/seaweed-block/cmd/sw-block/shell.go index b6304e6b49..0ebd29a309 100644 --- a/seaweed-block/cmd/sw-block/shell.go +++ b/seaweed-block/cmd/sw-block/shell.go @@ -137,8 +137,11 @@ func (s inspectionShell) execute(line string, stdout, stderr io.Writer) int { return 0 } name, args := words[0], words[1:] + if name == "log.collect" { + return s.collectLogs(args, stdout, stderr) + } if name == "help" { - fmt.Fprintln(stdout, "cluster.status, cluster.check [volume], volume.list, volume.status , volume.explain , snapshot.list , store.show , store.usage , volume.verify ; each supports -o json; quit") + fmt.Fprintln(stdout, "cluster.status, cluster.check [volume], volume.list, volume.status , volume.explain , snapshot.list , store.show , store.usage , volume.verify , log.collect -out DIR; each supports -o json; quit") return 0 } format := "text" diff --git a/seaweed-block/cmd/sw-block/shell_check.go b/seaweed-block/cmd/sw-block/shell_check.go index 854cf9be8a..b3a573588a 100644 --- a/seaweed-block/cmd/sw-block/shell_check.go +++ b/seaweed-block/cmd/sw-block/shell_check.go @@ -103,9 +103,18 @@ type inspectionObservation struct { func (s inspectionShell) check(volume, format string, stdout, stderr io.Writer) int { ctx, cancel := context.WithTimeout(context.Background(), s.timeout) defer cancel() + return s.checkContext(ctx, volume, format, stdout, stderr) +} + +func (s inspectionShell) checkContext(ctx context.Context, volume, format string, stdout, stderr io.Writer, volumeLimits ...int) int { o := &inspectionObservation{shell: s, requested: volume, started: time.Now()} o.cluster, o.masterErr = readMasterClusterEvidence(ctx, s.master) o.ended = time.Now() + return s.checkObservation(ctx, o, format, stdout, stderr, volumeLimits...) +} + +func (s inspectionShell) checkObservation(ctx context.Context, o *inspectionObservation, format string, stdout, stderr io.Writer, volumeLimits ...int) int { + volume := o.requested if o.masterErr == nil { conn, err := link.DialMasterFromEnv(s.master) o.lifecycleErr = err @@ -118,7 +127,11 @@ func (s inspectionShell) check(volume, format string, stdout, stderr io.Writer) err = nil } o.lifecycleErr = err - for _, v := range o.cluster.Volumes { + volumes := o.cluster.Volumes + if len(volumeLimits) > 0 && volumeLimits[0] > 0 && len(volumes) > volumeLimits[0] { + volumes = volumes[:volumeLimits[0]] + } + for _, v := range volumes { if volume != "" && v.VolumeID != volume { continue } diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 0d0e2f1652..9ea1486c23 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -58,7 +58,7 @@ var headReaders = map[string]string{ "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", // above the chunk store: they read through the layout remote's GetHead, so an // absent HEAD reaches them as ErrHeadAbsent, never as a zero HEAD (probe LayoutRemote) - "cmd/sw-block/chunk_b.go chunkShow -> ReadHead": "found=false: prints a null head (probe TestOpsChunk_AbsentVolume)", + "cmd/sw-block/chunk_b.go chunkShowContext -> ReadHead": "found=false: prints a null head, including via the chunkShow wrapper (probe TestOpsChunk_AbsentVolume)", "cmd/sw-block/chunk_b.go chunkSnapshots -> ReadHead": "refuses volume_not_found (probe TestOpsChunk_AbsentVolume)", "core/frontend/durable/provider_chunk.go GetHead -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", "core/frontend/durable/provider_chunk.go GetHeadRoot -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", diff --git a/seaweed-block/docs/design/inspection-shell.md b/seaweed-block/docs/design/inspection-shell.md index 9041acf608..82c6a97687 100644 --- a/seaweed-block/docs/design/inspection-shell.md +++ b/seaweed-block/docs/design/inspection-shell.md @@ -14,7 +14,8 @@ sw-block shell -master 127.0.0.1:9000 -filer 127.0.0.1:18888 -server-id host1 -s The inspection commands are `cluster.status`, `cluster.check [volume]`, `volume.list`, `volume.status `, `volume.explain `, `snapshot.list `, `store.show `, `store.usage ` and -`volume.verify `. `-o json` selects JSON. Store commands reuse the +`volume.verify `. `log.collect -out DIR` creates a local support bundle; +see [Log collection](log-collect.md). `-o json` selects JSON. Store commands reuse the existing chunk commands' JSON bodies in either output mode. Mutations are not inspection commands; use the existing admitted `ops` paths. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 801f8690d7..eabcb05952 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -963,6 +963,20 @@ Notes: - `INV-WS-FREEZE-ACCOUNTING-001` details retained: A frozen detach validates a positive, non-future origin before admission, converts it once to a local monotonic origin, and subtracts elapsed time from the five-second freeze budget at forecast and barrier. Only explicit final override may exceed the forecast budget, and its report records that override and actual elapsed time. New F2 wire fields are durations, not a changed clock-origin request. Existing Unix-nanosecond origin validation/conversion remains; new advice is same-host only. Estimate growth and request delay may cause a bounded refusal, not a promise every advised cycle admits. No new margin. + +### B.5a Support-bundle collection (read-only client observations) + +| 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`; `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-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 | +| `INV-CLI-BUNDLE-DEFAULT-UNITS-001` | Default unit discovery includes template holder instances even when no plain holder unit exists; discovery or collection failures remain explicit unavailable sources. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_local.go` `defaultBundleUnits` | `TestLogCollectDefaultIncludesEveryTemplateInstanceWithoutAPlainHolder` (`cmd/sw-block/log_collect_linux_test.go`; Linux qualification required) | - (local service discovery) | ACTIVE | +| `INV-CLI-BUNDLE-INVENTORY-001` | Bundle checks and per-volume artifacts use one observed inventory; a second read cannot hide truncation. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_status.go` `collectStatus`; `inspectionShell.checkObservation` | `TestLogCollectUsesOneInventoryForChecksAndVolumeArtifacts` | - (client observation reuse) | ACTIVE | +| `INV-CLI-BUNDLE-SOURCE-ACQUISITION-001` | Linux local-log acquisition is nonblocking if a regular path is replaced by a FIFO after inspection. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_open_linux.go` `openBundleLog` | `TestLogCollectChangedSourceCannotBlockAcquisition` (`cmd/sw-block/log_collect_linux_test.go`; Linux qualification required) | - (local acquisition boundary only; does not prove the caller's post-open validation) | ACTIVE | + ### B.6 Workspace: chunk lifecycle, GC and delete | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | diff --git a/seaweed-block/docs/design/log-collect.md b/seaweed-block/docs/design/log-collect.md new file mode 100644 index 0000000000..091ce665c8 --- /dev/null +++ b/seaweed-block/docs/design/log-collect.md @@ -0,0 +1,117 @@ +# Collect a support bundle + +`log.collect` collects read-only diagnostics in a new directory. Run it on the +volume host: the holder status pages, process arguments and daemon logs are local. +It starts no service and writes no volume, HEAD, snapshot or configuration. + +For systemd: + +```sh +sw-block shell -master 127.0.0.1:9000 -filer 127.0.0.1:18888 \ + -server-id host-a -status-addr 127.0.0.1:9090 -timeout 30s \ + -c 'log.collect -out ./support -since 15m -unit sw-blockmaster.service -unit sw-blockvolume.service' +``` + +For `sw-block mini` or another foreground deployment, select the daemon log +files and the running process IDs. Each `-pid` reads only that Linux process's +startup arguments, never its environment or the files named by its arguments. +The following uses mini's default ports; replace the sample PIDs with its printed +blockmaster and blockvolume PIDs: + +```sh +sw-block shell -master 127.0.0.1:9180 -filer 127.0.0.1:18888 \ + -server-id s1 -status-addr 127.0.0.1:9203 \ + -c 'log.collect -out ./support -since 15m -log-file ./swb-mini/blockmaster.log -log-file ./swb-mini/blockvolume.log -pid 1234 -pid 1235 -o json' +``` + +The output directory must not exist, and its parent must exist. No existing +bundle is overwritten. Directory and file modes are 0700 and 0600 on Unix. +The command's `-o json` result reports whether the directory was written and +whether collection was complete; it does not print raw diagnostic errors. + +## Contents and missing observations + +`manifest.json` names each artifact and marks it `collected` or `unavailable`, +with a reason for unavailable or bounded-out data. Filenames are generated +ordinals, never copied source paths, volume names or unit names. + +| Artifact | Observation | +|---|---| +| `versions.json` | Client build and master's reported revision | +| `cluster.json` | Existing master evidence, including host and volume identity | +| `cluster-check.json` | The same typed checks as `cluster.check` | +| `volume-NNN-status.json`, `-durable.json`, `-nvme.json` | Local holder status pages | +| `volume-NNN-head.json` | Existing read-only `store.show` HEAD and VOLUME summary | +| `unit-NNN-flags.txt`, `process-NNN-flags.json` | Unit ExecStart or Linux process startup arguments | +| `unit-NNN.log`, `file-NNN.log` | Selected daemon logs in the requested time window | + +The filer is required for HEAD summaries. The local server ID must match the +master's primary host before a status page is read. Off-host status is marked +unavailable with the host to use; no unauthenticated external listener is enabled. +These are separate observations, not an atomic snapshot. + +With no `-log-file` or `-unit`, collection selects `sw-blockmaster.service` and +discovers the host's loaded holder units with `systemctl list-units --all`, +including active and inactive `sw-blockvolume@.service` instances from +`volume start`, and any plain or ublk holder unit. Discovery is recorded in +`unit-discovery.json`. Only when none are found does it try the legacy plain +`sw-blockvolume.service`; failed discovery or sources remain incomplete. At most +31 discovered holder units accompany the master unit. Explicit file/unit selections +keep exactly the supplied sources. +Each selected unit uses read-only `systemctl show` and `journalctl`; missing +programs, permission errors, unavailable pages and old builds remain explicit. +With file sources but no unit or PID, startup arguments are unavailable. + +Exit 0 means all selected sources were collected, **not that the cluster is +healthy**. A collected check may report a failure. Exit 3 means some sources +were unavailable; inspect the manifest. Exit 2 is invalid input or existing +output, and exit 1 is a bundle write failure. A write failure can leave a partial, +already sanitized directory; a missing manifest is not a completed bundle. + +## Time and size bounds + +`-since` defaults to 15 minutes and accepts a positive duration up to 24 hours. +The window ends when collection starts. Local file logs are read before remote +observations, so an unresponsive master does not consume their collection budget. Journal requests carry both endpoints, +UTC output and no pager. Files accept the daemons' UTC Go timestamps (including +microseconds) or ISO timestamps. Continuation lines follow their preceding dated +record; undated leading text is omitted. A file with no dated records is unavailable. + +At most 32 explicit file/unit/PID selections and 32 volumes are collected. Sources +and sanitized artifacts are limited to 4 MiB each, with 32 MiB aggregate artifact +budgets and 1 MiB log records. A file larger than 4 MiB is refused rather than +starting inside an unrecognized multiline credential; rotate it or select a +bounded journal window. Links, pipes and non-UTF-8 log files are refused. Linux acquisition is nonblocking +and does not follow links, including if the path changes after inspection. +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. + +## Credential handling + +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. +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, +credential, authorization, API/access/private/TLS/control/client/signing key, JWT and HMAC. Bearer and +Basic authorization, URL user information and private-key PEM blocks are masked. +Explicitly identified credential values, including short passwords and +JSON/URL-escaped forms, are also removed from other collected text. Empty values, +true/false/yes/no/null and digits-only values shorter than eight bytes do not seed +global replacement. Bare whitespace +prose never teaches global replacement rules; ordinary words, dates and generation +numbers must remain readable. These ordinary values are still masked in their keyed/flag context. Unknown fields under a credential container are removed. + +Claim IDs remain support identifiers; they are not credentials. Ordinary diagnostic +lines and typed observations remain useful. No configuration tree, environment, +private-key file or guest data directory is swept. Use daemon logs, not arbitrary +application files: an opaque value with no credential label or known source cannot +be classified reliably. The planted-credential tests scan every emitted artifact +and command output; a disabled-redaction mutation must fail them. + +Log text is evidence for an operator. Runner decisions still use typed product +answers; bundle log text is not a health, durability or exact-generation verdict.