mirror of
https://github.com/xlionjuan/wastebin-mcp-go.git
synced 2026-11-16 19:40:06 +00:00
* Typed error refactor done; verify passes. Co-authored-by: xlionjuan <[email protected]> * All 6 items done; verify passes. Co-authored-by: xlionjuan <[email protected]> * Review: narrow error-model claims, fix Unwrap coverage, docs sync * All findings fixed; verify passes, tests added, docs synced. Co-authored-by: xlionjuan <[email protected]> * Both changes done; verify + diff check pass. Co-authored-by: xlionjuan <[email protected]> * Docs contract fixed; verify passes clean. Co-authored-by: xlionjuan <[email protected]> * All 3 findings fixed; verify passes, fixture shrunk 44→26. Co-authored-by: xlionjuan <[email protected]> * docs contract: cover parseErrorDocRows guardrails and fix fixture scope claim Add TestParseErrorDocRows_Behavior, table-driven tests proving that a same-named row outside the handler-error section is ignored, a duplicate inside the section fails closed with errDocDuplicateRow, and extraction stops at the next heading. Correct the fixture scope description in errorDocCases and TestDocsMCPTools_ErrorRows: some cases deliberately duplicate rows already pinned verbatim by exact-output unit tests to exercise placeholder normalization, rather than claiming those rows are not duplicated. --------- Co-authored-by: opencode-agent[bot] <opencode-agent[bot]@users.noreply.github.com> Co-authored-by: xlionjuan <[email protected]>
3650 lines
93 KiB
Go
3650 lines
93 KiB
Go
package wastebin //nolint:testpackage // white-box tests need access to unexported types/functions
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"io"
|
||
"log/slog"
|
||
"net"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"net/url"
|
||
"os"
|
||
"path/filepath"
|
||
"strings"
|
||
"sync"
|
||
"syscall"
|
||
"testing"
|
||
)
|
||
|
||
func TestCreatePaste_Success(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
if r.Method != http.MethodPost {
|
||
t.Errorf("expected POST, got %s", r.Method)
|
||
}
|
||
|
||
if r.URL.Path != "/" {
|
||
t.Errorf("expected /, got %s", r.URL.Path)
|
||
}
|
||
|
||
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
|
||
t.Errorf("expected Content-Type application/json, got %s", ct)
|
||
}
|
||
|
||
var req map[string]any
|
||
|
||
err := json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
if req["text"] != "hello world" {
|
||
t.Errorf("expected text 'hello world', got %v", req["text"])
|
||
}
|
||
|
||
if req["extension"] != "go" {
|
||
t.Errorf("expected extension 'go', got %v", req["extension"])
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/ABC123.go"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "hello world"
|
||
ext := "go"
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Extension: &ext,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.ID != "ABC123" {
|
||
t.Errorf("expected ID 'ABC123', got %q", resp.ID)
|
||
}
|
||
|
||
if resp.Hostname != server.URL {
|
||
t.Errorf("expected hostname %q, got %q", server.URL, resp.Hostname)
|
||
}
|
||
|
||
if resp.URL != "/ABC123.go" {
|
||
t.Errorf("expected URL '/ABC123.go', got %q", resp.URL)
|
||
}
|
||
|
||
if resp.Raw != "/raw/ABC123.go" {
|
||
t.Errorf("expected Raw '/raw/ABC123.go', got %q", resp.Raw)
|
||
}
|
||
|
||
if resp.MarkdownRendered != "" {
|
||
t.Errorf("expected empty MarkdownRendered, got %q", resp.MarkdownRendered)
|
||
}
|
||
|
||
if resp.Hint != "" {
|
||
t.Errorf("expected empty Hint, got %q", resp.Hint)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_ExpirationParsed(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
var capturedExt, capturedExpires any
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err := json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
capturedExt = req["extension"]
|
||
capturedExpires = req["expires"]
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/EXP123"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
expires := "1h"
|
||
ext := "go"
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Expires: &expires,
|
||
Extension: &ext,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.ID != "EXP123" {
|
||
t.Errorf("expected ID EXP123, got %q", resp.ID)
|
||
}
|
||
|
||
// Verify expiration was parsed: "1h" = 3600 seconds
|
||
if capturedExpires != float64(3600) {
|
||
t.Errorf("expected expires=3600, got %v", capturedExpires)
|
||
}
|
||
|
||
if capturedExt != "go" {
|
||
t.Errorf("expected extension 'go', got %v", capturedExt)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_403Response(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.WriteHeader(http.StatusForbidden)
|
||
_, _ = w.Write([]byte("forbidden")) //nolint:errcheck // Test helper write error is acceptable
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "server rejected the request") {
|
||
t.Errorf("expected 403 error message, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_413Response(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.WriteHeader(http.StatusRequestEntityTooLarge)
|
||
_, _ = w.Write([]byte("too large")) //nolint:errcheck // Test helper write error is acceptable
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "content exceeds the server's maximum allowed size") {
|
||
t.Errorf("expected 413 error message, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_422Response(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||
_, _ = w.Write([]byte("expiration value is invalid")) //nolint:errcheck // Test helper write error is acceptable
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errServerValidation) {
|
||
t.Errorf("expected errServerValidation, got: %v", err)
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "expiration value is invalid") {
|
||
t.Errorf("expected body in 422 error message, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_422Response_EmptyBody(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errServerValidation) {
|
||
t.Errorf("expected errServerValidation, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_ExpirationTooLarge(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
|
||
t.Error("server should not be reached for too-large expiration")
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
expires := "200y" // 6,307,200,000 seconds — far above max
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Expires: &expires,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for too-large expiration, got nil")
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "expiration exceeds maximum supported value") {
|
||
t.Errorf("expected expiration exceeds maximum error, got: %v", err)
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "exceeds maximum") {
|
||
t.Errorf("expected error mentioning maximum, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_ExpirationMax(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
var capturedExpires any
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err := json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
capturedExpires = req["expires"]
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/MAXEXP"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
expires := "10y" // 315360000 — exactly maxExpirationSeconds
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Expires: &expires,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.ID != "MAXEXP" {
|
||
t.Errorf("expected ID MAXEXP, got %q", resp.ID)
|
||
}
|
||
|
||
if capturedExpires != float64(maxExpirationSeconds) {
|
||
t.Errorf("expected expires=%f, got %v", float64(maxExpirationSeconds), capturedExpires)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_UnknownHTTPError(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.WriteHeader(http.StatusInternalServerError)
|
||
_, _ = w.Write([]byte("internal error")) //nolint:errcheck // Test helper write error is acceptable
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
if !strings.Contains(
|
||
err.Error(),
|
||
"unknown HTTP error; ask the user to check the server status or the request: HTTP 500",
|
||
) {
|
||
t.Errorf("expected unknown HTTP error message, got: %v", err)
|
||
}
|
||
|
||
if strings.Contains(err.Error(), "internal error") {
|
||
t.Errorf("expected body NOT to be leaked in error message, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_LargeNonOKBody(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.WriteHeader(http.StatusInternalServerError)
|
||
|
||
// Write a 1 MB body to verify the client doesn't read it all.
|
||
largeBody := make([]byte, 1024*1024)
|
||
for i := range largeBody {
|
||
largeBody[i] = 'A'
|
||
}
|
||
|
||
_, _ = w.Write(largeBody) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
if !strings.Contains(
|
||
err.Error(),
|
||
"unknown HTTP error; ask the user to check the server status or the request: HTTP 500",
|
||
) {
|
||
t.Errorf("expected unknown HTTP error message, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_ContentTooLarge(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345" // Not actually used since pre-check fails
|
||
cfg.MaxContentSize = 10
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "this content is way longer than ten bytes"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "content exceeds the maximum allowed size") {
|
||
t.Errorf("expected content too large error, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_MutualExclusivity(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test content"
|
||
filePath := "/tmp/test.txt"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
FilePath: &filePath,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errBothContentAndFilePath) {
|
||
t.Errorf("expected errBothContentAndFilePath, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_NeitherContentNorFile(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{})
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errNeitherContentNorFilePath) {
|
||
t.Errorf("expected errNeitherContentNorFilePath, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode(t *testing.T) {
|
||
t.Parallel()
|
||
// Set up a temp directory as allowed path.
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Create a text file in the allowed directory.
|
||
fileContent := "hello from file"
|
||
|
||
filePath := filepath.Join(allowedDir, "testfile.txt")
|
||
|
||
err = os.WriteFile(filePath, []byte(fileContent), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err = json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
if req["text"] != fileContent {
|
||
t.Errorf("expected text %q, got %v", fileContent, req["text"])
|
||
}
|
||
// Extension derived from file name (.txt).
|
||
if req["extension"] != "txt" {
|
||
t.Errorf("expected extension 'txt', got %v", req["extension"])
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/XYZ789.txt"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &filePath,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.ID != "XYZ789" {
|
||
t.Errorf("expected ID 'XYZ789', got %q", resp.ID)
|
||
}
|
||
|
||
if resp.URL != "/XYZ789.txt" {
|
||
t.Errorf("expected URL '/XYZ789.txt', got %q", resp.URL)
|
||
}
|
||
|
||
if resp.Raw != "/raw/XYZ789.txt" {
|
||
t.Errorf("expected Raw '/raw/XYZ789.txt', got %q", resp.Raw)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_ExtensionOverride(t *testing.T) {
|
||
t.Parallel()
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
filePath := filepath.Join(allowedDir, "script.py")
|
||
|
||
err = os.WriteFile(filePath, []byte("print('hello')"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err = json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
// Even though the file has .py extension, args.Extension overrides to 'go'.
|
||
if req["extension"] != "go" {
|
||
t.Errorf("expected extension 'go', got %v", req["extension"])
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/ABC.go"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
ext := "go"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &filePath,
|
||
Extension: &ext,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_MarkdownRendered(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/MARKDOWN.md"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "# Hello"
|
||
ext := "md"
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Extension: &ext,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.MarkdownRendered != "/md/MARKDOWN.md" {
|
||
t.Errorf("expected MarkdownRendered '/md/MARKDOWN.md', got %q", resp.MarkdownRendered)
|
||
}
|
||
|
||
if resp.Hint != "" {
|
||
t.Errorf("expected empty Hint, got %q", resp.Hint)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_MarkdownRendered_WithMarkdownExt(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/POST.markdown"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "# Post"
|
||
ext := "markdown"
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Extension: &ext,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.MarkdownRendered != "/md/POST.markdown" {
|
||
t.Errorf("expected MarkdownRendered '/md/POST.markdown', got %q", resp.MarkdownRendered)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_Hint(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/NOPATH"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "no extension paste"
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
// No Extension set — ext will be "".
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.Hint == "" {
|
||
t.Error("expected Hint to be non-empty for pastes without extension")
|
||
}
|
||
|
||
if !strings.Contains(resp.Hint, "Extension not detected") {
|
||
t.Errorf("expected hint about extension, got %q", resp.Hint)
|
||
}
|
||
|
||
if resp.MarkdownRendered != "" {
|
||
t.Errorf("expected empty MarkdownRendered, got %q", resp.MarkdownRendered)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_BinaryFileRejected(t *testing.T) {
|
||
t.Parallel()
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Write a binary file.
|
||
filePath := filepath.Join(allowedDir, "binary.bin")
|
||
|
||
err = os.WriteFile(filePath, []byte{0x00, 0xFF, 0xFE}, 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Server should not be reached.
|
||
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
|
||
t.Error("server should not be called for binary file")
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &filePath,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for binary file, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errFileNotText) {
|
||
t.Errorf("expected errFileNotText, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_StatError(t *testing.T) {
|
||
t.Parallel()
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
// File doesn't exist yet — with ALLOWED_PATHS configured, EvalSymlinks
|
||
// failure returns generic errFilePathCannotBeUsed (not specific errors,
|
||
// to avoid leaking path existence info outside the sandbox).
|
||
nonExistentPath := filepath.Join(allowedDir, "nonexistent.txt")
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &nonExistentPath,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for nonexistent file")
|
||
}
|
||
|
||
if !errors.Is(err, errFilePathCannotBeUsed) {
|
||
t.Errorf("expected errFilePathCannotBeUsed, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_FileTooLarge(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Create a file larger than MaxContentSize.
|
||
filePath := filepath.Join(allowedDir, "large.txt")
|
||
data := make([]byte, 100)
|
||
|
||
err = os.WriteFile(filePath, data, 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
cfg.MaxContentSize = 50 // Smaller than our 100-byte file.
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &filePath,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for oversized file")
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "content exceeds the maximum allowed size") {
|
||
t.Errorf("expected content too large error, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_ReadError(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Use a directory path — os.Stat succeeds (it's a valid path),
|
||
// but os.ReadFile fails deterministically (can't read a directory's
|
||
// content as a file), regardless of whether running as root or not.
|
||
dirPath := allowedDir
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &dirPath,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for unreadable file")
|
||
}
|
||
|
||
if !errors.Is(err, errFilePathCannotBeUsed) {
|
||
t.Errorf("expected errFilePathCannotBeUsed, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_PermissionDenied(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
if os.Getuid() == 0 {
|
||
t.Skip("skipping permission-denied test when running as root")
|
||
}
|
||
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
noPermFile := filepath.Join(allowedDir, "noperm.txt")
|
||
|
||
err = os.WriteFile(noPermFile, []byte("test"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Remove all permissions.
|
||
err = os.Chmod(noPermFile, 0o000)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &noPermFile,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for permission-denied file, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errFilePathCannotBeUsed) {
|
||
t.Errorf("expected errFilePathCannotBeUsed, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_PathNotAllowed(t *testing.T) {
|
||
t.Parallel()
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
otherDir := filepath.Join(tmpDir, "other")
|
||
|
||
err = os.Mkdir(otherDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Write a file in the non-allowed directory.
|
||
filePath := filepath.Join(otherDir, "test.txt")
|
||
|
||
err = os.WriteFile(filePath, []byte("hello"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &filePath,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for disallowed path, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errPathNotAllowed) {
|
||
t.Errorf("expected errPathNotAllowed, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_SandboxTranslation(t *testing.T) {
|
||
t.Parallel()
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Create the actual file on the host side (mapped path).
|
||
// The sandbox path /sandbox/foo will be translated to allowedDir/foo.
|
||
subDir := filepath.Join(allowedDir, "sub")
|
||
|
||
err = os.Mkdir(subDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
hostFilePath := filepath.Join(subDir, "host_file.txt")
|
||
|
||
err = os.WriteFile(hostFilePath, []byte("translated content"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err = json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
if req["text"] != "translated content" {
|
||
t.Errorf("expected text 'translated content', got %v", req["text"])
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/TRANSLATED.txt"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
cfg.SandboxMounts = []SandboxMount{
|
||
{HostPath: allowedDir, SandboxPath: "/workspace"},
|
||
}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
sandboxPath := "/workspace/sub/host_file.txt"
|
||
translate := true
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &sandboxPath,
|
||
TranslateSandboxPath: &translate,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.ID != "TRANSLATED" {
|
||
t.Errorf("expected ID 'TRANSLATED', got %q", resp.ID)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_SandboxTranslationBlockedPath(t *testing.T) {
|
||
t.Parallel()
|
||
tmpDir := t.TempDir()
|
||
|
||
blockedDir := filepath.Join(tmpDir, "secret")
|
||
|
||
err := os.Mkdir(blockedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
hostFilePath := filepath.Join(blockedDir, "token.txt")
|
||
|
||
err = os.WriteFile(hostFilePath, []byte("blocked content"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
|
||
t.Error("server should not be reached when translated path is user-blocked")
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.BlockedPaths = []blockedPathEntry{blockedEntry(blockedDir)}
|
||
cfg.SandboxMounts = []SandboxMount{
|
||
{HostPath: blockedDir, SandboxPath: "/workspace"},
|
||
}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
sandboxPath := "/workspace/token.txt"
|
||
translate := true
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &sandboxPath,
|
||
TranslateSandboxPath: &translate,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for translated user-blocked path, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errUserBlockedPath) {
|
||
t.Errorf("expected errUserBlockedPath, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_SandboxTranslation_Transparent(t *testing.T) {
|
||
t.Parallel()
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Create the actual file on the host side (mapped path).
|
||
subDir := filepath.Join(allowedDir, "sub")
|
||
|
||
err = os.Mkdir(subDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
hostFilePath := filepath.Join(subDir, "transparent_test.txt")
|
||
|
||
err = os.WriteFile(hostFilePath, []byte("transparent mode content"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err = json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
if req["text"] != "transparent mode content" {
|
||
t.Errorf("expected text 'transparent mode content', got %v", req["text"])
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/TRANSPARENT.txt"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
cfg.SandboxMounts = []SandboxMount{
|
||
{HostPath: allowedDir, SandboxPath: "/workspace"},
|
||
}
|
||
cfg.SandboxTransparent = true
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
sandboxPath := "/workspace/sub/transparent_test.txt"
|
||
|
||
// TranslateSandboxPath is nil (as it would be in MCP mode when transparent
|
||
// removes it from the schema). Translation should still happen.
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &sandboxPath,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.ID != "TRANSPARENT" {
|
||
t.Errorf("expected ID 'TRANSPARENT', got %q", resp.ID)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_SandboxPathWithBlockedComponent_Rejected(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
tmpDir := t.TempDir()
|
||
|
||
// Host directory — a neutral path not containing any blocked component.
|
||
hostDir := filepath.Join(tmpDir, "realssh")
|
||
|
||
err := os.Mkdir(hostDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Create a test file at the host path.
|
||
hostFilePath := filepath.Join(hostDir, "id_rsa")
|
||
|
||
err = os.WriteFile(hostFilePath, []byte("ssh-key-data"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Server handler that should NEVER be reached — the .ssh component
|
||
// must be caught before translation, so the server is never called.
|
||
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
|
||
t.Error("server should not be reached when sandbox path contains .ssh")
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{hostDir}
|
||
cfg.SandboxMounts = []SandboxMount{
|
||
{HostPath: hostDir, SandboxPath: "/container/home/.ssh"},
|
||
}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
// The raw sandbox path contains .ssh — hasComponentBlocked must catch
|
||
// it before any translation occurs.
|
||
sandboxPath := "/container/home/.ssh/id_rsa"
|
||
translate := true
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &sandboxPath,
|
||
TranslateSandboxPath: &translate,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for sandbox path with .ssh component, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errBuiltinBlockedComponent) {
|
||
t.Errorf("expected errBuiltinBlockedComponent, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_SandboxTranslationWithoutFlag(t *testing.T) {
|
||
t.Parallel()
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
// Create file directly in allowed dir (no translation needed).
|
||
filePath := filepath.Join(allowedDir, "direct.txt")
|
||
|
||
err = os.WriteFile(filePath, []byte("direct content"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err = json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
if req["text"] != "direct content" {
|
||
t.Errorf("expected text 'direct content', got %v", req["text"])
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/DIRECT.txt"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
cfg.SandboxMounts = []SandboxMount{
|
||
{HostPath: allowedDir, SandboxPath: "/workspace"},
|
||
}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
// Without TranslateSandboxPath, the path is used as-is and must exist on host.
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &filePath,
|
||
// TranslateSandboxPath not set.
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_SandboxTranslationNoMounts(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
sandboxPath := "/workspace/file.txt"
|
||
translate := true
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &sandboxPath,
|
||
TranslateSandboxPath: &translate,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for sandbox translation with no mounts")
|
||
}
|
||
|
||
if !errors.Is(err, errSandboxTranslationNoMounts) {
|
||
t.Errorf("expected errSandboxTranslationNoMounts, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_SandboxTranslationNoMatch(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
cfg.SandboxMounts = []SandboxMount{
|
||
{HostPath: "/tmp", SandboxPath: "/workspace"},
|
||
}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
// Path does not match any configured mount.
|
||
sandboxPath := "/other/path/file.txt"
|
||
translate := true
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &sandboxPath,
|
||
TranslateSandboxPath: &translate,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for unmounted sandbox path")
|
||
}
|
||
|
||
if !errors.Is(err, errSandboxTranslationNoMatch) {
|
||
t.Errorf("expected errSandboxTranslationNoMatch, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_SandboxTranslationUnderMountHost_Rejected(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
// HostPath "/" used to be broken — isUnderMountHost appended "//" as the
|
||
// prefix check, causing every subpath to be falsely rejected. After the
|
||
// fix using filepath.Rel, the path is correctly recognized as under "/",
|
||
// so it passes the traversal check and fails only because the file does
|
||
// not exist.
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
cfg.SandboxMounts = []SandboxMount{
|
||
{HostPath: "/", SandboxPath: "/workspace"},
|
||
}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
sandboxPath := "/workspace/foo"
|
||
translate := true
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &sandboxPath,
|
||
TranslateSandboxPath: &translate,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
// The path is correctly translated and passes the traversal check.
|
||
// It fails because the translated file does not exist on disk.
|
||
if errors.Is(err, errPathTraversal) {
|
||
t.Errorf("expected non-traversal error after root-path fix, got errPathTraversal")
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_SandboxPathTraversal_Rejected(t *testing.T) {
|
||
t.Parallel()
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Create a target outside the allowed dir to confirm it's NOT read.
|
||
outsideDir := filepath.Join(tmpDir, "outside")
|
||
|
||
err = os.Mkdir(outsideDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
err = os.WriteFile(filepath.Join(outsideDir, "secret.txt"), []byte("leaked"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
|
||
t.Error("server should not be reached when path traversal is detected")
|
||
}))
|
||
t.Cleanup(server.Close)
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
cfg.SandboxMounts = []SandboxMount{
|
||
{HostPath: allowedDir, SandboxPath: "/workspace"},
|
||
}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
tests := []struct {
|
||
name string
|
||
path string
|
||
}{
|
||
{"parent dir escape", "/workspace/../secret.txt"},
|
||
{"double parent dir escape", "/workspace/../../etc/passwd"},
|
||
}
|
||
|
||
for _, tt := range tests {
|
||
t.Run(tt.name, func(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
translate := true
|
||
|
||
_, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &tt.path,
|
||
TranslateSandboxPath: &translate,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for sandbox path traversal, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errPathTraversal) {
|
||
t.Errorf("expected errPathTraversal, got: %v", err)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_SandboxPathWithoutTraversalFlag_StillBlocksTraversal(t *testing.T) {
|
||
t.Parallel()
|
||
// Even without translate_sandbox_path, the raw path with ".." should be
|
||
// rejected by validateFilePath's own traversal check.
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
|
||
t.Error("server should not be reached")
|
||
}))
|
||
t.Cleanup(server.Close)
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
traversalPath := "../secret.txt"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &traversalPath,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for path traversal without sandbox flag, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errPathTraversal) {
|
||
t.Errorf("expected errPathTraversal, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_ExtensionDetectionFromFilePath(t *testing.T) {
|
||
t.Parallel()
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
filePath := filepath.Join(allowedDir, "script.py")
|
||
|
||
err = os.WriteFile(filePath, []byte("print('hello')"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err = json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
if req["extension"] != "py" {
|
||
t.Errorf("expected extension 'py' from file path, got %v", req["extension"])
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/SCRIPT.py"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &filePath,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
// The response path includes .py, so ID should be without it.
|
||
if resp.ID != "SCRIPT" {
|
||
t.Errorf("expected ID 'SCRIPT', got %q", resp.ID)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_HintFromFileModeNoExtension(t *testing.T) {
|
||
t.Parallel()
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// File without extension (like a Makefile or Dockerfile).
|
||
filePath := filepath.Join(allowedDir, "Dockerfile")
|
||
|
||
err = os.WriteFile(filePath, []byte("FROM alpine"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err = json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
// No extension detected from "Dockerfile" — should be omitted from JSON.
|
||
if ext, ok := req["extension"]; ok {
|
||
t.Errorf("expected extension to be omitted, got %v", ext)
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/DOCKERFILE"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &filePath,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.Hint == "" {
|
||
t.Error("expected Hint to be non-empty for extensionless file")
|
||
}
|
||
|
||
if !strings.Contains(resp.Hint, "Extension not detected") {
|
||
t.Errorf("expected hint about extension, got %q", resp.Hint)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_ConnectionError(t *testing.T) {
|
||
t.Parallel()
|
||
// Create a server that we immediately close to trigger a connection error.
|
||
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
|
||
// Not reached.
|
||
}))
|
||
server.Close() // Close immediately — subsequent dial gets "connection refused".
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "cannot connect to Wastebin server") {
|
||
t.Errorf("expected connection error message, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_MarkdownRenderedInFileMode(t *testing.T) {
|
||
t.Parallel()
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
filePath := filepath.Join(allowedDir, "readme.md")
|
||
|
||
err = os.WriteFile(filePath, []byte("# Readme"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/README.md"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &filePath,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.MarkdownRendered != "/md/README.md" {
|
||
t.Errorf("expected MarkdownRendered '/md/README.md', got %q", resp.MarkdownRendered)
|
||
}
|
||
}
|
||
|
||
func TestNewWastebinClient_NilConfig(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
_, err := NewWastebinClient(nil)
|
||
if err == nil {
|
||
t.Fatal("expected error for nil config, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errConfigRequired) {
|
||
t.Errorf("expected errConfigRequired, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestNewWastebinClient_EmptyServerURL(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
_, err := NewWastebinClient(&Config{})
|
||
if err == nil {
|
||
t.Fatal("expected error for empty server URL, got nil")
|
||
}
|
||
}
|
||
|
||
func TestNewWastebinClient_BadURL(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
_, err := NewWastebinClient(&Config{ServerURL: "://bad"})
|
||
if err == nil {
|
||
t.Fatal("expected error for bad URL, got nil")
|
||
}
|
||
}
|
||
|
||
func TestNewWastebinClient_NoScheme(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
_, err := NewWastebinClient(&Config{ServerURL: "localhost:8080"})
|
||
if err == nil {
|
||
t.Fatal("expected error for missing scheme, got nil")
|
||
}
|
||
}
|
||
|
||
func TestNewWastebinClient_FTPScheme(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
_, err := NewWastebinClient(&Config{ServerURL: "ftp://server"})
|
||
if !errors.Is(err, errUnsupportedURLScheme) {
|
||
t.Errorf("expected errUnsupportedURLScheme, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestNewWastebinClient_URLWithPathNoHost(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
_, err := NewWastebinClient(&Config{ServerURL: "http:///path"})
|
||
if !errors.Is(err, errURLMissingHost) {
|
||
t.Errorf("expected errURLMissingHost, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestNewWastebinClient_NoHost(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
_, err := NewWastebinClient(&Config{ServerURL: "http://"})
|
||
if err == nil {
|
||
t.Fatal("expected error for missing host, got nil")
|
||
}
|
||
}
|
||
|
||
func TestValidateServerURL(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
tests := []struct {
|
||
name string
|
||
serverURL string
|
||
wantErr error
|
||
}{
|
||
{
|
||
name: "HTTP URL",
|
||
serverURL: "http://bin.example.com",
|
||
},
|
||
{
|
||
name: "HTTPS URL",
|
||
serverURL: "https://bin.example.com",
|
||
},
|
||
{
|
||
name: "base path",
|
||
serverURL: "https://bin.example.com/wastebin/base/",
|
||
},
|
||
{
|
||
name: "username",
|
||
serverURL: "https://[email protected]",
|
||
wantErr: errURLUserInfo,
|
||
},
|
||
//nolint:gosec // This case intentionally verifies rejection of embedded credentials.
|
||
{
|
||
name: "username and password",
|
||
serverURL: "https://user:[email protected]/base",
|
||
wantErr: errURLUserInfo,
|
||
},
|
||
{
|
||
name: "query string",
|
||
serverURL: "https://bin.example.com/base?tenant=a",
|
||
wantErr: errURLQuery,
|
||
},
|
||
{
|
||
name: "empty query",
|
||
serverURL: "https://bin.example.com/base?",
|
||
wantErr: errURLQuery,
|
||
},
|
||
{
|
||
name: "fragment",
|
||
serverURL: "https://bin.example.com/base#section",
|
||
wantErr: errURLFragment,
|
||
},
|
||
{
|
||
name: "escaped fragment",
|
||
serverURL: "https://bin.example.com/base#section%2Fdetail",
|
||
wantErr: errURLFragment,
|
||
},
|
||
}
|
||
|
||
for _, tt := range tests {
|
||
t.Run(tt.name, func(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
baseURL, err := validateServerURL(&Config{ServerURL: tt.serverURL})
|
||
if tt.wantErr != nil {
|
||
if !errors.Is(err, tt.wantErr) {
|
||
t.Fatalf("validateServerURL() error = %v, want %v", err, tt.wantErr)
|
||
}
|
||
|
||
if baseURL != nil {
|
||
t.Errorf("validateServerURL() URL = %v, want nil", baseURL)
|
||
}
|
||
|
||
return
|
||
}
|
||
|
||
if err != nil {
|
||
t.Fatalf("validateServerURL() unexpected error: %v", err)
|
||
}
|
||
|
||
if got := baseURL.String(); got != tt.serverURL {
|
||
t.Errorf("validateServerURL() URL = %q, want %q", got, tt.serverURL)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
// TestBuildPasteResponse tests the response builder directly.
|
||
|
||
func TestBuildPasteResponse_WithExt(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
baseURL, _ := url.Parse("https://bin.example.com") //nolint:errcheck // URL literal is safe
|
||
resp := buildPasteResponse(baseURL, "/ABC.go", "go", false)
|
||
|
||
if resp.ID != "ABC" {
|
||
t.Errorf("expected ID 'ABC', got %q", resp.ID)
|
||
}
|
||
|
||
if resp.URL != "/ABC.go" {
|
||
t.Errorf("expected URL '/ABC.go', got %q", resp.URL)
|
||
}
|
||
|
||
if resp.Raw != "/raw/ABC.go" {
|
||
t.Errorf("expected Raw '/raw/ABC.go', got %q", resp.Raw)
|
||
}
|
||
|
||
if resp.MarkdownRendered != "" {
|
||
t.Errorf("expected empty MarkdownRendered, got %q", resp.MarkdownRendered)
|
||
}
|
||
|
||
if resp.Hint != "" {
|
||
t.Errorf("expected empty Hint, got %q", resp.Hint)
|
||
}
|
||
}
|
||
|
||
func TestBuildPasteResponse_Markdown(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
baseURL, _ := url.Parse("https://bin.example.com") //nolint:errcheck // URL literal is safe
|
||
resp := buildPasteResponse(baseURL, "/POST.md", "md", false)
|
||
|
||
if resp.ID != "POST" {
|
||
t.Errorf("expected ID 'POST', got %q", resp.ID)
|
||
}
|
||
|
||
if resp.MarkdownRendered != "/md/POST.md" {
|
||
t.Errorf("expected MarkdownRendered '/md/POST.md', got %q", resp.MarkdownRendered)
|
||
}
|
||
|
||
if resp.Hint != "" {
|
||
t.Errorf("expected empty Hint, got %q", resp.Hint)
|
||
}
|
||
}
|
||
|
||
func TestBuildPasteResponse_NoExt(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
baseURL, _ := url.Parse("https://bin.example.com") //nolint:errcheck // URL literal is safe
|
||
resp := buildPasteResponse(baseURL, "/NOPATH", "", false)
|
||
|
||
if resp.ID != "NOPATH" {
|
||
t.Errorf("expected ID 'NOPATH', got %q", resp.ID)
|
||
}
|
||
|
||
if resp.MarkdownRendered != "" {
|
||
t.Errorf("expected empty MarkdownRendered, got %q", resp.MarkdownRendered)
|
||
}
|
||
|
||
if resp.Hint == "" {
|
||
t.Error("expected non-empty Hint for no extension")
|
||
}
|
||
}
|
||
|
||
func TestBuildPasteResponse_MultiPartExt(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
baseURL, _ := url.Parse("https://bin.example.com") //nolint:errcheck // URL literal is safe
|
||
resp := buildPasteResponse(baseURL, "/abc.tar.gz", "tar.gz", false)
|
||
|
||
if resp.ID != "abc" {
|
||
t.Errorf("expected ID 'abc', got %q", resp.ID)
|
||
}
|
||
|
||
if resp.URL != "/abc.tar.gz" {
|
||
t.Errorf("expected URL '/abc.tar.gz', got %q", resp.URL)
|
||
}
|
||
|
||
if resp.Raw != "/raw/abc.tar.gz" {
|
||
t.Errorf("expected Raw '/raw/abc.tar.gz', got %q", resp.Raw)
|
||
}
|
||
}
|
||
|
||
func TestBuildPasteResponse_TrailingSlashBaseURL(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
baseURL, _ := url.Parse("https://bin.example.com/") //nolint:errcheck // URL literal is safe
|
||
resp := buildPasteResponse(baseURL, "/XYZ.go", "go", false)
|
||
|
||
if resp.Hostname != "https://bin.example.com" {
|
||
t.Errorf("expected hostname without trailing slash, got %q", resp.Hostname)
|
||
}
|
||
}
|
||
|
||
func TestValidateWastebinResponse_EmptyPath(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
err := validateWastebinResponse(wastebinResponse{Path: ""})
|
||
if !errors.Is(err, errInvalidWastebinResponse) {
|
||
t.Errorf("expected errInvalidWastebinResponse, got: %v", err)
|
||
}
|
||
|
||
if err == nil {
|
||
t.Fatal("expected error for empty path, got nil")
|
||
}
|
||
}
|
||
|
||
func TestValidateWastebinResponse_JustSlash(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
err := validateWastebinResponse(wastebinResponse{Path: "/"})
|
||
if !errors.Is(err, errInvalidWastebinResponse) {
|
||
t.Errorf("expected errInvalidWastebinResponse, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestValidateWastebinResponse_NonEmptyPath(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
err := validateWastebinResponse(wastebinResponse{Path: "/ABC.go"})
|
||
if err != nil {
|
||
t.Errorf("expected no error for valid path, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestValidateWastebinResponse_ValidPathOnlyID(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
err := validateWastebinResponse(wastebinResponse{Path: "/abc123"})
|
||
if err != nil {
|
||
t.Errorf("expected no error for valid path without extension, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestValidateWastebinResponse_AbsoluteURL(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
err := validateWastebinResponse(wastebinResponse{Path: "https://evil.example.com/malicious"})
|
||
if !errors.Is(err, errInvalidWastebinResponse) {
|
||
t.Errorf("expected errInvalidWastebinResponse, got: %v", err)
|
||
}
|
||
}
|
||
|
||
// errorReader is a helper for testing closeResponseBody with a body that
|
||
// returns an error on Close. It implements io.ReadCloser.
|
||
type errorReader struct{}
|
||
|
||
func (errorReader) Read(_ []byte) (int, error) { return 0, io.EOF }
|
||
|
||
func (errorReader) Close() error { return errors.New("close error") } //nolint:err113 // test helper
|
||
|
||
//nolint:paralleltest // intentional: modifies global slog state
|
||
func TestCloseResponseBody_CloseErrorLogged(t *testing.T) {
|
||
// NOTE: no t.Parallel() — slog.SetDefault() modifies global state and
|
||
// would race with other parallel tests that log via slog.Debug().
|
||
|
||
// Create a slog handler that captures log records.
|
||
var logBuf bytes.Buffer
|
||
|
||
handler := slog.NewTextHandler(&logBuf, &slog.HandlerOptions{Level: slog.LevelDebug})
|
||
original := slog.Default()
|
||
|
||
slog.SetDefault(slog.New(handler))
|
||
defer slog.SetDefault(original)
|
||
|
||
// Response body whose Close returns an error.
|
||
resp := &http.Response{
|
||
Body: &errorReader{},
|
||
}
|
||
|
||
closeResponseBody(resp)
|
||
|
||
output := logBuf.String()
|
||
if !strings.Contains(output, "failed to close response body") {
|
||
t.Error("expected debug log about close error, got:", output)
|
||
}
|
||
}
|
||
|
||
func TestIsConnectionError_NonMatch(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
errTestNonDial := errors.New("some other error") //nolint:err113 // test helper error
|
||
result := isConnectionError(errTestNonDial)
|
||
|
||
if result {
|
||
t.Error("expected false for non-dial error")
|
||
}
|
||
}
|
||
|
||
func TestNewWastebinClient_RedirectFollowed(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
// Server that redirects once to final destination.
|
||
// baseURL.JoinPath("/") appends "/", so the POST path has a trailing slash.
|
||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
if r.URL.Path == "/redirect/" {
|
||
// Redirect to the root which returns the JSON response.
|
||
http.Redirect(w, r, "/", http.StatusFound)
|
||
|
||
return
|
||
}
|
||
|
||
// Final destination.
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/REDIRECTED"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer ts.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = ts.URL + "/redirect" // postURL becomes ts.URL + "/redirect/".
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.ID != "REDIRECTED" {
|
||
t.Errorf("expected ID 'REDIRECTED', got %q", resp.ID)
|
||
}
|
||
}
|
||
|
||
func TestNewWastebinClient_RedirectDifferentHostBlocked(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
// baseURL.JoinPath("/") appends "/", so the POST path has a trailing slash.
|
||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
if r.URL.Path == "/redirect/" {
|
||
// Redirect to a completely different host.
|
||
http.Redirect(w, r, "http://evil.example.com/malicious", http.StatusFound)
|
||
|
||
return
|
||
}
|
||
|
||
w.WriteHeader(http.StatusOK)
|
||
}))
|
||
defer ts.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = ts.URL + "/redirect" // postURL becomes ts.URL + "/redirect/".
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected redirect error, got nil")
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "redirect to different host") {
|
||
t.Errorf("expected redirect blocked error, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestNewWastebinClient_RedirectSchemeDowngradeBlocked(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
if r.URL.Path == "/redirect/" {
|
||
//nolint:gosec // Test-only redirect to same host with scheme downgrade is intentional
|
||
http.Redirect(w, r, "http://"+r.Host+"/", http.StatusFound)
|
||
|
||
return
|
||
}
|
||
|
||
w.WriteHeader(http.StatusOK)
|
||
}))
|
||
defer ts.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = ts.URL + "/redirect"
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
// Override transport to trust the test server's self-signed TLS cert.
|
||
client.httpClient.Transport = ts.Client().Transport
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected redirect scheme downgrade error, got nil")
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "redirect scheme downgrade") {
|
||
t.Errorf("expected scheme downgrade error, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestNewWastebinClient_TooManyRedirects(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
http.Redirect(w, r, "/", http.StatusFound)
|
||
}))
|
||
defer ts.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = ts.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected too many redirects error, got nil")
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "stopped after 10 redirects") {
|
||
t.Errorf("expected stopped after 10 redirects error, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestShouldTranslateSandboxPath(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
tests := []struct {
|
||
name string
|
||
mounts []SandboxMount
|
||
transparent bool
|
||
requested *bool
|
||
want bool
|
||
}{
|
||
{
|
||
name: "no mounts, nil requested, not transparent",
|
||
mounts: nil,
|
||
want: false,
|
||
},
|
||
{
|
||
name: "no mounts, transparent true",
|
||
mounts: nil,
|
||
transparent: true,
|
||
want: false,
|
||
},
|
||
{
|
||
name: "with mounts, transparent false, requested nil",
|
||
mounts: []SandboxMount{{HostPath: "/host", SandboxPath: "/sandbox"}},
|
||
transparent: false,
|
||
want: false,
|
||
},
|
||
{
|
||
name: "with mounts, transparent false, requested false",
|
||
mounts: []SandboxMount{{HostPath: "/host", SandboxPath: "/sandbox"}},
|
||
transparent: false,
|
||
requested: new(bool),
|
||
want: false,
|
||
},
|
||
{
|
||
name: "opt-in: with mounts, requested true",
|
||
mounts: []SandboxMount{{HostPath: "/host", SandboxPath: "/sandbox"}},
|
||
transparent: false,
|
||
requested: func() *bool {
|
||
b := true
|
||
|
||
return &b
|
||
}(),
|
||
want: true,
|
||
},
|
||
{
|
||
name: "transparent: with mounts, requested nil",
|
||
mounts: []SandboxMount{{HostPath: "/host", SandboxPath: "/sandbox"}},
|
||
transparent: true,
|
||
want: true,
|
||
},
|
||
{
|
||
name: "transparent: with mounts, requested false (redundant but should still translate)",
|
||
mounts: []SandboxMount{{HostPath: "/host", SandboxPath: "/sandbox"}},
|
||
transparent: true,
|
||
requested: new(bool),
|
||
want: true,
|
||
},
|
||
{
|
||
name: "transparent + explicit opt-in: with mounts, requested true",
|
||
mounts: []SandboxMount{{HostPath: "/host", SandboxPath: "/sandbox"}},
|
||
transparent: true,
|
||
requested: func() *bool {
|
||
v := true
|
||
|
||
return &v
|
||
}(),
|
||
want: true,
|
||
},
|
||
}
|
||
|
||
for _, tt := range tests {
|
||
t.Run(tt.name, func(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
cfg := &Config{
|
||
SandboxMounts: tt.mounts,
|
||
SandboxTransparent: tt.transparent,
|
||
}
|
||
|
||
got := shouldTranslateSandboxPath(cfg, tt.requested)
|
||
if got != tt.want {
|
||
t.Errorf("shouldTranslateSandboxPath() = %v, want %v", got, tt.want)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_ContentEmpty(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
empty := ""
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &empty,
|
||
})
|
||
if !errors.Is(err, errContentEmpty) {
|
||
t.Errorf("expected errContentEmpty, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_PasswordOverHTTP(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err := json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
if _, ok := req["password"]; !ok {
|
||
t.Error("expected password in request body")
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/PASSWD"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
// httptest binds to 127.0.0.1 (loopback), so password over loopback HTTP
|
||
// is allowed but triggers a warning.
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "secret"
|
||
password := "hunter2"
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Password: &password,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.PasswordHint == "" {
|
||
t.Error("expected PasswordHint to be set for password-protected paste")
|
||
}
|
||
|
||
if !strings.Contains(resp.PasswordHint, "Wastebin-Password") {
|
||
t.Error("PasswordHint should mention Wastebin-Password header")
|
||
}
|
||
|
||
if strings.Contains(resp.PasswordHint, "?password=") {
|
||
t.Error("PasswordHint must not recommend query-parameter password transport (URL secrets are logged)")
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_PasswordOverHTTP_NonLoopbackRejected(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
// Non-loopback HTTP URL — password should be rejected.
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://wastebin.example.com:8080"
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "secret"
|
||
password := "hunter2"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Password: &password,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for password over non-loopback HTTP, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errPasswordOverHTTP) {
|
||
t.Errorf("expected errPasswordOverHTTP, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_PasswordOverHTTP_NonLoopbackAllowedWithOverride(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err := json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
if _, ok := req["password"]; !ok {
|
||
t.Error("expected password in request body")
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/PASSWD"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
// Keep baseURL as the non-loopback configured host so the policy check
|
||
// still sees the non-loopback URL. Route only the HTTP transport to
|
||
// the test server by overriding the dialer.
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://wastebin.example.com:12345"
|
||
cfg.AllowInsecurePassword = true
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
serverBase, err := url.Parse(server.URL)
|
||
if err != nil {
|
||
t.Fatalf("failed to parse server URL: %v", err)
|
||
}
|
||
|
||
client.httpClient.Transport = &http.Transport{
|
||
DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
|
||
return new(net.Dialer).DialContext(ctx, network, serverBase.Host)
|
||
},
|
||
}
|
||
|
||
content := "secret"
|
||
password := "hunter2"
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Password: &password,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.PasswordHint == "" {
|
||
t.Error("expected PasswordHint to be set for password-protected paste")
|
||
}
|
||
}
|
||
|
||
func TestIsLoopbackHost(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
tests := []struct {
|
||
name string
|
||
host string
|
||
want bool
|
||
}{
|
||
{name: "localhost", host: "localhost", want: true},
|
||
{name: "localhost uppercase", host: "LOCALHOST", want: true},
|
||
{name: "localhost mixed case", host: "LocalHost", want: true},
|
||
{name: "localhost with port", host: "localhost:8080", want: true},
|
||
{name: "IPv4 loopback", host: "127.0.0.1", want: true},
|
||
{name: "IPv4 loopback with port", host: "127.0.0.1:8080", want: true},
|
||
{name: "IPv6 loopback", host: "::1", want: true},
|
||
{name: "IPv6 loopback bracketed", host: "[::1]", want: true},
|
||
{name: "IPv6 loopback with port", host: "[::1]:8080", want: true},
|
||
{name: "non-loopback hostname", host: "example.com", want: false},
|
||
{name: "non-loopback hostname with port", host: "example.com:8080", want: false},
|
||
{name: "non-loopback IPv4", host: "10.0.0.1", want: false},
|
||
{name: "non-loopback IPv4 with port", host: "10.0.0.1:3000", want: false},
|
||
{name: "empty string", host: "", want: false},
|
||
{name: "IP without port IPv6", host: "::face", want: false},
|
||
}
|
||
|
||
for _, tt := range tests {
|
||
t.Run(tt.name, func(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
got := isLoopbackHost(tt.host)
|
||
if got != tt.want {
|
||
t.Errorf("isLoopbackHost(%q) = %v, want %v", tt.host, got, tt.want)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_InvalidExpiration(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/EXPIRED"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
badExpiry := "not-a-valid-expiry"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Expires: &badExpiry,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for invalid expiration")
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "invalid expiration format") {
|
||
t.Errorf("expected 'invalid expiration format' error, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_JSONDecodeError(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_, _ = w.Write([]byte(`{invalid json`)) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for invalid JSON response")
|
||
}
|
||
|
||
if !strings.Contains(err.Error(), "failed to parse Wastebin response") {
|
||
t.Errorf("expected parse error, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_EmptyPathResponse(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_, _ = w.Write([]byte(`{}`)) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for empty path response")
|
||
}
|
||
|
||
if !errors.Is(err, errInvalidWastebinResponse) {
|
||
t.Errorf("expected errInvalidWastebinResponse, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_EmptyPathStringResponse(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": ""}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for empty path string response")
|
||
}
|
||
|
||
if !errors.Is(err, errInvalidWastebinResponse) {
|
||
t.Errorf("expected errInvalidWastebinResponse, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_TitleInBody(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
var capturedTitle any
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err := json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
capturedTitle = req["title"]
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/TITLE"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
title := "My Test Paste"
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Title: &title,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.ID != "TITLE" {
|
||
t.Errorf("expected ID TITLE, got %q", resp.ID)
|
||
}
|
||
|
||
if capturedTitle != "My Test Paste" {
|
||
t.Errorf("expected title 'My Test Paste', got %v", capturedTitle)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_BurnAfterReadingInBody(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
var capturedBurn any
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err := json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
capturedBurn = req["burn_after_reading"]
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/BURN"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
burn := true
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
BurnAfterReading: &burn,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.ID != "BURN" {
|
||
t.Errorf("expected ID BURN, got %q", resp.ID)
|
||
}
|
||
|
||
if capturedBurn != true {
|
||
t.Errorf("expected burn_after_reading=true, got %v", capturedBurn)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_DefaultExpiresInBody(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
var capturedExpires any
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err := json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
capturedExpires = req["expires"]
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/EXP"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
// No Expires set — should use default (31536000)
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.ID != "EXP" {
|
||
t.Errorf("expected ID EXP, got %q", resp.ID)
|
||
}
|
||
|
||
if capturedExpires != float64(31536000) {
|
||
t.Errorf("expected default expires 31536000, got %v", capturedExpires)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_TitleOmittedWhenNil(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
var capturedTitle any
|
||
|
||
hasTitleKey := false
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err := json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
_, hasTitleKey = req["title"]
|
||
capturedTitle = req["title"]
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/NOTITLE"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
// No Title set — should not be in JSON body
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if hasTitleKey {
|
||
t.Error("expected title key to be omitted from JSON body when Title is nil")
|
||
}
|
||
|
||
if capturedTitle != nil {
|
||
t.Errorf("expected nil title, got %v", capturedTitle)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileReadDisabled_RejectsFilePath(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
cfg.FileReadEnabled = false
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
filePath := "/tmp/test.txt"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &filePath,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error when FileReadEnabled=false, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errFileReadDisabled) {
|
||
t.Errorf("expected errFileReadDisabled, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileReadDisabled_AllowsContent(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/CONTENT"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.FileReadEnabled = false
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test content"
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.ID != "CONTENT" {
|
||
t.Errorf("expected ID CONTENT, got %q", resp.ID)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileReadDisabled_RejectsBothContentAndFilePath(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
cfg.FileReadEnabled = false
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
filePath := "/tmp/test.txt"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
FilePath: &filePath,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
// Mutual exclusivity check takes priority over file read disabled check.
|
||
if !errors.Is(err, errBothContentAndFilePath) {
|
||
t.Errorf("expected errBothContentAndFilePath, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_OpenError(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
filePath := filepath.Join(allowedDir, "noread.txt")
|
||
|
||
err = os.WriteFile(filePath, []byte("content"), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Remove read permission — os.Open should fail with EACCES while
|
||
// validateFilePath (EvalSymlinks) still succeeds.
|
||
err = os.Chmod(filePath, 0o000)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Verify we aren't running as root (which ignores permissions).
|
||
f, openErr := os.Open(filePath) //nolint:gosec // Test helper — intentional unreadable file
|
||
if openErr == nil {
|
||
_ = f.Close() //nolint:errcheck // Best-effort close before skip
|
||
|
||
t.Skip("skipping: running as root — permission checks are bypassed")
|
||
}
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &filePath,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for unopenable file")
|
||
}
|
||
|
||
if !errors.Is(err, errFilePathCannotBeUsed) {
|
||
t.Errorf("expected errFilePathCannotBeUsed, got: %v", err)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_FileMode_NonRegularFileRejected(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
fifoPath := filepath.Join(allowedDir, "nonregular.fifo")
|
||
|
||
err = syscall.Mkfifo(fifoPath, 0o600)
|
||
if err != nil {
|
||
t.Skipf("skipping: cannot create FIFO: %v", err)
|
||
}
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
FilePath: &fifoPath,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for non-regular file (FIFO)")
|
||
}
|
||
|
||
if !errors.Is(err, errFilePathCannotBeUsed) {
|
||
t.Errorf("expected errFilePathCannotBeUsed, got: %v", err)
|
||
}
|
||
}
|
||
|
||
// TestCreatePaste_SymlinkSwapRace verifies that a post-validation symlink
|
||
// swap does not cause blocked-directory content to be uploaded. An attacker
|
||
// goroutine rapidly flips the victim file between a regular file (with
|
||
// allowed content) and a symlink to a blocked-path file. Under the old code
|
||
// (os.Open without O_NOFOLLOW) this would occasionally read blocked content;
|
||
// under the fix the fd-based openat+O_NOFOLLOW traversal only ever reads the
|
||
// original file or fails with an error — blocked content is never uploaded.
|
||
//
|
||
//nolint:paralleltest // Uses shared filesystem; goroutine coordination relies on global state
|
||
func TestCreatePaste_SymlinkSwapRace(t *testing.T) {
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
blockedDir := filepath.Join(tmpDir, "blocked")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
err = os.Mkdir(blockedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Write blocked content that must never reach the server.
|
||
blockedContent := "BLOCKED-SECRET-DATA-" + t.Name()
|
||
|
||
blockedFile := filepath.Join(blockedDir, "secret.txt")
|
||
|
||
err = os.WriteFile(blockedFile, []byte(blockedContent), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Allowed file content.
|
||
realContent := "allowed-public-content-" + t.Name()
|
||
|
||
victimFile := filepath.Join(allowedDir, "victim.txt")
|
||
|
||
// Start with the real file.
|
||
err = os.WriteFile(victimFile, []byte(realContent), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
var (
|
||
mu sync.Mutex
|
||
blockedObserved bool
|
||
)
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
_ = json.NewDecoder(r.Body).Decode(&req) //nolint:errcheck // Test helper — best-effort decode
|
||
|
||
if text, ok := req["text"].(string); ok {
|
||
mu.Lock()
|
||
if text == blockedContent {
|
||
blockedObserved = true
|
||
}
|
||
mu.Unlock()
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/RESULT.txt"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
ctx, cancel := context.WithCancel(context.Background())
|
||
defer cancel()
|
||
|
||
// Attacker goroutine: rapidly flips the victim file between a regular
|
||
// file and a symlink to the blocked file. The rapid switching creates
|
||
// a realistic TOCTOU window between validateFilePath and the open call.
|
||
go func() {
|
||
for {
|
||
select {
|
||
case <-ctx.Done():
|
||
return
|
||
default:
|
||
}
|
||
|
||
// Replace with symlink.
|
||
_ = os.Remove(victimFile) //nolint:errcheck // Test helper — best-effort
|
||
_ = os.Symlink(blockedFile, victimFile) //nolint:errcheck // Test helper — best-effort
|
||
|
||
// Swap back to regular file.
|
||
_ = os.Remove(victimFile) //nolint:errcheck // Test helper — best-effort
|
||
_ = os.WriteFile(victimFile, []byte(realContent), 0o600) //nolint:errcheck // Test helper — best-effort
|
||
}
|
||
}()
|
||
|
||
// Run many CreatePaste attempts. Statistically, some will hit the
|
||
// window where validateFilePath sees the real file but open sees
|
||
// the symlink. With O_NOFOLLOW, those attempts simply fail — the
|
||
// blocked content is never read.
|
||
for range 200 {
|
||
fp := victimFile
|
||
|
||
_, _ = client.CreatePaste(ctx, &CreatePasteArgs{ //nolint:errcheck // Test helper — errors expected
|
||
FilePath: &fp,
|
||
})
|
||
}
|
||
|
||
cancel()
|
||
|
||
mu.Lock()
|
||
if blockedObserved {
|
||
t.Error("blocked content was uploaded — symlink swap protection failed")
|
||
}
|
||
mu.Unlock()
|
||
}
|
||
|
||
// TestCreatePaste_SymlinkSwapRace_NoAllowedPaths tests the case where
|
||
// ALLOWED_PATHS is empty and an intermediate directory (flipDir) is rapidly
|
||
// swapped between a real directory and a symlink to a blocked directory. The
|
||
// openat+O_NOFOLLOW walk from / must reject the swapped intermediate component
|
||
// (ELOOP) rather than follow it to the blocked directory.
|
||
//
|
||
//nolint:paralleltest // Uses shared filesystem; goroutine coordination
|
||
func TestCreatePaste_SymlinkSwapRace_NoAllowedPaths(t *testing.T) {
|
||
tmpDir := t.TempDir()
|
||
|
||
flipDir := filepath.Join(tmpDir, "flip")
|
||
blockedDir := filepath.Join(tmpDir, "blocked")
|
||
|
||
err := os.MkdirAll(flipDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
err = os.MkdirAll(blockedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
targetFile := "victim.txt"
|
||
safeContent := "safe-data-" + t.Name()
|
||
blockedContent := "BLOCKED-SECRET-" + t.Name()
|
||
|
||
// Same filename in both directories — if the symlink is followed, the
|
||
// blocked file with the same name would be opened.
|
||
err = os.WriteFile(filepath.Join(flipDir, targetFile), []byte(safeContent), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
err = os.WriteFile(filepath.Join(blockedDir, targetFile), []byte(blockedContent), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
victimPath := filepath.Join(flipDir, targetFile)
|
||
|
||
var (
|
||
mu sync.Mutex
|
||
blockedObserved bool
|
||
)
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
_ = json.NewDecoder(r.Body).Decode(&req) //nolint:errcheck // Test helper — best-effort decode
|
||
|
||
if text, ok := req["text"].(string); ok {
|
||
mu.Lock()
|
||
if text == blockedContent {
|
||
blockedObserved = true
|
||
}
|
||
mu.Unlock()
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/RESULT.txt"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.BlockedPaths = []blockedPathEntry{blockedEntry(blockedDir)}
|
||
// AllowedPaths is deliberately empty — exercises the no-ALLOWED_PATHS
|
||
// branch of openFileResolved which walks from / with openat+O_NOFOLLOW.
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
ctx, cancel := context.WithCancel(context.Background())
|
||
|
||
var racerDone sync.WaitGroup
|
||
|
||
racerDone.Add(1)
|
||
|
||
// Attacker goroutine: rapidly flips flipDir between a real directory
|
||
// (containing the safe victim.txt) and a symlink to blockedDir (which
|
||
// also contains a victim.txt with blocked content). A TOCTOU window
|
||
// exists between validateFilePath (which calls EvalSymlinks) and the
|
||
// openat+O_NOFOLLOW walk.
|
||
//nolint:modernize // sync.WaitGroup.Go doesn't exist; plain go+Add pattern
|
||
go func() {
|
||
defer racerDone.Done()
|
||
|
||
for {
|
||
select {
|
||
case <-ctx.Done():
|
||
return
|
||
default:
|
||
}
|
||
|
||
_ = os.RemoveAll(flipDir) //nolint:errcheck // Test helper — best-effort
|
||
_ = os.Symlink(blockedDir, flipDir) //nolint:errcheck // Test helper — best-effort
|
||
_ = os.RemoveAll(flipDir) //nolint:errcheck // Test helper — best-effort
|
||
_ = os.MkdirAll(flipDir, 0o750) //nolint:errcheck // Test helper — best-effort
|
||
_ = os.WriteFile( //nolint:errcheck,nolintlint,gosec // Test helper
|
||
filepath.Join(flipDir, targetFile),
|
||
[]byte(safeContent), 0o600,
|
||
)
|
||
}
|
||
}()
|
||
|
||
for range 200 {
|
||
fp := victimPath
|
||
|
||
_, _ = client.CreatePaste(ctx, &CreatePasteArgs{ //nolint:errcheck // Test helper — errors expected
|
||
FilePath: &fp,
|
||
})
|
||
}
|
||
|
||
cancel()
|
||
racerDone.Wait()
|
||
|
||
mu.Lock()
|
||
if blockedObserved {
|
||
t.Error("blocked content was uploaded — intermediate symlink swap protection failed")
|
||
}
|
||
mu.Unlock()
|
||
}
|
||
|
||
// TestCreatePaste_FileMode_PostReadSizeCheck_Race verifies that the
|
||
// post-read size check catches files that grow between f.Stat() and
|
||
// io.ReadAll. A concurrent writer rapidly toggles the file between
|
||
// MaxContentSize bytes and 3×MaxContentSize bytes, so that some
|
||
// CreatePaste calls will see fi.Size() ≤ MaxContentSize (pre-check
|
||
// passes) but then actually read more (post-check catches).
|
||
//
|
||
//nolint:paralleltest // Shared filesystem; goroutine coordination
|
||
func TestCreatePaste_FileMode_PostReadSizeCheck_Race(t *testing.T) {
|
||
tmpDir := t.TempDir()
|
||
|
||
allowedDir := filepath.Join(tmpDir, "allowed")
|
||
|
||
err := os.Mkdir(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
filePath := filepath.Join(allowedDir, "growing.txt")
|
||
maxSize := int64(50)
|
||
|
||
smallContent := make([]byte, maxSize)
|
||
|
||
err = os.WriteFile(filePath, smallContent, 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
var (
|
||
mu sync.Mutex
|
||
oversizeUploaded bool
|
||
errContentTooLarge bool
|
||
)
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
_ = json.NewDecoder(r.Body).Decode(&req) //nolint:errcheck // Test helper — best-effort decode
|
||
|
||
if text, ok := req["text"].(string); ok {
|
||
mu.Lock()
|
||
if int64(len(text)) > maxSize {
|
||
oversizeUploaded = true
|
||
}
|
||
mu.Unlock()
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/RESULT.txt"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
cfg.AllowedPaths = []string{allowedDir}
|
||
cfg.MaxContentSize = maxSize
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
ctx, cancel := context.WithCancel(context.Background())
|
||
defer cancel()
|
||
|
||
// Writer goroutine: rapidly toggle file size between small and large.
|
||
largeContent := make([]byte, maxSize*3)
|
||
|
||
go func() {
|
||
for {
|
||
select {
|
||
case <-ctx.Done():
|
||
return
|
||
default:
|
||
}
|
||
|
||
_ = os.WriteFile(filePath, largeContent, 0o600) //nolint:errcheck // Test helper — best-effort
|
||
_ = os.WriteFile(filePath, smallContent, 0o600) //nolint:errcheck // Test helper — best-effort
|
||
}
|
||
}()
|
||
|
||
for range 500 {
|
||
fp := filePath
|
||
|
||
_, err := client.CreatePaste(ctx, &CreatePasteArgs{
|
||
FilePath: &fp,
|
||
})
|
||
if err != nil && strings.Contains(err.Error(), "content exceeds the maximum allowed size") {
|
||
mu.Lock()
|
||
errContentTooLarge = true
|
||
mu.Unlock()
|
||
}
|
||
}
|
||
|
||
cancel()
|
||
|
||
mu.Lock()
|
||
if oversizeUploaded {
|
||
t.Error("content exceeding MaxContentSize was uploaded — post-read size check race protection failed")
|
||
}
|
||
|
||
if !errContentTooLarge {
|
||
t.Log("warning: race window not hit in 500 iterations; post-read size check not verified (non-deterministic)")
|
||
}
|
||
mu.Unlock()
|
||
}
|
||
|
||
// TestCreatePaste_FileMode_AllowedRootParentSymlinkSwap verifies that an
|
||
// ALLOWED_PATHS parent-directory symlink swap does NOT cause blocked content
|
||
// to be uploaded. Unlike the race-based tests (which rely on timing), this
|
||
// test is deterministic: the symlink swap happens BEFORE openFileResolved is
|
||
// called. findAllowedRoot performs string-based matching and still considers
|
||
// the path allowed, but the openat+O_NOFOLLOW walk from / rejects the
|
||
// symlinked intermediate component with ELOOP, causing openFileResolved to
|
||
// fail rather than follow the symlink to the blocked tree.
|
||
//
|
||
//nolint:paralleltest // Uses shared filesystem
|
||
func TestCreatePaste_FileMode_AllowedRootParentSymlinkSwap(t *testing.T) {
|
||
tmpDir := t.TempDir()
|
||
|
||
// Directory structure:
|
||
// real-parent/allowed/victim.txt (safe — should be readable)
|
||
// blocked-parent/allowed/victim.txt (should never be read)
|
||
realParentDir := filepath.Join(tmpDir, "real-parent")
|
||
blockedParentDir := filepath.Join(tmpDir, "blocked-parent")
|
||
allowedDir := filepath.Join(realParentDir, "allowed")
|
||
blockedAllowedDir := filepath.Join(blockedParentDir, "allowed")
|
||
|
||
err := os.MkdirAll(allowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
err = os.MkdirAll(blockedAllowedDir, 0o750)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
safeContent := "safe-content-" + t.Name()
|
||
blockedContent := "BLOCKED-SECRET-" + t.Name()
|
||
|
||
victimFile := filepath.Join(allowedDir, "victim.txt")
|
||
blockedVictim := filepath.Join(blockedAllowedDir, "victim.txt")
|
||
|
||
err = os.WriteFile(victimFile, []byte(safeContent), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
err = os.WriteFile(blockedVictim, []byte(blockedContent), 0o600)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// The resolved path as computed by validateFilePath while real-parent is real.
|
||
resolvedPath := victimFile
|
||
|
||
// Now swap real-parent to a symlink to blocked-parent.
|
||
// After this swap, resolvedPath is no longer reachable via the real
|
||
// filesystem — instead, walking resolvedPath would end up at blockedVictim.
|
||
err = os.RemoveAll(realParentDir)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
err = os.Symlink(blockedParentDir, realParentDir)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
|
||
// Call openFileResolved with allowedPaths set to the original allowed dir.
|
||
// findAllowedRoot uses string matching and still accepts resolvedPath.
|
||
// But the openat+O_NOFOLLOW walk from / will fail on the "real-parent"
|
||
// component because it is now a symlink. The test asserts an error.
|
||
f, openErr := openFileResolved(resolvedPath, []string{allowedDir})
|
||
if openErr == nil {
|
||
_ = f.Close() //nolint:errcheck // Cleanup; not relevant to the assertion
|
||
|
||
t.Fatal("expected error after parent-directory symlink swap, got nil")
|
||
}
|
||
|
||
// Also verify: if we bypass the regex test and try to open resolvedPath
|
||
// directly through openFileResolved a second time, it should also fail
|
||
// for the same reason (intermediate component is a symlink).
|
||
f2, openErr2 := openFileResolved(resolvedPath, []string{allowedDir})
|
||
if openErr2 == nil {
|
||
_ = f2.Close() //nolint:errcheck // Cleanup
|
||
|
||
t.Error("expected error even on second call — symlink should still be rejected")
|
||
}
|
||
}
|
||
|
||
func TestNormalizeExtension(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
tests := []struct {
|
||
name string
|
||
input string
|
||
want string
|
||
wantErr bool
|
||
}{
|
||
{name: "plain md", input: "md", want: "md"},
|
||
{name: "dot md", input: ".md", want: "md"},
|
||
{name: "double dot md", input: "..md", want: "md"},
|
||
{name: "uppercase MD", input: "MD", want: "md"},
|
||
{name: "mixed case", input: "MarkDown", want: "markdown"},
|
||
{name: "dot uppercase", input: ".MD", want: "md"},
|
||
{name: "with whitespace", input: " md ", want: "md"},
|
||
{name: "dot markdown", input: ".markdown", want: "markdown"},
|
||
{name: "go", input: "go", want: "go"},
|
||
{name: "dot go", input: ".go", want: "go"},
|
||
{name: "dots only", input: "...", want: ""},
|
||
{name: "space only", input: " ", want: ""},
|
||
{name: "empty string", input: "", want: ""},
|
||
{name: "path separator slash", input: "a/b", wantErr: true},
|
||
{name: "path separator backslash", input: "a\\b", wantErr: true},
|
||
{name: "query char", input: "md?refresh", wantErr: true},
|
||
{name: "fragment char", input: "md#section", wantErr: true},
|
||
}
|
||
|
||
for _, tt := range tests {
|
||
t.Run(tt.name, func(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
got, err := normalizeExtension(tt.input)
|
||
|
||
if tt.wantErr {
|
||
if err == nil {
|
||
t.Fatal("expected error, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errInvalidExtension) {
|
||
t.Errorf("expected errInvalidExtension, got %v", err)
|
||
}
|
||
|
||
return
|
||
}
|
||
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if got != tt.want {
|
||
t.Errorf("normalizeExtension(%q) = %q, want %q", tt.input, got, tt.want)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_MarkdownRendered_WithDotExtension(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err := json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
if req["extension"] != "md" {
|
||
t.Errorf("expected extension 'md' after normalization, got %v", req["extension"])
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/DOTMD.md"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "# Dot"
|
||
ext := ".md"
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Extension: &ext,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.MarkdownRendered != "/md/DOTMD.md" {
|
||
t.Errorf("expected MarkdownRendered '/md/DOTMD.md', got %q", resp.MarkdownRendered)
|
||
}
|
||
|
||
if resp.URL != "/DOTMD.md" {
|
||
t.Errorf("expected URL without double dot, got %q", resp.URL)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_MarkdownRendered_WithUppercaseExtension(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var req map[string]any
|
||
|
||
err := json.NewDecoder(r.Body).Decode(&req)
|
||
if err != nil {
|
||
t.Fatalf("failed to decode request: %v", err)
|
||
}
|
||
|
||
if req["extension"] != "md" {
|
||
t.Errorf("expected extension 'md' after normalization, got %v", req["extension"])
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
_ = json.NewEncoder(w).Encode(map[string]string{"path": "/UCMD.md"}) //nolint:errcheck // Test helper OK
|
||
}))
|
||
defer server.Close()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = server.URL
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "# UC"
|
||
ext := "MD"
|
||
|
||
resp, err := client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Extension: &ext,
|
||
})
|
||
if err != nil {
|
||
t.Fatalf("unexpected error: %v", err)
|
||
}
|
||
|
||
if resp.MarkdownRendered != "/md/UCMD.md" {
|
||
t.Errorf("expected MarkdownRendered '/md/UCMD.md', got %q", resp.MarkdownRendered)
|
||
}
|
||
}
|
||
|
||
func TestCreatePaste_InvalidExtension_Rejected(t *testing.T) {
|
||
t.Parallel()
|
||
|
||
cfg := DefaultConfig()
|
||
cfg.ServerURL = "http://localhost:12345"
|
||
|
||
client, err := NewWastebinClient(cfg)
|
||
if err != nil {
|
||
t.Fatalf("failed to create client: %v", err)
|
||
}
|
||
|
||
content := "test"
|
||
badExt := "a/b"
|
||
|
||
_, err = client.CreatePaste(context.Background(), &CreatePasteArgs{
|
||
Content: &content,
|
||
Extension: &badExt,
|
||
})
|
||
if err == nil {
|
||
t.Fatal("expected error for invalid extension, got nil")
|
||
}
|
||
|
||
if !errors.Is(err, errInvalidExtension) {
|
||
t.Errorf("expected errInvalidExtension, got: %v", err)
|
||
}
|
||
}
|