diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index e91969a5c..fe4b129f1 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -11,7 +11,6 @@ package archied import ( "context" - "crypto/subtle" "encoding/json" "fmt" "net" @@ -222,13 +221,3 @@ func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants) (op grpc.ChainStreamInterceptor(grants.StreamInterceptor(token)), }, false, nil } - -// constantTimeTokenValidator returns a staterpc.TokenValidator that accepts -// exactly the configured token, compared in constant time so a timing side -// channel cannot leak how many bytes matched (the standalone server's -// equivalent of the earlier in-process interceptor's token check). -func constantTimeTokenValidator(token string) staterpc.TokenValidator { - return func(candidate string) bool { - return subtle.ConstantTimeCompare([]byte(token), []byte(candidate)) == 1 - } -} diff --git a/internal/app/archied/state_store_test.go b/internal/app/archied/state_store_test.go index b743fa333..2d922ed30 100644 --- a/internal/app/archied/state_store_test.go +++ b/internal/app/archied/state_store_test.go @@ -50,19 +50,6 @@ func TestStateStoreServerOptsMalformedListen(t *testing.T) { } } -func TestConstantTimeTokenValidator(t *testing.T) { - validate := constantTimeTokenValidator("correct-token") - if !validate("correct-token") { - t.Fatal("validator should accept the configured token") - } - if validate("wrong-token") { - t.Fatal("validator should reject a different token") - } - if validate("") { - t.Fatal("validator should reject an empty token") - } -} - // TestServeStateStoreServesContract verifies the standalone composition's // serveStateStore + stateStoreDeps wiring actually serves the StateStore gRPC // contract over a real loopback listener: the same service .4.2 serves diff --git a/internal/infrastructure/staterpc/auth.go b/internal/infrastructure/staterpc/auth.go index fc7084713..041b404e0 100644 --- a/internal/infrastructure/staterpc/auth.go +++ b/internal/infrastructure/staterpc/auth.go @@ -4,9 +4,7 @@ import ( "context" "google.golang.org/grpc" - "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" ) // tokenMetadataKey is the gRPC metadata key the bearer token travels in. @@ -14,40 +12,6 @@ import ( // lifecycle note. const tokenMetadataKey = "state-store-token" -// TokenValidator reports whether token is a currently-issued, unexpired -// bearer token for the State Store's bridge-address listener topology. The -// caller (the daemon) owns the issued-token set; this package only enforces -// the check server-side and attaches the token client-side. -type TokenValidator func(token string) bool - -// UnaryTokenInterceptor validates the bearer token carried in each unary -// call's metadata, returning codes.Unauthenticated on a missing, unknown, or -// expired token. Required on the bridge-address (agent-consumed) listener -// topology per §9; not used on the loopback-only, daemon-only topology. -func UnaryTokenInterceptor(validate TokenValidator) grpc.UnaryServerInterceptor { - return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { - if err := checkToken(ctx, validate); err != nil { - return nil, err - } - return handler(ctx, req) - } -} - -func checkToken(ctx context.Context, validate TokenValidator) error { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return status.Error(codes.Unauthenticated, "missing state store token") - } - values := md.Get(tokenMetadataKey) - if len(values) == 0 || values[0] == "" { - return status.Error(codes.Unauthenticated, "missing state store token") - } - if !validate(values[0]) { - return status.Error(codes.Unauthenticated, "invalid state store token") - } - return nil -} - // UnaryClientTokenInterceptor attaches token to every outgoing call's // metadata under tokenMetadataKey. One token covers a task's container // lifetime (§9's per-incumbence lifecycle) so it does not need to be diff --git a/internal/infrastructure/staterpc/conformance_test.go b/internal/infrastructure/staterpc/conformance_test.go index bd5adabb7..4c397b776 100644 --- a/internal/infrastructure/staterpc/conformance_test.go +++ b/internal/infrastructure/staterpc/conformance_test.go @@ -263,50 +263,6 @@ func TestStateStoreConformance(t *testing.T) { } } -// TestTokenInterceptorRejectsMissingOrInvalidToken exercises the gRPC -// interceptor the bridge-address (agent-consumed) listener topology -// requires: missing or unrecognised tokens fail closed with -// codes.Unauthenticated, per §9's token lifecycle. -func TestTokenInterceptorRejectsMissingOrInvalidToken(t *testing.T) { - const validToken = "task-42-token" - validate := func(token string) bool { return token == validToken } - - listener := bufconn.Listen(1 << 20) - local := store.OpenTest(t) - server := grpc.NewServer(grpc.UnaryInterceptor(UnaryTokenInterceptor(validate))) - RegisterServer(server, Deps{Tasks: local}) - go func() { _ = server.Serve(listener) }() - t.Cleanup(func() { server.Stop(); _ = listener.Close() }) - - dial := func(t *testing.T, token string) contract { - t.Helper() - opts := []grpc.DialOption{ - grpc.WithTransportCredentials(insecure.NewCredentials()), - grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }), - } - if token != "" { - opts = append(opts, grpc.WithUnaryInterceptor(UnaryClientTokenInterceptor(token))) - } - conn, err := grpc.NewClient("passthrough:///state", opts...) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = conn.Close() }) - return NewClient(conn) - } - - ctx := t.Context() - if _, err := dial(t, "").StatusCounts(ctx); err == nil { - t.Fatal("missing token accepted") - } - if _, err := dial(t, "wrong-token").StatusCounts(ctx); err == nil { - t.Fatal("invalid token accepted") - } - if _, err := dial(t, validToken).StatusCounts(ctx); err != nil { - t.Fatalf("valid token rejected: %v", err) - } -} - // TestConfigSnapshotContract drives the published configuration projection // through both the local store and the gRPC client. The document is opaque to // this hop, so the test's whole claim is that it arrives unchanged: the UI diff --git a/internal/memory/builtin/provider.go b/internal/memory/builtin/provider.go index 4697f5b22..755789aa0 100644 --- a/internal/memory/builtin/provider.go +++ b/internal/memory/builtin/provider.go @@ -144,8 +144,7 @@ func (p *Provider) Err() error { return p.dirErr } // SystemPromptBlock implements memory.SystemPromptProvider. It returns a // markdown-formatted block containing the frozen snapshot of MEMORY.md and -// USER.md content, wrapped in … fences so the scrubber can -// strip it from streaming output. +// USER.md content, wrapped in … fences. // // When the frozen snapshot is enabled (the default), the block is built from // the snapshot captured at Initialize() time and does not change for the diff --git a/internal/memory/scrubber/scrubber.go b/internal/memory/scrubber/scrubber.go deleted file mode 100644 index 39509f08b..000000000 --- a/internal/memory/scrubber/scrubber.go +++ /dev/null @@ -1,340 +0,0 @@ -// Package scrubber implements a stateful StreamingContextScrubber that -// strips ... fence spans from streaming text output. It -// handles partial chunks that split across fence boundaries, maintains state -// between chunks, and only emits clean text downstream. -// -// The scrubber is designed for zero allocations in the hot path (normal text -// with no memory blocks). Buffers are pre-allocated and reused. An allocation -// occurs only when a tag spans a chunk boundary (the pending path), which is -// rare in practice. -package scrubber - -import ( - "bytes" - "fmt" - "io" - "strings" -) - -const ( - // openTag marks the start of a memory context block. - openTag = "" - // closeTag marks the end of a memory context block. - closeTag = "" - - // maxTagLen is the length of the longest tag we need to buffer for - // partial chunk boundary matching. - maxTagLen = len(closeTag) // 9 bytes -) - -// Scrubber strips ... fence spans from streaming text -// output. It maintains state between Write calls to handle fence tags -// that span chunk boundaries. -// -// A Scrubber is safe for use by a single goroutine; it is not safe for -// concurrent use without external synchronization. -type Scrubber struct { - w io.Writer // underlying writer; nil means discard - depth int // nesting depth of blocks (0 = normal text) - - // pending holds bytes from the end of the previous chunk that may be - // the start of a tag we're looking for. Backed by pbuf to avoid - // allocation when len(pending) <= maxTagLen. - pending []byte - pbuf [maxTagLen]byte - - // buf is a reusable buffer for building output in Process. - buf bytes.Buffer - - // writeErr stores the first write error from the underlying writer. - // Subsequent writes are skipped once an error is recorded. - writeErr error - - // Stats counters. - blocksStripped int - bytesStripped int64 -} - -// New creates a new Scrubber that writes scrubbed output to w. If w is -// nil, scrubbed output is discarded (useful when the caller only needs -// to count stripped blocks or when using Process). -func New(w io.Writer) *Scrubber { - return &Scrubber{w: w} -} - -// Reset resets the scrubber to its initial state so it can be reused. -// The underlying writer is preserved. Buffers are cleared without -// releasing backing arrays. -func (s *Scrubber) Reset() { - s.depth = 0 - s.pending = s.pending[:0] - s.buf.Reset() - s.writeErr = nil - s.blocksStripped = 0 - s.bytesStripped = 0 -} - -// Write processes a chunk of streaming text and writes the scrubbed output -// to the underlying writer. It returns the number of bytes consumed from p -// (always len(p) on success) and any write error from the underlying writer. -// -// Write is the primary streaming interface. It maintains internal state -// across calls to handle tags that span chunk boundaries. -func (s *Scrubber) Write(p []byte) (int, error) { - if len(p) == 0 { - return 0, nil - } - - data := p - - // Prepend any pending bytes from the previous chunk. - if len(s.pending) > 0 { - // We need to combine pending + new data. This allocates, but the - // pending path is rare (only when a tag is split across chunks). - combined := make([]byte, len(s.pending)+len(p)) - copy(combined, s.pending) - copy(combined[len(s.pending):], p) - data = combined - s.pending = s.pending[:0] - } - - for len(data) > 0 { - if s.depth > 0 { - data = s.processInMemory(data) - } else { - data = s.processNormal(data) - } - } - - // Return any stored write error. The full input length is reported as - // consumed per the io.Writer contract: we always consume the entire - // input even if the underlying writer fails (the data has been - // processed; the error is about delivery, not consumption). - return len(p), s.writeErr -} - -// processNormal handles input when we're outside a memory block (depth == 0). -// It looks for open tags and passes everything else through. -func (s *Scrubber) processNormal(data []byte) []byte { - // Fast path: no '<' at all means no possible tag. - idx := bytes.IndexByte(data, '<') - if idx < 0 { - s.writeOutput(data) - return nil - } - - // Check if the '<' starts a tag. - tail := data[idx:] - if len(tail) >= len(openTag) { - // Enough data to check the full tag. - if string(tail[:len(openTag)]) == openTag { - // Found -- write everything before it, then enter memory block. - s.writeOutput(data[:idx]) - s.depth++ - s.blocksStripped++ - s.bytesStripped += int64(len(openTag)) - return tail[len(openTag):] - } - // Not -- write the '<' and continue after it. - s.writeOutput(data[:idx+1]) - return data[idx+1:] - } - - // Not enough data to determine -- partial tag at end of chunk. - // Hold the tail for the next Write call. - if isPrefixOfTag(tail, openTag) { - s.writeOutput(data[:idx]) - s.pending = append(s.pbuf[:0], tail...) - return nil - } - - // Not a prefix of -- write everything. - s.writeOutput(data) - return nil -} - -// processInMemory handles input when we're inside a memory block (depth > 0). -// It looks for close tags and strips everything else. -func (s *Scrubber) processInMemory(data []byte) []byte { - // Fast path: no '<' means no possible close tag -- strip everything. - idx := bytes.IndexByte(data, '<') - if idx < 0 { - s.bytesStripped += int64(len(data)) - return nil - } - - tail := data[idx:] - - // Check for nested open tags (increment depth). - if len(tail) >= len(openTag) && string(tail[:len(openTag)]) == openTag { - s.bytesStripped += int64(idx + len(openTag)) - s.depth++ - s.blocksStripped++ - return tail[len(openTag):] - } - - // Check for close tag. - if len(tail) >= len(closeTag) { - if string(tail[:len(closeTag)]) == closeTag { - s.bytesStripped += int64(idx + len(closeTag)) - s.depth-- - return tail[len(closeTag):] - } - // Not a close tag -- skip the '<' and continue stripping. - s.bytesStripped += int64(idx + 1) - return data[idx+1:] - } - - // Not enough data to determine -- partial tag at end of chunk. - // Could be the start of (which would close the block) or - // (which would nest). Buffer it. - if isPrefixOfTag(tail, closeTag) || isPrefixOfTag(tail, openTag) { - s.bytesStripped += int64(idx) - s.pending = append(s.pbuf[:0], tail...) - return nil - } - - // Not a prefix of any relevant tag -- strip everything. - s.bytesStripped += int64(len(data)) - return nil -} - -// writeOutput writes data to the underlying writer. If a previous write -// error has been recorded, writes are silently skipped. New write errors -// are stored for return from Write/Flush. -func (s *Scrubber) writeOutput(data []byte) { - if len(data) == 0 || s.w == nil || s.writeErr != nil { - return - } - _, err := s.w.Write(data) - if err != nil && s.writeErr == nil { - s.writeErr = err - } -} - -// Flush writes any pending buffered bytes (from a partial tag match at the -// end of the previous chunk) to the underlying writer and resets the pending -// buffer. Call Flush at the end of the stream to ensure any partial tag that -// wasn't actually a tag is emitted. -// -// If the scrubber is inside a memory block when Flush is called, the block -// is implicitly closed (missing closing tag handling). Any pending bytes -// inside the block are stripped, not emitted. -func (s *Scrubber) Flush() error { - if s.depth > 0 { - // Inside an unclosed memory block. Pending bytes are content that - // was buffered as potential tag starts -- since no close tag arrives, - // they are memory-block content and should be stripped, not emitted. - s.bytesStripped += int64(len(s.pending)) - s.pending = s.pending[:0] - s.depth = 0 - } else if len(s.pending) > 0 { - // Outside a memory block -- pending bytes are literal text whose - // partial tag didn't resolve. - s.writeOutput(s.pending) - s.pending = s.pending[:0] - } - - err := s.writeErr - s.writeErr = nil - return err -} - -// Close is equivalent to Flush. It implements a subset of io.Closer for -// convenience when the scrubber is used in a pipeline. -func (s *Scrubber) Close() error { - return s.Flush() -} - -// Process is a convenience method that scrubs a single chunk and returns -// the cleaned text. It maintains internal state across calls, so it can -// be used for streaming just like Write. The returned string is only the -// newly scrubbed output from this chunk -- not the full accumulated output. -// -// For zero-allocation streaming, prefer Write with a pre-allocated writer. -func (s *Scrubber) Process(chunk string) string { - s.buf.Reset() - prev := s.w - s.w = &s.buf - // Restore the original writer even if Write panics. - defer func() { s.w = prev }() - _, _ = s.Write([]byte(chunk)) - if s.buf.Len() == 0 { - return "" - } - return s.buf.String() -} - -// ProcessString is a convenience method that scrubs a complete string in -// one call. It resets the scrubber state first and flushes at the end, -// so it is suitable for one-shot use. For streaming use, call Write or -// Process repeatedly and call Flush at the end. -func (s *Scrubber) ProcessString(input string) string { - s.Reset() - s.buf.Reset() - prev := s.w - s.w = &s.buf - defer func() { s.w = prev }() - _, _ = s.Write([]byte(input)) - _ = s.Flush() - return s.buf.String() -} - -// BlocksStripped returns the number of blocks that have been -// stripped since the last Reset. -func (s *Scrubber) BlocksStripped() int { - return s.blocksStripped -} - -// BytesStripped returns the total number of bytes stripped (including -// the fence tags themselves) since the last Reset. -func (s *Scrubber) BytesStripped() int64 { - return s.bytesStripped -} - -// InMemoryBlock reports whether the scrubber is currently inside a -// block (i.e., an open tag has been seen but no matching -// close tag yet). -func (s *Scrubber) InMemoryBlock() bool { - return s.depth > 0 -} - -// Depth returns the current nesting depth of blocks. -// The depth is represented as an int; it is the caller's responsibility -// to ensure nesting does not exceed reasonable bounds. -func (s *Scrubber) Depth() int { - return s.depth -} - -// ── Helpers ──────────────────────────────────────────────────────────── - -// isPrefixOfTag reports whether data is a prefix of tag -- i.e., data could -// be the start of tag if more bytes arrive later. Returns false if data is -// longer than tag. -func isPrefixOfTag(data []byte, tag string) bool { - if len(data) >= len(tag) { - return false - } - for i, b := range data { - if b != tag[i] { - return false - } - } - return len(data) > 0 -} - -// DebugString returns a human-readable representation of the scrubber's -// internal state. Useful for debugging tests. -func (s *Scrubber) DebugString() string { - var sb strings.Builder - fmt.Fprintf(&sb, "Scrubber{depth=%d", s.depth) - fmt.Fprintf(&sb, ", pending=%q", string(s.pending)) - fmt.Fprintf(&sb, ", blocksStripped=%d", s.blocksStripped) - fmt.Fprintf(&sb, ", bytesStripped=%d}", s.bytesStripped) - return sb.String() -} - -// Compile-time interface checks. -var ( - _ io.Writer = (*Scrubber)(nil) -) diff --git a/internal/memory/scrubber/scrubber_test.go b/internal/memory/scrubber/scrubber_test.go deleted file mode 100644 index 2a85d41c4..000000000 --- a/internal/memory/scrubber/scrubber_test.go +++ /dev/null @@ -1,1022 +0,0 @@ -package scrubber - -import ( - "bytes" - "fmt" - "io" - "strings" - "testing" -) - -// ── Basic functionality ───────────────────────────────────────────────── - -func TestScrubber_NoMemoryBlock(t *testing.T) { - s := New(nil) - result := s.ProcessString("Hello, world!") - if result != "Hello, world!" { - t.Errorf("got %q, want %q", result, "Hello, world!") - } - if s.BlocksStripped() != 0 { - t.Errorf("BlocksStripped = %d, want 0", s.BlocksStripped()) - } -} - -func TestScrubber_SingleMemoryBlock(t *testing.T) { - s := New(nil) - result := s.ProcessString("Before secret After") - if result != "Before After" { - t.Errorf("got %q, want %q", result, "Before After") - } - if s.BlocksStripped() != 1 { - t.Errorf("BlocksStripped = %d, want 1", s.BlocksStripped()) - } -} - -func TestScrubber_MultipleMemoryBlocks(t *testing.T) { - s := New(nil) - result := s.ProcessString("A x B y C") - if result != "A B C" { - t.Errorf("got %q, want %q", result, "A B C") - } - if s.BlocksStripped() != 2 { - t.Errorf("BlocksStripped = %d, want 2", s.BlocksStripped()) - } -} - -func TestScrubber_EmptyContent(t *testing.T) { - s := New(nil) - result := s.ProcessString("") - if result != "" { - t.Errorf("got %q, want %q", result, "") - } -} - -func TestScrubber_OnlyOpenTag(t *testing.T) { - // Missing close tag -- block is implicitly closed at end of stream. - s := New(nil) - result := s.ProcessString("Before stuff") - if result != "Before " { - t.Errorf("got %q, want %q", result, "Before ") - } -} - -func TestScrubber_OnlyCloseTag(t *testing.T) { - // Stray close tag with no open -- treated as literal text. - s := New(nil) - result := s.ProcessString("text more") - if result != "text more" { - t.Errorf("got %q, want %q", result, "text more") - } -} - -func TestScrubber_EmptyMemoryBlock(t *testing.T) { - s := New(nil) - result := s.ProcessString("beforeafter") - if result != "beforeafter" { - t.Errorf("got %q, want %q", result, "beforeafter") - } -} - -func TestScrubber_OnlyMemoryBlock(t *testing.T) { - s := New(nil) - result := s.ProcessString("everything") - if result != "" { - t.Errorf("got %q, want %q", result, "") - } -} - -// ── Nested tags ───────────────────────────────────────────────────────── - -func TestScrubber_NestedMemoryBlocks(t *testing.T) { - s := New(nil) - result := s.ProcessString("A outer inner back B") - if result != "A B" { - t.Errorf("got %q, want %q", result, "A B") - } - if s.BlocksStripped() != 2 { - t.Errorf("BlocksStripped = %d, want 2", s.BlocksStripped()) - } -} - -func TestScrubber_DeeplyNestedMemoryBlocks(t *testing.T) { - s := New(nil) - result := s.ProcessString("12321") - if result != "" { - t.Errorf("got %q, want %q", result, "") - } - if s.BlocksStripped() != 3 { - t.Errorf("BlocksStripped = %d, want 3", s.BlocksStripped()) - } -} - -func TestScrubber_UnbalancedNested_MoreOpens(t *testing.T) { - // More open tags than close tags -- remaining blocks implicitly closed - // at end of stream. Everything after the first is stripped - // because the outer block never closes. - s := New(nil) - result := s.ProcessString("A outer inner B") - if result != "A " { - t.Errorf("got %q, want %q", result, "A ") - } -} - -func TestScrubber_UnbalancedNested_MoreCloses(t *testing.T) { - // Extra close tags are literal text. - s := New(nil) - result := s.ProcessString("ab") - if result != "b" { - t.Errorf("got %q, want %q", result, "b") - } -} - -// ── Partial chunk handling ────────────────────────────────────────────── - -func TestScrubber_PartialOpenTag_SplitAtAngle(t *testing.T) { - // Open tag split right after '<' - var buf bytes.Buffer - s := New(&buf) - - _, _ = s.Write([]byte("Hello <")) - _, _ = s.Write([]byte("memory>secret World")) - - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - - result := buf.String() - if result != "Hello World" { - t.Errorf("got %q, want %q", result, "Hello World") - } -} - -func TestScrubber_PartialOpenTag_SplitMidTag(t *testing.T) { - tests := []struct { - name string - chunk1 string - chunk2 string - expected string - }{ - {name: "split after secret Bye", expected: "Hi Bye"}, - {name: "split after secret Bye", expected: "Hi Bye"}, - {name: "split after secret Bye", expected: "Hi Bye"}, - {name: "split after secret Bye", expected: "Hi Bye"}, - {name: "split after secret Bye", expected: "Hi Bye"}, - {name: "split after secret Bye", expected: "Hi Bye"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - _, _ = s.Write([]byte(tt.chunk1)) - _, _ = s.Write([]byte(tt.chunk2)) - - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - - if got := buf.String(); got != tt.expected { - t.Errorf("got %q, want %q", got, tt.expected) - } - }) - } -} - -func TestScrubber_PartialCloseTag_SplitMidTag(t *testing.T) { - tests := []struct { - name string - chunk1 string - chunk2 string - expected string - }{ - {name: "close split after <", chunk1: "AB secret <", chunk2: "/memory> CD", expected: "AB CD"}, - {name: "close split after secret CD", expected: "AB CD"}, - {name: "close split after secret CD", expected: "AB CD"}, - {name: "close split after secret CD", expected: "AB CD"}, - {name: "close split after secret CD", expected: "AB CD"}, - {name: "close split after secret CD", expected: "AB CD"}, - {name: "close split after secret CD", expected: "AB CD"}, - {name: "close split after secret CD", expected: "AB CD"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - _, _ = s.Write([]byte(tt.chunk1)) - _, _ = s.Write([]byte(tt.chunk2)) - - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - - if got := buf.String(); got != tt.expected { - t.Errorf("got %q, want %q", got, tt.expected) - } - }) - } -} - -func TestScrubber_PartialTag_NotActuallyATag(t *testing.T) { - tests := []struct { - name string - chunk1 string - chunk2 string - expected string - }{ - { - name: "literal < followed by x", chunk1: "abc <", chunk2: "x not a tag> def", - expected: "abc def", - }, - { - name: "literal def", - expected: "abc def", - }, - { - name: "literal def", - expected: "abc def", - }, - { - name: "partial in memory block not a close tag", - chunk1: "content more", - // "" is not "" -- it doesn't close the block. - // Everything inside the memory block is stripped until the real - // is found. - expected: "", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - _, _ = s.Write([]byte(tt.chunk1)) - _, _ = s.Write([]byte(tt.chunk2)) - - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - - if got := buf.String(); got != tt.expected { - t.Errorf("got %q, want %q", got, tt.expected) - } - }) - } -} - -func TestScrubber_LiteralAngleBrackets(t *testing.T) { - s := New(nil) - result := s.ProcessString("if (x < 5 && y > 3) { doStuff(); }") - if result != "if (x < 5 && y > 3) { doStuff(); }" { - t.Errorf("got %q, want %q", result, "if (x < 5 && y > 3) { doStuff(); }") - } -} - -func TestScrubber_LiteralLtInMemoryBlock(t *testing.T) { - s := New(nil) - result := s.ProcessString("before if (x < 5) { } after") - if result != "before after" { - t.Errorf("got %q, want %q", result, "before after") - } -} - -// ── Chunk boundary edge cases ────────────────────────────────────────── - -func TestScrubber_OpenTagAtExactChunkBoundary(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - _, _ = s.Write([]byte("Hello ")) - _, _ = s.Write([]byte("secret")) - _, _ = s.Write([]byte(" World")) - - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - - if got := buf.String(); got != "Hello World" { - t.Errorf("got %q, want %q", got, "Hello World") - } -} - -func TestScrubber_CloseTagAtExactChunkBoundary(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - _, _ = s.Write([]byte("Hello secret")) - _, _ = s.Write([]byte(" World")) - - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - - if got := buf.String(); got != "Hello World" { - t.Errorf("got %q, want %q", got, "Hello World") - } -} - -func TestScrubber_SingleByteChunks(t *testing.T) { - input := "abcdefghi" - var buf bytes.Buffer - s := New(&buf) - - for i := 0; i < len(input); i++ { - _, _ = s.Write([]byte{input[i]}) - } - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - - if got := buf.String(); got != "abcghi" { - t.Errorf("got %q, want %q", got, "abcghi") - } -} - -func TestScrubber_TwoByteChunks(t *testing.T) { - input := "abc" - var buf bytes.Buffer - s := New(&buf) - - for i := 0; i < len(input); i += 2 { - end := min(i+2, len(input)) - _, _ = s.Write([]byte(input[i:end])) - } - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - - if got := buf.String(); got != "ac" { - t.Errorf("got %q, want %q", got, "ac") - } -} - -func TestScrubber_ChunkEndingWithOpenTagStart(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - _, _ = s.Write([]byte("text <")) - _, _ = s.Write([]byte("notmemory> more")) - - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - - if got := buf.String(); got != "text more" { - t.Errorf("got %q, want %q", got, "text more") - } -} - -// ── Streaming Write interface ────────────────────────────────────────── - -func TestScrubber_Write_ReturnsBytesConsumed(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - input := []byte("hello") - n, err := s.Write(input) - if err != nil { - t.Fatalf("Write error: %v", err) - } - if n != len(input) { - t.Errorf("Write returned n=%d, want %d", n, len(input)) - } -} - -func TestScrubber_Write_EmptyChunk(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - n, err := s.Write(nil) - if err != nil { - t.Fatalf("Write(nil) error: %v", err) - } - if n != 0 { - t.Errorf("Write(nil) returned n=%d, want 0", n) - } -} - -func TestScrubber_Flush_EmptyState(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - // Flush with no writes should be a no-op. - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - if buf.Len() != 0 { - t.Errorf("buf has %d bytes after empty flush, want 0", buf.Len()) - } -} - -// ── Process / ProcessString ──────────────────────────────────────────── - -func TestScrubber_Process_StreamingEquivalence(t *testing.T) { - input := "A x B y C" - - // ProcessString (one-shot) - s1 := New(nil) - oneShot := s1.ProcessString(input) - - // Process with chunking (streaming) - s2 := New(nil) - var streamingResult strings.Builder - chunks := []string{"A x B ", "y C"} - for _, ch := range chunks { - streamingResult.WriteString(s2.Process(ch)) - } - _ = s2.Flush() - streamingResult.WriteString(s2.Process("")) // drain any final output - - if streamingResult.String() != oneShot { - t.Errorf("streaming result %q != one-shot %q", streamingResult.String(), oneShot) - } -} - -func TestScrubber_Process_ReturnsOnlyNewOutput(t *testing.T) { - s := New(nil) - r1 := s.Process("hello secret world") - r3 := s.Process("") - - if r1 != "hello " { - t.Errorf("first Process = %q, want %q", r1, "hello ") - } - if r2 != " world" { - t.Errorf("second Process = %q, want %q", r2, " world") - } - if r3 != "" { - t.Errorf("third Process = %q, want %q", r3, "") - } -} - -func TestScrubber_ProcessString_CompleteInput(t *testing.T) { - s := New(nil) - - r1 := s.ProcessString("A x B") - r2 := s.ProcessString("C y D") - - if r1 != "A B" { - t.Errorf("first = %q, want %q", r1, "A B") - } - if r2 != "C D" { - t.Errorf("second = %q, want %q", r2, "C D") - } -} - -// ── Reset ────────────────────────────────────────────────────────────── - -func TestScrubber_Reset_MidStream(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - _, _ = s.Write([]byte("A secret")) - if s.InMemoryBlock() == false { - t.Error("expected to be in memory block") - } - - s.Reset() - buf.Reset() - - if s.InMemoryBlock() { - t.Error("after Reset, should not be in memory block") - } - if s.BlocksStripped() != 0 { - t.Errorf("BlocksStripped = %d after Reset, want 0", s.BlocksStripped()) - } - - _, _ = s.Write([]byte("clean gone text")) - _ = s.Flush() - - if got := buf.String(); got != "clean text" { - t.Errorf("after Reset: got %q, want %q", got, "clean text") - } -} - -// ── Stats tracking ───────────────────────────────────────────────────── - -func TestScrubber_Stats(t *testing.T) { - s := New(nil) - s.ProcessString("x abcdef y ghijk z") - - if s.BlocksStripped() != 2 { - t.Errorf("BlocksStripped = %d, want 2", s.BlocksStripped()) - } - // Tags: = 8, = 9 each → 17*2 = 34 - // Content: "abcdef" = 6, "ghijk" = 5 → 11 - // Total stripped: 45 - expectedBytes := int64(45) - if s.BytesStripped() != expectedBytes { - t.Errorf("BytesStripped = %d, want %d", s.BytesStripped(), expectedBytes) - } -} - -func TestScrubber_Stats_Reset(t *testing.T) { - s := New(nil) - s.ProcessString("a") - - if s.BlocksStripped() == 0 { - t.Fatal("expected blocks to be stripped") - } - - s.Reset() - - if s.BlocksStripped() != 0 { - t.Errorf("BlocksStripped = %d after Reset, want 0", s.BlocksStripped()) - } - if s.BytesStripped() != 0 { - t.Errorf("BytesStripped = %d after Reset, want 0", s.BytesStripped()) - } -} - -// ── InMemoryBlock / Depth ────────────────────────────────────────────── - -func TestScrubber_InMemoryBlock(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - if s.InMemoryBlock() { - t.Error("InMemoryBlock should be false initially") - } - - _, _ = s.Write([]byte("before ")) - if !s.InMemoryBlock() { - t.Error("InMemoryBlock should be true after open tag") - } - - _, _ = s.Write([]byte("content after")) - if s.InMemoryBlock() { - t.Error("InMemoryBlock should be false after close tag") - } -} - -func TestScrubber_Depth(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - if s.Depth() != 0 { - t.Errorf("Depth = %d initially, want 0", s.Depth()) - } - - _, _ = s.Write([]byte("")) - if s.Depth() != 1 { - t.Errorf("Depth = %d after first open, want 1", s.Depth()) - } - - _, _ = s.Write([]byte("")) - if s.Depth() != 2 { - t.Errorf("Depth = %d after second open, want 2", s.Depth()) - } - - _, _ = s.Write([]byte("")) - if s.Depth() != 1 { - t.Errorf("Depth = %d after first close, want 1", s.Depth()) - } - - _, _ = s.Write([]byte("")) - if s.Depth() != 0 { - t.Errorf("Depth = %d after second close, want 0", s.Depth()) - } -} - -// ── Nil writer ───────────────────────────────────────────────────────── - -func TestScrubber_NilWriter(t *testing.T) { - s := New(nil) - - input := []byte("some hidden text") - n, err := s.Write(input) - if err != nil { - t.Fatalf("Write error with nil writer: %v", err) - } - if n != len(input) { - t.Errorf("Write returned n=%d, want %d", n, len(input)) - } - - if err := s.Flush(); err != nil { - t.Fatalf("Flush error with nil writer: %v", err) - } -} - -// ── IO Writer integration ────────────────────────────────────────────── - -func TestScrubber_IOWriter_Chain(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - _, err := io.WriteString(s, "Hello hidden World") - if err != nil { - t.Fatalf("io.WriteString error: %v", err) - } - _ = s.Flush() - - if got := buf.String(); got != "Hello World" { - t.Errorf("got %q, want %q", got, "Hello World") - } -} - -// ── Complex scenarios ────────────────────────────────────────────────── - -func TestScrubber_MemoryBlockAcrossManyChunks(t *testing.T) { - content := "This is a very long memory block with lots of content " + - "that should be stripped. " + strings.Repeat("blah ", 200) - input := "visible_start" + content + "visible_end" - - var buf bytes.Buffer - s := New(&buf) - - for i := 0; i < len(input); i += 3 { - end := min(i+3, len(input)) - _, _ = s.Write([]byte(input[i:end])) - } - _ = s.Flush() - - expected := "visible_startvisible_end" - if got := buf.String(); got != expected { - t.Errorf("got %q (len=%d), want %q (len=%d)", got, len(got), expected, len(expected)) - } -} - -func TestScrubber_ConsecutivePartialTags(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - _, _ = s.Write([]byte("a <")) // partial - _, _ = s.Write([]byte("m")) // still partial - _, _ = s.Write([]byte("emory>")) // complete! - _, _ = s.Write([]byte("hidden")) - _, _ = s.Write([]byte("")) // complete close - _, _ = s.Write([]byte("b")) - _ = s.Flush() - - if got := buf.String(); got != "a b" { - t.Errorf("got %q, want %q", got, "a b") - } -} - -func TestScrubber_MemoryLikeButNotExactly(t *testing.T) { - tests := []struct { - name string - input string - want string - }{ - {name: "memory without angle brackets", input: "memory and /memory are not tags", want: "memory and /memory are not tags"}, - {name: "angle bracket but wrong tag name", input: "use
content
here", want: "use
content
here"}, - {name: "unclosed angle bracket", input: "the more text", want: "text more text"}, - {name: "back-to-back memory blocks", input: "AxyB", want: "AB"}, - {name: "memory block at start", input: "xB", want: "B"}, - {name: "memory block at end", input: "Ax", want: "A"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - s := New(nil) - got := s.ProcessString(tt.input) - if got != tt.want { - t.Errorf("got %q, want %q", got, tt.want) - } - }) - } -} - -func TestScrubber_MalformedNested(t *testing.T) { - tests := []struct { - name string - input string - want string - }{ - {name: "interleaved close tags", input: "a
b", want: "b"}, - {name: "open after close", input: "b", want: ""}, - {name: "deeply nested with missing close", input: "ABCD", want: "A"}, - {name: "partial nest resolution", input: "ABCDE", want: "AE"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - s := New(nil) - got := s.ProcessString(tt.input) - if got != tt.want { - t.Errorf("got %q, want %q", got, tt.want) - } - }) - } -} - -// ── UTF-8 / multibyte handling ───────────────────────────────────────── - -func TestScrubber_UnicodeContent(t *testing.T) { - s := New(nil) - result := s.ProcessString("BEFORE こんにちは世界 AFTER") - if result != "BEFORE AFTER" { - t.Errorf("got %q, want %q", result, "BEFORE AFTER") - } -} - -func TestScrubber_UnicodeOutsideMemoryBlock(t *testing.T) { - s := New(nil) - result := s.ProcessString("👋 hello secret 🌍 world") - if result != "👋 hello 🌍 world" { - t.Errorf("got %q, want %q", result, "👋 hello 🌍 world") - } -} - -func TestScrubber_UnicodeSplitAcrossChunks(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - - _, _ = s.Write([]byte("Hi ")) // completes the open tag - _, _ = s.Write([]byte("世界 Bye")) - - _ = s.Flush() - - if got := buf.String(); got != "Hi Bye" { - t.Errorf("got %q, want %q", got, "Hi Bye") - } -} - -// ── Large input ───────────────────────────────────────────────────────── - -func TestScrubber_LargeInput(t *testing.T) { - var input strings.Builder - var expected strings.Builder - - input.WriteString("START ") - expected.WriteString("START ") - - for i := range 100 { - fmt.Fprintf(&input, " visible_%d ", i) - fmt.Fprintf(&expected, " visible_%d ", i) - - input.WriteString("") - fmt.Fprintf(&input, " hidden_block_%d ", i) - input.WriteString("") - } - - input.WriteString(" END") - expected.WriteString(" END") - - s := New(nil) - got := s.ProcessString(input.String()) - want := expected.String() - - if got != want { - t.Errorf("large output mismatch (got len=%d, want len=%d)", len(got), len(want)) - } -} - -// ── Regression: edge cases ───────────────────────────────────────────── - -func TestScrubber_Regression_DoubleChevron(t *testing.T) { - s := New(nil) - result := s.ProcessString("a <hidden b") - if result != "a < b" { - t.Errorf("got %q, want %q", result, "a < b") - } -} - -func TestScrubber_Regression_TagInTag(t *testing.T) { - s := New(nil) - result := s.ProcessString("x >test y") - if result != "x abc<", expected: ""}, - {name: "pending < only inside memory block", input: "<", expected: ""}, - {name: "pending abcabcabc<", expected: "hi"}, - {name: "nested with pending inside", input: "ABC<", expected: "A"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var buf bytes.Buffer - s := New(&buf) - _, _ = s.Write([]byte(tt.input)) - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - if got := buf.String(); got != tt.expected { - t.Errorf("got %q, want %q", got, tt.expected) - } - }) - } -} - -func TestScrubber_Flush_PendingInMemoryBlock_StatsCorrect(t *testing.T) { - // Finding 3: BytesStripped should count pending bytes that are stripped - // on Flush inside a memory block. - var buf bytes.Buffer - s := New(&buf) - _, _ = s.Write([]byte("abc<")) - // At this point: bytesStripped = 8 () + 3 (abc) = 11, pending = "<" - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - // After Flush: pending "<" should be counted as stripped - // Total: 8 + 3 + 1 = 12 - expectedBytes := int64(12) - if s.BytesStripped() != expectedBytes { - t.Errorf("BytesStripped = %d, want %d", s.BytesStripped(), expectedBytes) - } - // No output should be emitted - if buf.Len() != 0 { - t.Errorf("output = %q, want empty", buf.String()) - } -} - -func TestScrubber_Flush_PendingInMemoryBlock_TwoChunks(t *testing.T) { - // Finding 1 two-chunk variant: first chunk ends with pending inside - // memory block, second chunk is empty. - var buf bytes.Buffer - s := New(&buf) - _, _ = s.Write([]byte("xyz<")) - _, _ = s.Write([]byte("")) // empty chunk - if err := s.Flush(); err != nil { - t.Fatalf("Flush error: %v", err) - } - if got := buf.String(); got != "" { - t.Errorf("got %q, want %q", got, "") - } - if s.BytesStripped() == 0 { - t.Error("BytesStripped should include both the open tag and the stripped content") - } -} - -func TestScrubber_Flush_PendingOutsideMemoryBlock(t *testing.T) { - // Pending bytes OUTSIDE a memory block should still be emitted. - // This is the normal case for a partial tag that turns out not to be a tag. - var buf bytes.Buffer - s := New(&buf) - _, _ = s.Write([]byte("hello xyz<")) - _ = s.Flush() - - if got := buf.String(); got != "A " { - t.Errorf("got %q, want %q", got, "A ") - } - // bytesStripped: open tag (8) + "xyz" (3) + pending "<" (1) = 12 - if s.BytesStripped() != 12 { - t.Errorf("BytesStripped = %d, want 12", s.BytesStripped()) - } -} - -func TestScrubber_Write_ZeroLengthChunkWithPending(t *testing.T) { - // Zero-length write while pending is non-empty should leave pending - // untouched (no crash, no side effects). - var buf bytes.Buffer - s := New(&buf) - // Write text ending with a partial tag prefix. - _, _ = s.Write([]byte("data " so it should pass through. - _, _ = s.Write([]byte("x abc")) - _ = s.Flush() - if got := buf.String(); got != "data test")) - - ds := s.DebugString() - if !strings.Contains(ds, "depth=1") { - t.Errorf("DebugString should contain depth=1: %s", ds) - } -} - -// ── Benchmarks ───────────────────────────────────────────────────────── - -func BenchmarkScrubber_NoMemoryBlock(b *testing.B) { - s := New(io.Discard) - input := []byte("This is normal text without any memory blocks at all.") - b.ResetTimer() - b.ReportAllocs() - for b.Loop() { - _, _ = s.Write(input) - } - _ = s.Flush() -} - -func BenchmarkScrubber_SingleMemoryBlock(b *testing.B) { - s := New(io.Discard) - input := []byte("Before hidden content here After") - b.ResetTimer() - b.ReportAllocs() - for b.Loop() { - s.Reset() - _, _ = s.Write(input) - _ = s.Flush() - } -} - -func BenchmarkScrubber_ManySmallChunks(b *testing.B) { - text := "This is a long text with some hidden content that should be stripped and more text here" - var chunks [][]byte - for i := 0; i < len(text); i += 3 { - end := min(i+3, len(text)) - chunks = append(chunks, []byte(text[i:end])) - } - - s := New(io.Discard) - b.ResetTimer() - b.ReportAllocs() - for b.Loop() { - s.Reset() - for _, ch := range chunks { - _, _ = s.Write(ch) - } - _ = s.Flush() - } -} - -func BenchmarkScrubber_ProcessString(b *testing.B) { - s := New(nil) - input := "Before hidden content here After" - b.ResetTimer() - b.ReportAllocs() - for b.Loop() { - s.ProcessString(input) - } -} - -func BenchmarkScrubber_LargeInputManyBlocks(b *testing.B) { - var input strings.Builder - for i := range 100 { - fmt.Fprintf(&input, "visible_%d ", i) - input.WriteString("") - fmt.Fprintf(&input, "hidden_%d ", i) - input.WriteString("") - } - data := []byte(input.String()) - - s := New(io.Discard) - b.ResetTimer() - b.ReportAllocs() - for b.Loop() { - s.Reset() - _, _ = s.Write(data) - _ = s.Flush() - } -} - -func BenchmarkScrubber_NestedBlocks(b *testing.B) { - s := New(io.Discard) - input := []byte("A B C DEFG") - b.ResetTimer() - b.ReportAllocs() - for b.Loop() { - s.Reset() - _, _ = s.Write(input) - _ = s.Flush() - } -}