diff --git a/CLAUDE.md b/CLAUDE.md index 26d3d93..694ef8b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,7 +22,8 @@ docker compose up -d # Run with PostgreSQL + Streamable HTTP (via supergatewa - `internal/config/` — YAML + env var config loading - `internal/repository/` — Repository interface + SQLite/PostgreSQL implementations - `internal/service/` — Business logic (collision resolution, store, restore, search, file ops) -- `internal/s3/` — S3 presigned URL client (aws-sdk-go-v2), Presigner interface +- `internal/s3/` — S3 client (aws-sdk-go-v2): Presigner interface (presigned URLs, delete) + Streamer interface (GetObject/PutObject for the proxy) +- `internal/proxy/` — HMAC-signed proxy endpoints `/dl` (download) and `/ul` (upload) that stream file bytes between client and S3 - `internal/auth/` — Bearer token + JWT/JWKS validation, RFC 9728 Protected Resource Metadata, WWW-Authenticate headers - `internal/mcp/` — MCP server setup + tool handlers (text + file) - `internal/worker/` — Background expiration goroutine @@ -35,7 +36,7 @@ docker compose up -d # Run with PostgreSQL + Streamable HTTP (via supergatewa - **Domain errors → tool result errors** (not transport errors) — MCP client gets structured messages - **Collision resolution** — base word, then word2..word999, all within a transaction - **Auth per-transport** — stdio validates WORDSTORE_AUTH_TOKEN once at startup; SSE uses HTTP middleware -- **S3 presigned URLs** — file tools generate presigned PUT/GET URLs; MCP server never touches file data. Conditionally registered only when S3 is configured +- **S3 presigned URLs + optional proxy** — the `upload_file`/`download_file` MCP tools only return URLs, never file bytes. They always include presigned S3 PUT/GET URLs. When `s3.proxy` is configured they also include HMAC-signed `proxy_upload_url`/`proxy_url`, and then the server **does** carry file data: `GET /dl` streams S3 GetObject → client, `PUT /ul` streams client → S3 PutObject. Both must stay streaming (`io.Copy`, no `io.ReadAll`/whole-file buffers); the container runs with a 128Mi memory limit. `/dl` records completed downloads in `download_history` in the background with a detached context (`context.WithoutCancel` + timeout), because the request context is cancelled once the handler returns. File tools are registered only when S3 is configured - **Compact list/search responses** — `list_entries`, `search_entries`, `search_words` omit payload to reduce token usage; `get_entry`/`get_entry_by_word` return full content - **delete_entry accepts UUID or word** — tries UUID parse first, falls back to word lookup - **entry_type column** — `text` (default) or `file`; file entries store JSON metadata in payload field diff --git a/cmd/server/main.go b/cmd/server/main.go index af5518b..a00042b 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -9,6 +9,7 @@ import ( "os" "os/signal" "syscall" + "time" "github.com/mark3labs/mcp-go/server" @@ -25,6 +26,16 @@ import ( const version = "1.0.0" +// mcpSessionIdleTTL bounds per-session transport state in the Streamable HTTP +// server. mcp-go keeps it forever by default, so clients that disconnect +// without a DELETE leak memory; in production that grew until the container +// was OOM-killed every few weeks. +const mcpSessionIdleTTL = 30 * time.Minute + +func newStreamableHTTPServer(mcpSrv *server.MCPServer) *server.StreamableHTTPServer { + return server.NewStreamableHTTPServer(mcpSrv, server.WithSessionIdleTTL(mcpSessionIdleTTL)) +} + func main() { configPath := flag.String("config", "", "path to config file") flag.Parse() @@ -173,7 +184,7 @@ func main() { } case "streamable-http": innerMux := http.NewServeMux() - innerMux.Handle("/mcp", server.NewStreamableHTTPServer(mcpSrv)) + innerMux.Handle("/mcp", newStreamableHTTPServer(mcpSrv)) registerOAuthMetadata(innerMux, cfg) outerMux := http.NewServeMux() registerProxyHandler(outerMux, cfg, s3c, repo, logger) @@ -192,7 +203,7 @@ func main() { case "http": // Serve both SSE and Streamable HTTP on the same port innerMux := http.NewServeMux() - innerMux.Handle("/mcp", server.NewStreamableHTTPServer(mcpSrv)) + innerMux.Handle("/mcp", newStreamableHTTPServer(mcpSrv)) sseSrv := server.NewSSEServer(mcpSrv, server.WithSSEEndpoint("/sse"), server.WithBaseURL(fmt.Sprintf("http://localhost:%d", cfg.Server.HTTPPort)), diff --git a/internal/proxy/handler.go b/internal/proxy/handler.go index 9a5b25f..a179448 100644 --- a/internal/proxy/handler.go +++ b/internal/proxy/handler.go @@ -1,12 +1,14 @@ package proxy import ( + "context" "encoding/json" "errors" "fmt" "io" "log/slog" "net/http" + "time" "github.com/google/uuid" @@ -15,7 +17,13 @@ import ( s3client "github.com/watchword/watchword/internal/s3" ) +// recordDownloadTimeout bounds the best-effort download-history write that +// runs after the response has been sent. +const recordDownloadTimeout = 10 * time.Second + // Handler serves proxied file downloads with HMAC-signed URL validation. +// The object body is streamed from S3 straight to the client (io.Copy with a +// small fixed buffer); file content is never held in memory as a whole. type Handler struct { secret string streamer s3client.Streamer @@ -99,15 +107,25 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") if _, err := io.Copy(w, body); err != nil { - h.logger.Error("failed to stream file", "entry_id", entryID, "error", err) + // Only completed downloads are recorded. + if r.Context().Err() != nil { + h.logger.Info("download aborted by client", "entry_id", entryID, "error", err) + } else { + h.logger.Error("failed to stream file", "entry_id", entryID, "error", err) + } return } - // Record download best-effort in background + // Record download best-effort in background. The request context is + // cancelled as soon as ServeHTTP returns, so detach from its cancellation + // (keeping its values) and bound the write with its own timeout. + clientIP := r.RemoteAddr + userAgent := r.UserAgent() + recordCtx := context.WithoutCancel(r.Context()) go func() { - clientIP := r.RemoteAddr - userAgent := r.UserAgent() - if err := h.repo.RecordDownload(r.Context(), id, entry.Word, filename, clientIP, userAgent); err != nil { + ctx, cancel := context.WithTimeout(recordCtx, recordDownloadTimeout) + defer cancel() + if err := h.repo.RecordDownload(ctx, id, entry.Word, filename, clientIP, userAgent); err != nil { h.logger.Warn("failed to record download", "entry_id", entryID, "error", err) } }() diff --git a/internal/proxy/handler_stream_test.go b/internal/proxy/handler_stream_test.go new file mode 100644 index 0000000..b648131 --- /dev/null +++ b/internal/proxy/handler_stream_test.go @@ -0,0 +1,238 @@ +package proxy + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/google/uuid" + + "github.com/watchword/watchword/internal/domain" +) + +// countingWriter is an http.ResponseWriter that discards the body but counts +// bytes written. It optionally fails after failAfter bytes (simulating a +// client that disconnects mid-download). +type countingWriter struct { + header http.Header + status int + written int64 + failAfter int64 // 0 = never fail +} + +func newCountingWriter() *countingWriter { return &countingWriter{header: http.Header{}} } + +func (w *countingWriter) Header() http.Header { return w.header } +func (w *countingWriter) WriteHeader(code int) { + if w.status == 0 { + w.status = code + } +} +func (w *countingWriter) Write(p []byte) (int, error) { + if w.status == 0 { + w.status = http.StatusOK + } + if w.failAfter > 0 && w.written+int64(len(p)) > w.failAfter { + return 0, errors.New("client went away") + } + w.written += int64(len(p)) + return len(p), nil +} + +// guardedReader yields size bytes but fails if the handler pulls more than +// maxAhead bytes from it that have not yet been written to the client. That +// would mean the handler is buffering the object instead of streaming it. +type guardedReader struct { + size int64 + read int64 + maxAhead int64 + out *countingWriter + closed bool +} + +func (g *guardedReader) Read(p []byte) (int, error) { + if g.read >= g.size { + return 0, io.EOF + } + if ahead := g.read - g.out.written; ahead > g.maxAhead { + return 0, fmt.Errorf("handler buffered %d unwritten bytes (limit %d)", ahead, g.maxAhead) + } + n := int64(len(p)) + if rem := g.size - g.read; n > rem { + n = rem + } + for i := range p[:n] { + p[i] = 'x' + } + g.read += n + return int(n), nil +} + +func (g *guardedReader) Close() error { g.closed = true; return nil } + +type readerStreamer struct { + body io.ReadCloser + contentType string + size int64 +} + +func (s *readerStreamer) GetObject(_ context.Context, _ string) (io.ReadCloser, string, int64, error) { + return s.body, s.contentType, s.size, nil +} + +func (s *readerStreamer) PutObject(_ context.Context, _ string, _ io.Reader, _ string, _ int64) error { + return nil +} + +// recordingRepo captures RecordDownload calls. The call blocks until release +// is closed so the test can cancel the request context first. +type recordingRepo struct { + mockRepo + release chan struct{} + calls chan recordCall +} + +type recordCall struct { + ctxErr error + hasDeadline bool + clientIP string + userAgent string +} + +func (r *recordingRepo) RecordDownload(ctx context.Context, _ uuid.UUID, _, _, clientIP, userAgent string) error { + <-r.release + _, hasDeadline := ctx.Deadline() + r.calls <- recordCall{ctxErr: ctx.Err(), hasDeadline: hasDeadline, clientIP: clientIP, userAgent: userAgent} + return ctx.Err() +} + +func fileEntry(id uuid.UUID, filename string) *domain.Entry { + return &domain.Entry{ + ID: id, + Word: "bigfile", + EntryType: domain.EntryTypeFile, + Payload: `{"s3_key":"` + id.String() + `/` + filename + `","filename":"` + filename + `","content_type":"application/zip","size_limit":1073741824}`, + } +} + +func TestHandler_StreamsWithoutBuffering(t *testing.T) { + const size = 64 << 20 // 64 MiB, half the production memory limit + const maxAhead = 1 << 20 // never more than 1 MiB read-but-unwritten + + secret := "test-secret" + entryID := uuid.New() + repo := &recordingRepo{ + mockRepo: mockRepo{entry: fileEntry(entryID, "guide.zip")}, + release: make(chan struct{}), + calls: make(chan recordCall, 1), + } + close(repo.release) + + w := newCountingWriter() + body := &guardedReader{size: size, maxAhead: maxAhead, out: w} + handler := NewHandler(secret, &readerStreamer{body: body, contentType: "application/zip", size: size}, repo, slog.Default()) + + signedURL := SignDownloadURL("http://localhost", secret, entryID.String(), "guide.zip", 5*time.Minute) + handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, signedURL, nil)) + + if w.status != http.StatusOK { + t.Fatalf("status = %d, want 200", w.status) + } + if w.written != size { + t.Fatalf("written = %d, want %d (stream aborted: handler likely buffered)", w.written, size) + } + if !body.closed { + t.Error("S3 body was not closed") + } + if got := w.header.Get("Content-Length"); got != fmt.Sprint(size) { + t.Errorf("Content-Length = %q, want %d", got, size) + } + if got := w.header.Get("Content-Type"); got != "application/zip" { + t.Errorf("Content-Type = %q, want application/zip", got) + } + if got := w.header.Get("Content-Disposition"); got != `attachment; filename="guide.zip"` { + t.Errorf("Content-Disposition = %q", got) + } + + select { + case <-repo.calls: + case <-time.After(5 * time.Second): + t.Fatal("download was not recorded") + } +} + +func TestHandler_RecordDownloadSurvivesRequestCancel(t *testing.T) { + secret := "test-secret" + entryID := uuid.New() + repo := &recordingRepo{ + mockRepo: mockRepo{entry: fileEntry(entryID, "guide.zip")}, + release: make(chan struct{}), + calls: make(chan recordCall, 1), + } + handler := NewHandler(secret, &mockStreamer{body: "zipdata", contentType: "application/zip", size: 7}, repo, slog.Default()) + + signedURL := SignDownloadURL("http://localhost", secret, entryID.String(), "guide.zip", 5*time.Minute) + ctx, cancel := context.WithCancel(context.Background()) + req := httptest.NewRequest(http.MethodGet, signedURL, nil).WithContext(ctx) + req.RemoteAddr = "203.0.113.7:4321" + req.Header.Set("User-Agent", "curl/8") + + handler.ServeHTTP(httptest.NewRecorder(), req) + + // net/http cancels the request context once the handler returns (or the + // client disconnects). The background record must not inherit that. + cancel() + close(repo.release) + + select { + case c := <-repo.calls: + if c.ctxErr != nil { + t.Errorf("RecordDownload ctx error = %v, want nil", c.ctxErr) + } + if !c.hasDeadline { + t.Error("RecordDownload ctx has no deadline; want a bounded timeout") + } + if c.clientIP != "203.0.113.7:4321" || c.userAgent != "curl/8" { + t.Errorf("client info = %q / %q", c.clientIP, c.userAgent) + } + case <-time.After(5 * time.Second): + t.Fatal("download was not recorded") + } +} + +func TestHandler_ClientDisconnectNotRecorded(t *testing.T) { + secret := "test-secret" + entryID := uuid.New() + repo := &recordingRepo{ + mockRepo: mockRepo{entry: fileEntry(entryID, "guide.zip")}, + release: make(chan struct{}), + calls: make(chan recordCall, 1), + } + close(repo.release) + + w := newCountingWriter() + w.failAfter = 100 << 10 + body := &guardedReader{size: 8 << 20, maxAhead: 1 << 20, out: w} + handler := NewHandler(secret, &readerStreamer{body: body, contentType: "application/zip", size: 8 << 20}, repo, slog.Default()) + + signedURL := SignDownloadURL("http://localhost", secret, entryID.String(), "guide.zip", 5*time.Minute) + handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, signedURL, nil)) + + if !body.closed { + t.Error("S3 body was not closed after client disconnect") + } + if body.read >= body.size { + t.Error("handler kept reading the whole object after the client went away") + } + select { + case <-repo.calls: + t.Error("incomplete download was recorded") + case <-time.After(100 * time.Millisecond): + } +}