fix(cli): keep credential discovery ahead of collection limits

This commit is contained in:
pingqiu committed 2026-11-29 02:43:01 -08:00
1 parent c92f5b5a13
commit 7b65aab75f
9 files changed
+207 -15

No files matched your search

+24 -7
View File
@@ -35,9 +35,26 @@ type logBundle struct {
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")
@@ -59,11 +76,8 @@ func (b *logBundle) add(name string, data []byte, err error) {
}
func (b *logBundle) write(dir string) error {
// All discovery completes in memory. No raw artifact is ever staged on disk.
r := &bundleRedactor{secrets: map[string]bool{}}
for _, a := range b.Artifacts {
r.discover(a.data)
r.discover([]byte(a.Error))
}
b.discover(nil)
r := b.redactor
if r.overflow {
return errors.New("redaction discovery bound exceeded")
}
@@ -138,7 +152,7 @@ func (s inspectionShell) collectLogs(args []string, stdout, stderr io.Writer) in
b.add(fmt.Sprintf("file-%03d.log", i+1), nil, ctx.Err())
continue
}
data, err := readBundleLog(p, b.Since, b.Until)
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)
@@ -165,7 +179,7 @@ func (s inspectionShell) collectLogs(args []string, stdout, stderr io.Writer) in
}
return 0
}
func readBundleLog(path string, since, until time.Time) ([]byte, error) {
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")
@@ -192,6 +206,9 @@ func readBundleLog(path string, since, until time.Time) ([]byte, error) {
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) {
@@ -138,6 +138,13 @@ func TestLogCollectJournalsUseBoundsAndHeadSummaryIsReadOnly(t *testing.T) {
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")
@@ -82,7 +82,8 @@ func (b *logBundle) collectLocal(ctx context.Context, units, pids []string) {
for i, u := range units {
flags, err := bundleCommand(ctx, "systemctl", "show", "--property=ExecStart", "--value", "--", u)
b.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.Format(time.RFC3339Nano), "--until="+b.Until.Format(time.RFC3339Nano), "--unit="+u)
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)
}
@@ -8,13 +8,14 @@ import (
"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\n]*)(?:'|$)|([^\s,"';}]+))`)
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/@]+)@`)
@@ -126,7 +127,12 @@ func (r *bundleRedactor) discoverValue(v any) {
}
}
func (r *bundleRedactor) discoverText(text string) {
for _, m := range bundleSecretValue.FindAllStringSubmatch(text, 4097) {
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, "-") {
@@ -139,10 +145,20 @@ func (r *bundleRedactor) discoverText(text string) {
}
}
}
for _, m := range bundleAuthorization.FindAllStringSubmatch(text, 4097) {
matches = bundleAuthorization.FindAllStringSubmatch(text, 4097)
if len(matches) == 4097 {
r.overflow = true
return
}
for _, m := range matches {
r.remember(m[2])
}
for _, m := range bundleURLUser.FindAllStringSubmatch(text, 4097) {
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])
@@ -158,6 +174,17 @@ func (r *bundleRedactor) discoverText(text string) {
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:], " "))
}
}
}
}
}
@@ -36,11 +36,13 @@ func (b *logBundle) addJSON(name string, v any, err error) {
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.checkContext(ctx, "", "json", &check, &diagnostic, 32)
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 {
@@ -2,8 +2,11 @@ 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"
@@ -11,6 +14,7 @@ import (
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
@@ -315,6 +319,7 @@ func TestLogCollectRecognizedCredentialFormsNeverLeaveTheBundle(t *testing.T) {
{"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 {
@@ -402,3 +407,127 @@ func TestLogCollectPreservesExactLargeJSONNumbers(t *testing.T) {
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)
}
}
}
@@ -110,6 +110,11 @@ func (s inspectionShell) checkContext(ctx context.Context, volume, format string
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
+2 -1
View File
@@ -968,9 +968,10 @@ Notes:
| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status |
|---|---|---|---|---|---|---|
| `INV-CLI-BUNDLE-REDACTION-001` | Recognized credentials are discovered across bounded sources before any artifact is written, and their opaque repeats are masked. Bare prose does not seed global replacements; ordinary values are excluded. JSON counters retain exact integer values. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go`; `logBundle.write` | `TestLogCollectPlantedSecretsNeverLeaveTheBundle`, `TestLogCollectRecognizedCredentialFormsNeverLeaveTheBundle`, `TestLogCollectKeepsOrdinaryWordsAndGenerationsWhileRedactingTokens`, `TestLogCollectPreservesExactLargeJSONNumbers` | — (pure client sanitization) | ACTIVE |
| `INV-CLI-BUNDLE-REDACTION-001` | Recognized credentials are discovered across bounded sources before any artifact is written, and their opaque repeats are masked. Discovery precedes time filtering and aggregate-budget omission; exhausting the match bound refuses output. Bare prose does not seed global replacements; ordinary values are excluded. JSON counters retain exact integer values. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go`; `logBundle.write` | `TestLogCollectPlantedSecretsNeverLeaveTheBundle`, `TestLogCollectRecognizedCredentialFormsNeverLeaveTheBundle`, `TestLogCollectKeepsOrdinaryWordsAndGenerationsWhileRedactingTokens`, `TestLogCollectPreservesExactLargeJSONNumbers`, `TestLogCollectRefusesExhaustedCredentialDiscovery`, `TestLogCollectDiscoversCredentialsBeforeTheTimeWindow`, `TestLogCollectDiscoversCredentialsInSourcesBeyondTheArtifactBudget` | — (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 cannot block on a substituted FIFO and does not follow a substituted link; the opened file must still be the inspected regular file. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_open_linux.go` `openBundleLog`; `readBundleLog` | `TestLogCollectChangedSourceCannotBlockAcquisition`, `TestLogCollectJournalDeadlineAndLinkedFileAreUnavailable` (`cmd/sw-block/log_collect_linux_test.go`; Linux qualification required) | — (local input acquisition) | ACTIVE |
### B.6 Workspace: chunk lifecycle, GC and delete
+4 -1
View File
@@ -90,7 +90,10 @@ name resolution and reads share the same deadline. No unbounded subprocess outpu
## Credential handling
All source data stays in bounded memory until credential discovery finishes.
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,