From 9c13c5283d4b38295ee6d9e021a2c68ca9cc0077 Mon Sep 17 00:00:00 2001 From: tchivert Date: Tue, 20 Oct 2026 15:06:01 +0200 Subject: [PATCH 1/6] Security, performance and UX improvements Security: - Add HTTP server timeouts (ReadTimeout, WriteTimeout, IdleTimeout) - Add http.MaxBytesReader to limit POST body size before parsing - Fix file permissions to 0600 for paste files - Add TCP connection limit (--max-conns, default 100) - Fix purge localhost check using net.SplitHostPort (was broken for IPv6) - Add rate limiting with golang.org/x/time/rate (--rate-limit) - Fix concurrent purge race with sync.Mutex + atomic.Bool - Docker: run as non-root user, pin base images Performance: - Add Cache-Control headers for static assets (index.html, favicon) - Add graceful shutdown on SIGTERM/SIGINT - Use filepath.Join instead of string concatenation for paths Observability: - Add structured logging with log/slog (replaces log.Printf) - Add Prometheus metrics endpoint (--metrics-addr) - Add /health endpoint for health checks - Metrics: pastes, bytes, HTTP requests, TCP connections, purges, removes UX: - Fix hardcoded HTTP link to HTTPS in index.html - Fix mobile textarea min-height (560px -> 40vh, with media queries) - Add responsive styles for small screens (max-width: 600px) Code quality: - Fix double strings.Split in handleRemove - Update Go version to 1.22 - Update Dockerfile: golang:1.22-alpine, alpine:3.19 - Add go.sum with pinned dependencies - Update README with new flags and security/monitoring docs --- Dockerfile | 14 +- README.md | 30 +++- go.mod | 17 +- go.sum | 22 +++ index.html | 29 +++- tbin.go | 485 ++++++++++++++++++++++++++++++++++++++++++----------- 6 files changed, 487 insertions(+), 110 deletions(-) create mode 100644 go.sum diff --git a/Dockerfile b/Dockerfile index 19d7e1e..6399a67 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,20 +1,24 @@ -FROM golang AS build +FROM golang:1.22-alpine AS build WORKDIR /build -COPY go.mod ./ +COPY go.mod go.sum* ./ RUN go mod download COPY *.go ./ RUN CGO_ENABLED=0 GOOS=linux go build -o tbin . -FROM alpine +FROM alpine:3.19 + +RUN addgroup -S tbin && adduser -S tbin -G tbin WORKDIR /app COPY --from=build /build/tbin ./ -COPY index.html ./ -COPY favicon.png ./ +COPY --chown=tbin:tbin index.html ./ +COPY --chown=tbin:tbin favicon.png ./ + +USER tbin EXPOSE 4242 EXPOSE 8080 diff --git a/README.md b/README.md index ca8060c..fd9c94b 100644 --- a/README.md +++ b/README.md @@ -53,8 +53,36 @@ tbin can be configured using command-line flags when starting the application. - `--chunk`: Chunk size in bytes for reading data (default: 8192). - `--conn-time`: Connection timeout in seconds (default: 10). - `--read-time`: Read timeout in seconds (default: 2). -- `--verbose`: Enable verbose logging (default: false). +- `--verbose`: Enable verbose (debug-level) logging (default: false). - `--plaintext`: Only allow plaintext snippets (default: false). +- `--max-conns`: Maximum concurrent TCP connections (default: 100). +- `--rate-limit`: Max requests per second per IP, 0 to disable (default: 10). +- `--metrics-addr`: Prometheus metrics listen address, empty to disable (default: ""). + +## Monitoring + +tbin exposes Prometheus metrics when `--metrics-addr` is set. Available metrics: + +- `tbin_pastes_total`: Total pastes created +- `tbin_pastes_bytes_total`: Total bytes of pastes created +- `tbin_http_requests_total`: HTTP requests by method, path, and status +- `tbin_tcp_connections_total`: Total TCP connections accepted +- `tbin_tcp_active_connections`: Current active TCP connections +- `tbin_purge_runs_total`: Total purge operations executed +- `tbin_purge_files_total`: Files processed during purge by result +- `tbin_removes_total`: Total manual remove requests + +A `/health` endpoint is also available on the HTTP port for health checks. + +## Security + +- HTTP server has read/write/idle timeouts to prevent slowloris attacks +- Request body size is limited via `http.MaxBytesReader` +- TCP connections are rate-limited and capped with `--max-conns` +- Paste files are created with 0600 permissions +- The `/purge` endpoint is restricted to localhost +- Security headers (CSP, X-Frame-Options, etc.) are set on all responses +- Graceful shutdown on SIGTERM/SIGINT ## License diff --git a/go.mod b/go.mod index d03b1bc..71976c8 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,18 @@ module tbin -go 1.19 +go 1.22 + +require ( + github.com/prometheus/client_golang v1.19.0 + golang.org/x/time v0.5.0 +) + +require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/prometheus/client_model v0.5.0 // indirect + github.com/prometheus/common v0.48.0 // indirect + github.com/prometheus/procfs v0.12.0 // indirect + golang.org/x/sys v0.16.0 // indirect + google.golang.org/protobuf v1.32.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..afdc8f0 --- /dev/null +++ b/go.sum @@ -0,0 +1,22 @@ +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/prometheus/client_golang v1.19.0 h1:ygXvpU1AoN1MhdzckN+PyD9QJOSD4x7kmXYlnfbA6JU= +github.com/prometheus/client_golang v1.19.0/go.mod h1:ZRM9uEAypZakd+q/x7+gmsvXdURP+DABIEIjnmDdp+k= +github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw= +github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI= +github.com/prometheus/common v0.48.0 h1:QO8U2CdOzSn1BBsmXJXduaaW+dY/5QLjfB8svtSzKKE= +github.com/prometheus/common v0.48.0/go.mod h1:0/KsvlIEfPQCQ5I2iNSAWKPZziNCvRs5EC6ILDTlAPc= +github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo= +github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= +golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= +golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I= +google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= diff --git a/index.html b/index.html index 1cda42c..8a9283f 100644 --- a/index.html +++ b/index.html @@ -57,7 +57,7 @@ .paste-panel textarea { box-sizing: border-box; width: 100%; - min-height: 560px; + min-height: 40vh; resize: vertical; background-color: #424242; color: #fff; @@ -191,6 +191,31 @@ .privacy-panel .input { width: 100%; } + .paste-panel textarea { + min-height: 30vh; + } + } + + @media (max-width: 600px) { + body { + margin: 15px; + } + h1 { + font-size: 28px; + } + h2 { + font-size: 22px; + } + .paste-panel textarea { + min-height: 25vh; + } + .paste-panel .button { + width: 100%; + padding: 10px; + } + .privacy-panel .button { + width: 100%; + } } @@ -198,7 +223,7 @@
-

Telnet Pastebin

+

Telnet Pastebin

source

A simple pastebin you can use from your terminal

Usage

diff --git a/tbin.go b/tbin.go index c361a66..561fbfc 100644 --- a/tbin.go +++ b/tbin.go @@ -1,20 +1,29 @@ package main import ( + "context" "crypto/sha256" "errors" "flag" "fmt" "io" - "log" + "log/slog" "net" "net/http" "os" + "os/signal" "path/filepath" "strconv" "strings" + "sync" + "sync/atomic" + "syscall" "time" "unicode/utf8" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "golang.org/x/time/rate" ) var ( @@ -30,82 +39,201 @@ var ( ttl = flag.Int("ttl", 48, "Time-to-live in hours for the snippets") verbose = flag.Bool("verbose", false, "Verbose output") plaintext = flag.Bool("plaintext", false, "Only allow plaintext snippets") + maxConns = flag.Int("max-conns", 100, "Maximum concurrent TCP connections") + rateLimit = flag.Int("rate-limit", 10, "Max requests per second per IP (0 to disable)") + metricsAddr = flag.String("metrics-addr", "", "Prometheus metrics listen address (empty to disable)") ) +var ( + logger *slog.Logger + connSem chan struct{} + activeConns atomic.Int64 + purgeMu sync.Mutex + purgeRunning atomic.Bool + tcpLimiter *rate.Limiter + httpLimiter *rate.Limiter + + metricPastesTotal prometheus.Counter + metricPastesBytes prometheus.Counter + metricHTTPRequests *prometheus.CounterVec + metricTCPConnections prometheus.Counter + metricActiveConns prometheus.Gauge + metricPurgeRuns prometheus.Counter + metricPurgeFilesTotal *prometheus.CounterVec + metricRemovesTotal prometheus.Counter +) + +func initMetrics() { + metricPastesTotal = prometheus.NewCounter(prometheus.CounterOpts{ + Name: "tbin_pastes_total", + Help: "Total number of pastes created", + }) + metricPastesBytes = prometheus.NewCounter(prometheus.CounterOpts{ + Name: "tbin_pastes_bytes_total", + Help: "Total bytes of pastes created", + }) + metricHTTPRequests = prometheus.NewCounterVec(prometheus.CounterOpts{ + Name: "tbin_http_requests_total", + Help: "Total HTTP requests by method and path", + }, []string{"method", "path", "status"}) + metricTCPConnections = prometheus.NewCounter(prometheus.CounterOpts{ + Name: "tbin_tcp_connections_total", + Help: "Total TCP connections accepted", + }) + metricActiveConns = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "tbin_tcp_active_connections", + Help: "Current active TCP connections", + }) + metricPurgeRuns = prometheus.NewCounter(prometheus.CounterOpts{ + Name: "tbin_purge_runs_total", + Help: "Total purge operations executed", + }) + metricPurgeFilesTotal = prometheus.NewCounterVec(prometheus.CounterOpts{ + Name: "tbin_purge_files_total", + Help: "Files processed during purge by result", + }, []string{"result"}) + metricRemovesTotal = prometheus.NewCounter(prometheus.CounterOpts{ + Name: "tbin_removes_total", + Help: "Total manual remove requests", + }) + + prometheus.MustRegister( + metricPastesTotal, + metricPastesBytes, + metricHTTPRequests, + metricTCPConnections, + metricActiveConns, + metricPurgeRuns, + metricPurgeFilesTotal, + metricRemovesTotal, + ) +} + func main() { flag.Parse() - // Validate and normalize configuration + logLevel := slog.LevelInfo + if *verbose { + logLevel = slog.LevelDebug + } + logger = slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: logLevel})) + slog.SetDefault(logger) + + initMetrics() + *buff *= 1024 * 1024 if *buff <= 0 { - log.Fatal("Buffer size must be positive") + logger.Error("buffer size must be positive") + os.Exit(1) } if *chunkSize <= 0 { - log.Fatal("Chunk size must be positive") + logger.Error("chunk size must be positive") + os.Exit(1) } if *connTimeout <= 0 { - log.Fatal("Connection timeout must be positive") + logger.Error("connection timeout must be positive") + os.Exit(1) } if *readTimeout <= 0 { - log.Fatal("Read timeout must be positive") + logger.Error("read timeout must be positive") + os.Exit(1) } if *ttl <= 0 { - log.Fatal("TTL must be positive") + logger.Error("TTL must be positive") + os.Exit(1) + } + + if *maxConns <= 0 { + logger.Error("max connections must be positive") + os.Exit(1) } if !strings.HasSuffix(*httpURL, "/") { *httpURL += "/" } - // Validate and create data directory if *dir == "" { - log.Fatal("Data directory cannot be empty") + logger.Error("data directory cannot be empty") + os.Exit(1) } - // Use absolute path for data directory to prevent path traversal absDir, err := filepath.Abs(*dir) if err != nil { - log.Fatalf("Error getting absolute path for data directory: %v", err) + logger.Error("error getting absolute path for data directory", "error", err) + os.Exit(1) } *dir = absDir if err := os.MkdirAll(*dir, 0700); err != nil { - log.Fatalf("Error creating data directory %s: %v", *dir, err) + logger.Error("error creating data directory", "dir", *dir, "error", err) + os.Exit(1) } - log.Printf("Starting tbin with data directory: %s", *dir) - log.Printf("Buffer size: %d MB", *buff/1024/1024) - log.Printf("TTL: %d hours", *ttl) + connSem = make(chan struct{}, *maxConns) - go listenTCP() - listenHTTP() + if *rateLimit > 0 { + tcpLimiter = rate.NewLimiter(rate.Limit(*rateLimit), *rateLimit*2) + httpLimiter = rate.NewLimiter(rate.Limit(*rateLimit), *rateLimit*2) + } + + logger.Info("starting tbin", + "data_dir", *dir, + "buffer_mb", *buff/1024/1024, + "ttl_hours", *ttl, + "max_conns", *maxConns, + "rate_limit", *rateLimit, + ) + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + go listenTCP(ctx) + + if *metricsAddr != "" { + go listenMetrics(ctx) + } + + listenHTTP(ctx) } -func listenTCP() { +func listenTCP(ctx context.Context) { l, err := net.Listen("tcp", *connHost+":"+*connPort) if err != nil { - log.Fatalf("Error listening: %v", err) + logger.Error("error listening TCP", "error", err) + os.Exit(1) } defer l.Close() - log.Printf("Listening on %s:%s for TCP connections", *connHost, *connPort) + + go func() { + <-ctx.Done() + l.Close() + }() + + logger.Info("listening for TCP connections", "addr", *connHost+":"+*connPort) for { conn, err := l.Accept() if err != nil { - log.Printf("Error accepting: %v", err) - continue + select { + case <-ctx.Done(): + return + default: + logger.Error("error accepting TCP connection", "error", err) + continue + } } + metricTCPConnections.Inc() go handleTCP(conn) } } -func listenHTTP() { - // Set up security headers middleware - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - // Security headers +func listenHTTP(ctx context.Context) { + mux := http.NewServeMux() + + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Frame-Options", "DENY") w.Header().Set("X-XSS-Protection", "1; mode=block") @@ -115,96 +243,237 @@ func listenHTTP() { handleHTTP(w, r) }) - log.Printf("Listening on %s:%s for HTTP connections", *connHost, *httpPort) - err := http.ListenAndServe(*connHost+":"+*httpPort, nil) - if err != nil { - log.Fatalf("Error listening: %v", err) + mux.Handle("/metrics", promhttp.Handler()) + + mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"status":"ok"}`)) + }) + + server := &http.Server{ + Addr: *connHost + ":" + *httpPort, + Handler: mux, + ReadTimeout: 10 * time.Second, + WriteTimeout: 30 * time.Second, + IdleTimeout: 60 * time.Second, } + + go func() { + <-ctx.Done() + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + server.Shutdown(shutdownCtx) + }() + + logger.Info("listening for HTTP connections", "addr", *connHost+":"+*httpPort) + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + logger.Error("error listening HTTP", "error", err) + os.Exit(1) + } +} + +func listenMetrics(ctx context.Context) { + mux := http.NewServeMux() + mux.Handle("/metrics", promhttp.Handler()) + + server := &http.Server{ + Addr: *metricsAddr, + Handler: mux, + ReadTimeout: 5 * time.Second, + WriteTimeout: 10 * time.Second, + IdleTimeout: 30 * time.Second, + } + + go func() { + <-ctx.Done() + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + server.Shutdown(shutdownCtx) + }() + + logger.Info("listening for metrics", "addr", *metricsAddr) + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + logger.Error("error listening metrics", "error", err) + } +} + +func getClientIP(r *http.Request) string { + if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" { + parts := strings.Split(fwd, ",") + return strings.TrimSpace(parts[0]) + } + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + return host +} + +func isLocalhost(addr string) bool { + host, _, err := net.SplitHostPort(addr) + if err != nil { + host = addr + } + return host == "127.0.0.1" || host == "::1" || host == "localhost" } func handleHTTP(w http.ResponseWriter, r *http.Request) { if *verbose { - log.Printf("HTTP %s %s %s", r.RemoteAddr, r.Method, r.URL.Path) + logger.Debug("http request", "remote", r.RemoteAddr, "method", r.Method, "path", r.URL.Path) + } + + if httpLimiter != nil { + if !httpLimiter.Allow() { + metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "429").Inc() + http.Error(w, "Too many requests", http.StatusTooManyRequests) + return + } } - // Security: Prevent path traversal attacks id := strings.TrimPrefix(r.URL.Path, "/") if strings.Contains(id, "..") || strings.Contains(id, "/") { + metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "400").Inc() http.Error(w, "Invalid path", http.StatusBadRequest) return } switch r.Method { case "POST": + r.Body = http.MaxBytesReader(w, r.Body, int64(*buff)+1024) + switch id { case "paste": data := r.FormValue("paste") if data == "" { + metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "400").Inc() http.Error(w, "Empty data", http.StatusBadRequest) return } if len(data) > *buff { + metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "413").Inc() http.Error(w, "Data too large", http.StatusRequestEntityTooLarge) return } - id = handleData([]byte(data)) - if id == "" { + newID := handleData([]byte(data)) + if newID == "" { + metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "500").Inc() http.Error(w, "Error generating file", http.StatusInternalServerError) return } - http.Redirect(w, r, "/"+id, http.StatusSeeOther) + metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "303").Inc() + http.Redirect(w, r, "/"+newID, http.StatusSeeOther) case "remove": - id = r.FormValue("remove") - if id != "" { - go handleRemove(id) + removeID := r.FormValue("remove") + if removeID != "" { + metricRemovesTotal.Inc() + go handleRemove(removeID) } + metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "303").Inc() http.Redirect(w, r, "/", http.StatusSeeOther) + default: + metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "404").Inc() + http.Error(w, "Not found", http.StatusNotFound) } case "GET": switch { case id == "": - id = "index.html" - w.Header().Set("Content-Type", "text/html") + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "public, max-age=3600") + serveFile(w, "index.html") + metricHTTPRequests.WithLabelValues(r.Method, "/", "200").Inc() case strings.HasPrefix(id, "favicon"): - id = "favicon.png" w.Header().Set("Content-Type", "image/png") + w.Header().Set("Cache-Control", "public, max-age=86400") + serveFile(w, "favicon.png") + metricHTTPRequests.WithLabelValues(r.Method, "/favicon", "200").Inc() case id == "example": w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Write([]byte("Hello there\n")) + metricHTTPRequests.WithLabelValues(r.Method, "/example", "200").Inc() return case id == "purge": - // Security: Only allow purge from localhost or add authentication - if r.RemoteAddr != "[::1]:" && !strings.HasPrefix(r.RemoteAddr, "127.0.0.1:") { - log.Printf("Unauthorized purge attempt from %s", r.RemoteAddr) + if !isLocalhost(r.RemoteAddr) { + logger.Warn("unauthorized purge attempt", "remote", r.RemoteAddr) + metricHTTPRequests.WithLabelValues(r.Method, "/purge", "401").Inc() http.Error(w, "Unauthorized", http.StatusUnauthorized) return } - log.Printf("Purge requested from %s", r.RemoteAddr) + logger.Info("purge requested", "remote", r.RemoteAddr) + metricHTTPRequests.WithLabelValues(r.Method, "/purge", "200").Inc() go handlePurge() w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Write([]byte("OK\n")) return + case id == "health": + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"status":"ok"}`)) + metricHTTPRequests.WithLabelValues(r.Method, "/health", "200").Inc() + return default: w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("X-Robots-Tag", "noindex,nofollow") - id = *dir + "/" + id + ".txt" + filename := filepath.Join(*dir, id+".txt") + f, err := os.Open(filename) + if err != nil { + metricHTTPRequests.WithLabelValues(r.Method, "paste", "404").Inc() + http.Error(w, "Not found", http.StatusNotFound) + return + } + defer f.Close() + metricHTTPRequests.WithLabelValues(r.Method, "paste", "200").Inc() + io.CopyN(w, f, int64(*buff)) } - f, err := os.Open(id) - if err != nil { - http.Error(w, "Not found", http.StatusNotFound) - return - } - defer f.Close() - io.CopyN(w, f, int64(*buff)) + default: + metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "405").Inc() + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } } -func handleTCP(conn net.Conn) { - defer conn.Close() +func serveFile(w http.ResponseWriter, name string) { + f, err := os.Open(name) + if err != nil { + http.Error(w, "Not found", http.StatusNotFound) + return + } + defer f.Close() + io.Copy(w, f) +} - // Rate limiting: limit concurrent connections per IP +func handleTCP(conn net.Conn) { remoteAddr := conn.RemoteAddr().String() - log.Printf("TCP %s connection", remoteAddr) + + select { + case connSem <- struct{}{}: + defer func() { <-connSem }() + default: + logger.Warn("max connections reached, rejecting", "remote", remoteAddr) + conn.Write([]byte("Error: server busy, try again later\n")) + conn.Close() + return + } + + active := activeConns.Add(1) + metricActiveConns.Set(float64(active)) + defer func() { + activeConns.Add(-1) + metricActiveConns.Set(float64(activeConns.Load())) + conn.Close() + }() + + if tcpLimiter != nil { + host, _, err := net.SplitHostPort(remoteAddr) + if err != nil { + host = remoteAddr + } + if !tcpLimiter.Allow() { + logger.Warn("rate limit exceeded", "remote", remoteAddr) + conn.Write([]byte("Error: rate limit exceeded, slow down\n")) + return + } + _ = host + } + + logger.Debug("tcp connection", "remote", remoteAddr) buf := make([]byte, *chunkSize) var data []byte @@ -216,7 +485,7 @@ func handleTCP(conn net.Conn) { n, err := conn.Read(buf) if err != nil { if err != io.EOF { - log.Printf("Error reading from %s: %v", remoteAddr, err) + logger.Debug("error reading from tcp", "remote", remoteAddr, "error", err) } break } @@ -224,7 +493,7 @@ func handleTCP(conn net.Conn) { dataLen += n if dataLen >= *buff { - log.Printf("Buffer limit exceeded from %s: %d bytes", remoteAddr, dataLen) + logger.Warn("buffer limit exceeded", "remote", remoteAddr, "bytes", dataLen) conn.Write([]byte("Warning: " + strconv.Itoa(*buff/1024/1024) + "MB limit exceeded\n")) break } @@ -233,15 +502,14 @@ func handleTCP(conn net.Conn) { } if dataLen == 0 { - log.Printf("No data received from %s", remoteAddr) + logger.Debug("no data received", "remote", remoteAddr) conn.Write([]byte("Error: no data received\n")) return } if *plaintext { - err := checkData(data) - if err != nil { - log.Printf("Invalid data from %s: %v", remoteAddr, err) + if err := checkData(data); err != nil { + logger.Warn("invalid data", "remote", remoteAddr, "error", err) conn.Write([]byte("Error: " + err.Error() + "\n")) return } @@ -249,12 +517,12 @@ func handleTCP(conn net.Conn) { id := handleData(data) if id == "" { - log.Printf("Error generating file for %s", remoteAddr) + logger.Error("error generating file", "remote", remoteAddr) conn.Write([]byte("Error generating file\n")) return } - log.Printf("TCP %s %d %s.txt", remoteAddr, dataLen, id) + logger.Info("tcp paste created", "remote", remoteAddr, "bytes", dataLen, "id", id) conn.Write([]byte(*httpURL + id + "\n")) time.Sleep(100 * time.Millisecond) } @@ -264,7 +532,6 @@ func checkData(data []byte) error { return errors.New("only plain text data is allowed") } - // Additional validation: check for control characters (except newline) for _, b := range data { if b < 32 && b != '\n' && b != '\t' && b != '\r' { return errors.New("control characters are not allowed") @@ -278,43 +545,42 @@ func handleData(data []byte) string { var id string for l := 6; l <= 16; l++ { id = generateId(data, l) - if _, err := os.Stat(*dir + "/" + id + ".txt"); os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(*dir, id+".txt")); os.IsNotExist(err) { break } id = "" } if id == "" { - log.Println("Error no available id found") + logger.Error("no available id found") return "" } - // Validate ID format if !isAlphanumeric(id) { - log.Printf("Error invalid ID format: %s", id) + logger.Error("invalid ID format", "id", id) return "" } - filename := *dir + "/" + id + ".txt" - f, err := os.Create(filename) + filename := filepath.Join(*dir, id+".txt") + f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600) if err != nil { - log.Printf("Error creating file %s: %v", filename, err) + logger.Error("error creating file", "file", filename, "error", err) return "" } defer f.Close() - // Ensure data ends with newline if len(data) > 0 && data[len(data)-1] != '\n' { data = append(data, '\n') } - _, err = f.Write(data) - if err != nil { - log.Printf("Error writing to file %s: %v", filename, err) - // Try to clean up the empty file + if _, err := f.Write(data); err != nil { + logger.Error("error writing to file", "file", filename, "error", err) os.Remove(filename) return "" } + metricPastesTotal.Inc() + metricPastesBytes.Add(float64(len(data))) + return id } @@ -337,41 +603,53 @@ func isAlphanumeric(id string) bool { } func handleRemove(id string) { - // Extract ID from URL or direct input - id = strings.TrimPrefix(strings.Split(id, "/")[len(strings.Split(id, "/"))-1], "/") + parts := strings.Split(id, "/") + id = strings.TrimPrefix(parts[len(parts)-1], "/") - // Validate ID format if id == "" || len(id) > 16 || !isAlphanumeric(id) { - log.Printf("Error invalid id to remove: %s", id) + logger.Warn("invalid id to remove", "id", id) return } - filename := *dir + "/" + id + ".txt" + filename := filepath.Join(*dir, id+".txt") - // Check if file exists before attempting to remove if _, err := os.Stat(filename); os.IsNotExist(err) { - log.Printf("File not found for removal: %s", filename) + logger.Debug("file not found for removal", "file", filename) return } - err := os.Remove(filename) - if err != nil { - log.Printf("Error removing file %s: %v", filename, err) + if err := os.Remove(filename); err != nil { + logger.Error("error removing file", "file", filename, "error", err) } else { - log.Printf("File removed: %s", filename) + logger.Info("file removed", "file", filename) + metricRemovesTotal.Inc() } } func handlePurge() { + if !purgeMu.TryLock() { + logger.Debug("purge already running, skipping") + return + } + defer purgeMu.Unlock() + + if !purgeRunning.CompareAndSwap(false, true) { + logger.Debug("purge already in progress, skipping") + return + } + defer purgeRunning.Store(false) + + metricPurgeRuns.Inc() + logger.Info("purge started") + files, err := os.ReadDir(*dir) if err != nil { - log.Printf("Error reading data directory: %v", err) + logger.Error("error reading data directory", "error", err) + metricPurgeFilesTotal.WithLabelValues("error").Inc() return } - var filesRemoved int - var filesSkipped int - var errorsEncountered int + var filesRemoved, filesSkipped, errorsEncountered int for _, file := range files { if file.IsDir() { @@ -379,7 +657,6 @@ func handlePurge() { continue } - // Only process .txt files if !strings.HasSuffix(file.Name(), ".txt") { filesSkipped++ continue @@ -387,23 +664,29 @@ func handlePurge() { info, err := file.Info() if err != nil { - log.Printf("Error getting file info for %s: %v", file.Name(), err) + logger.Error("error getting file info", "file", file.Name(), "error", err) errorsEncountered++ + metricPurgeFilesTotal.WithLabelValues("error").Inc() continue } if time.Since(info.ModTime()) > time.Duration(*ttl)*time.Hour { - filename := *dir + "/" + file.Name() - err = os.Remove(filename) - if err != nil { - log.Printf("Error removing file %s: %v", filename, err) + filename := filepath.Join(*dir, file.Name()) + if err := os.Remove(filename); err != nil { + logger.Error("error removing file", "file", filename, "error", err) errorsEncountered++ + metricPurgeFilesTotal.WithLabelValues("error").Inc() } else { filesRemoved++ - log.Printf("File removed: %s", filename) + logger.Debug("file removed", "file", filename) + metricPurgeFilesTotal.WithLabelValues("removed").Inc() } } } - log.Printf("Purge done: %d files removed, %d files skipped, %d errors", filesRemoved, filesSkipped, errorsEncountered) + logger.Info("purge done", + "removed", filesRemoved, + "skipped", filesSkipped, + "errors", errorsEncountered, + ) } -- 2.54.1 From 1ff7e9dc1ee5f2b4bce979e15a488b1b1bfbeef2 Mon Sep 17 00:00:00 2001 From: tchivert Date: Tue, 20 Oct 2026 15:11:59 +0200 Subject: [PATCH 2/6] Bump Go to 1.27 and Alpine to 3.24 - go.mod: go 1.22 -> go 1.27 - Dockerfile: golang:1.22-alpine -> golang:1.27-alpine - Dockerfile: alpine:3.19 -> alpine:3.24 - README: update Go version requirement --- Dockerfile | 4 ++-- README.md | 2 +- go.mod | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index 6399a67..b910bb3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.22-alpine AS build +FROM golang:1.27-alpine AS build WORKDIR /build @@ -8,7 +8,7 @@ RUN go mod download COPY *.go ./ RUN CGO_ENABLED=0 GOOS=linux go build -o tbin . -FROM alpine:3.19 +FROM alpine:3.24 RUN addgroup -S tbin && adduser -S tbin -G tbin diff --git a/README.md b/README.md index fd9c94b..b1b935b 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ tbin is a simple pastebin application that allows you to store and share text sn Before building and starting tbin, ensure that you have the following software installed on your system: - Docker -- Go (if you want to build the application from source) +- Go 1.27+ (if you want to build the application from source) ## Building from source diff --git a/go.mod b/go.mod index 71976c8..429208b 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module tbin -go 1.22 +go 1.27 require ( github.com/prometheus/client_golang v1.19.0 -- 2.54.1 From 699409096d098785bd4ac00aabb15ebc8274e3ea Mon Sep 17 00:00:00 2001 From: tchivert Date: Tue, 20 Oct 2026 15:13:51 +0200 Subject: [PATCH 3/6] Update CI pipeline --- .gitea/workflows/build.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index c53cc41..9282889 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -9,7 +9,7 @@ jobs: build: runs-on: ubuntu-latest container: - image: catthehacker/ubuntu:act-latest + image: registry.rznet.fr/tchivert/ubuntu:act-latest steps: - name: Checkout uses: actions/checkout@v3 @@ -17,10 +17,10 @@ jobs: fetch-depth: 0 # all history for all branches and tags - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 + uses: docker/setup-buildx-action@v4 - name: Login to registry - uses: docker/login-action@v2 + uses: docker/login-action@v4 with: registry: git.rznet.fr username: ${{ secrets.DOCKER_USERNAME }} -- 2.54.1 From 7d25ef3804ca0c4f718be4f7608b2dd6939ad245 Mon Sep 17 00:00:00 2001 From: tchivert Date: Thu, 22 Oct 2026 13:38:19 +0200 Subject: [PATCH 4/6] Address review feedback: fix blockers and non-blocking issues Blockers fixed: - Docker: create /app/data with tbin ownership, use named volume in docker-compose (was: bind mount broke non-root user, MkdirAll failed on startup) - Remove /metrics from main HTTP mux (was: exposed publicly even when --metrics-addr empty) - Implement per-IP rate limiting with ipLimiter (map + cleanup goroutine) (was: single global limiter, docs said per-IP but wasn't) - Fix Prometheus label cardinality: use fixed endpoint labels instead of r.URL.Path (was: unbounded memory growth from unique paths as labels) Non-blocking fixes: - Remove redundant purgeRunning atomic.Bool (keep only purgeMu.TryLock) - Remove dead code: getClientIP (replaced by getRemoteIP), unreachable health case in handleHTTP, _ = host in TCP limiter - Fix MaxBytesReader/413: use r.ParseForm() to detect body-too-large errors properly - Track TCP handlers and async operations with sync.WaitGroup for graceful shutdown - CI: add test job with go build, vet, gofmt check, go test before Docker build - CI: bump actions/checkout to v4, add PR trigger - docker-compose: use named volume tbin-data instead of bind mount - Dockerfile: pin tbin user to UID 1000, add VOLUME /app/data - README: document non-root user, named volume, per-IP rate limiting All checks pass: go build, go vet, gofmt -l --- .gitea/workflows/build.yml | 32 ++++++- Dockerfile | 6 +- README.md | 17 ++-- docker-compose.yml | 5 +- tbin.go | 170 +++++++++++++++++++++++-------------- 5 files changed, 159 insertions(+), 71 deletions(-) diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 9282889..7cc53cf 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -4,15 +4,45 @@ on: push: branches: - "main" + - "security-performance-improvements" + pull_request: + branches: + - "main" jobs: + test: + runs-on: ubuntu-latest + container: + image: golang:1.27-alpine + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: go mod download + run: go mod download + + - name: go build + run: go build -v ./... + + - name: go vet + run: go vet ./... + + - name: gofmt check + run: test -z "$(gofmt -l .)" || (echo "gofmt issues found:" && gofmt -l . && exit 1) + + - name: go test + run: go test -v ./... + build: + needs: test runs-on: ubuntu-latest container: image: registry.rznet.fr/tchivert/ubuntu:act-latest steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 # all history for all branches and tags diff --git a/Dockerfile b/Dockerfile index b910bb3..24ef699 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ RUN CGO_ENABLED=0 GOOS=linux go build -o tbin . FROM alpine:3.24 -RUN addgroup -S tbin && adduser -S tbin -G tbin +RUN addgroup -S tbin && adduser -S -u 1000 -G tbin tbin WORKDIR /app @@ -18,8 +18,12 @@ COPY --from=build /build/tbin ./ COPY --chown=tbin:tbin index.html ./ COPY --chown=tbin:tbin favicon.png ./ +RUN mkdir -p /app/data && chown tbin:tbin /app/data + USER tbin +VOLUME /app/data + EXPOSE 4242 EXPOSE 8080 diff --git a/README.md b/README.md index b1b935b..32569e6 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ tbin can also be started using Docker. To do this, follow these steps: 4. Start the application using Docker Compose: `docker-compose up -d` 5. tbin will be started as a Docker container and will be accessible via telnet and HTTP. +The Docker container runs as a non-root user (UID 1000) and uses a named volume (`tbin-data`) for data persistence. + ## Usage To submit a text snippet using the telnet interface, follow these steps: @@ -36,7 +38,7 @@ To submit a text snippet using the telnet interface, follow these steps: 2. Use the `nc` command to connect to the tbin server: `echo "Your text snippet" | nc localhost 4242` 3. The server will generate a unique URL for your text snippet, which will be displayed in the terminal. -Purges can be trigged with the `/purge` endpoint. +Purges can be trigged with the `/purge` endpoint (localhost only). It will remove all snippets olders than the configuered TTL (default: 48 hours). ## Configuration @@ -61,11 +63,11 @@ tbin can be configured using command-line flags when starting the application. ## Monitoring -tbin exposes Prometheus metrics when `--metrics-addr` is set. Available metrics: +tbin exposes Prometheus metrics when `--metrics-addr` is set. The metrics server runs on a separate port and is not exposed on the main HTTP port. Available metrics: - `tbin_pastes_total`: Total pastes created - `tbin_pastes_bytes_total`: Total bytes of pastes created -- `tbin_http_requests_total`: HTTP requests by method, path, and status +- `tbin_http_requests_total`: HTTP requests by method, endpoint, and status - `tbin_tcp_connections_total`: Total TCP connections accepted - `tbin_tcp_active_connections`: Current active TCP connections - `tbin_purge_runs_total`: Total purge operations executed @@ -78,11 +80,14 @@ A `/health` endpoint is also available on the HTTP port for health checks. - HTTP server has read/write/idle timeouts to prevent slowloris attacks - Request body size is limited via `http.MaxBytesReader` -- TCP connections are rate-limited and capped with `--max-conns` -- Paste files are created with 0600 permissions +- TCP connections are rate-limited per-IP and capped with `--max-conns` +- HTTP requests are rate-limited per-IP +- Paste files are created with 0600 permissions and O_EXCL to prevent races - The `/purge` endpoint is restricted to localhost - Security headers (CSP, X-Frame-Options, etc.) are set on all responses -- Graceful shutdown on SIGTERM/SIGINT +- Graceful shutdown on SIGTERM/SIGINT with WaitGroup tracking of in-flight requests +- Docker container runs as non-root user (UID 1000) +- Docker base images are pinned (golang:1.27-alpine, alpine:3.24) ## License diff --git a/docker-compose.yml b/docker-compose.yml index db3b037..6447c08 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,6 +7,9 @@ services: image: git.rznet.fr/tchivert/tbin restart: always volumes: - - ./data:/app/data + - tbin-data:/app/data command: - --http-url=http://localhost:8080/ + +volumes: + tbin-data: diff --git a/tbin.go b/tbin.go index 561fbfc..d78656e 100644 --- a/tbin.go +++ b/tbin.go @@ -45,13 +45,11 @@ var ( ) var ( - logger *slog.Logger - connSem chan struct{} - activeConns atomic.Int64 - purgeMu sync.Mutex - purgeRunning atomic.Bool - tcpLimiter *rate.Limiter - httpLimiter *rate.Limiter + logger *slog.Logger + connSem chan struct{} + activeConns atomic.Int64 + wg sync.WaitGroup + purgeMu sync.Mutex metricPastesTotal prometheus.Counter metricPastesBytes prometheus.Counter @@ -63,6 +61,53 @@ var ( metricRemovesTotal prometheus.Counter ) +type ipLimiter struct { + mu sync.Mutex + limiters map[string]*rate.Limiter + limit rate.Limit + burst int +} + +func newIPLimiter(limit rate.Limit, burst int) *ipLimiter { + il := &ipLimiter{ + limiters: make(map[string]*rate.Limiter), + limit: limit, + burst: burst, + } + go il.cleanup() + return il +} + +func (il *ipLimiter) get(ip string) *rate.Limiter { + il.mu.Lock() + defer il.mu.Unlock() + l, ok := il.limiters[ip] + if !ok { + l = rate.NewLimiter(il.limit, il.burst) + il.limiters[ip] = l + } + return l +} + +func (il *ipLimiter) cleanup() { + ticker := time.NewTicker(10 * time.Minute) + defer ticker.Stop() + for range ticker.C { + il.mu.Lock() + for ip, l := range il.limiters { + if l.Tokens() == float64(il.burst) { + delete(il.limiters, ip) + } + } + il.mu.Unlock() + } +} + +var ( + httpIPLimiter *ipLimiter + tcpIPLimiter *ipLimiter +) + func initMetrics() { metricPastesTotal = prometheus.NewCounter(prometheus.CounterOpts{ Name: "tbin_pastes_total", @@ -74,8 +119,8 @@ func initMetrics() { }) metricHTTPRequests = prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "tbin_http_requests_total", - Help: "Total HTTP requests by method and path", - }, []string{"method", "path", "status"}) + Help: "Total HTTP requests by method, endpoint, and status", + }, []string{"method", "endpoint", "status"}) metricTCPConnections = prometheus.NewCounter(prometheus.CounterOpts{ Name: "tbin_tcp_connections_total", Help: "Total TCP connections accepted", @@ -176,8 +221,8 @@ func main() { connSem = make(chan struct{}, *maxConns) if *rateLimit > 0 { - tcpLimiter = rate.NewLimiter(rate.Limit(*rateLimit), *rateLimit*2) - httpLimiter = rate.NewLimiter(rate.Limit(*rateLimit), *rateLimit*2) + httpIPLimiter = newIPLimiter(rate.Limit(*rateLimit), *rateLimit*2) + tcpIPLimiter = newIPLimiter(rate.Limit(*rateLimit), *rateLimit*2) } logger.Info("starting tbin", @@ -198,6 +243,9 @@ func main() { } listenHTTP(ctx) + + wg.Wait() + logger.Info("shutdown complete") } func listenTCP(ctx context.Context) { @@ -226,7 +274,11 @@ func listenTCP(ctx context.Context) { } } metricTCPConnections.Inc() - go handleTCP(conn) + wg.Add(1) + go func() { + defer wg.Done() + handleTCP(conn) + }() } } @@ -243,8 +295,6 @@ func listenHTTP(ctx context.Context) { handleHTTP(w, r) }) - mux.Handle("/metrics", promhttp.Handler()) - mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"status":"ok"}`)) @@ -297,23 +347,16 @@ func listenMetrics(ctx context.Context) { } } -func getClientIP(r *http.Request) string { - if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" { - parts := strings.Split(fwd, ",") - return strings.TrimSpace(parts[0]) - } - host, _, err := net.SplitHostPort(r.RemoteAddr) +func getRemoteIP(addr string) string { + host, _, err := net.SplitHostPort(addr) if err != nil { - return r.RemoteAddr + return addr } return host } func isLocalhost(addr string) bool { - host, _, err := net.SplitHostPort(addr) - if err != nil { - host = addr - } + host := getRemoteIP(addr) return host == "127.0.0.1" || host == "::1" || host == "localhost" } @@ -322,9 +365,10 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) { logger.Debug("http request", "remote", r.RemoteAddr, "method", r.Method, "path", r.URL.Path) } - if httpLimiter != nil { - if !httpLimiter.Allow() { - metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "429").Inc() + if httpIPLimiter != nil { + ip := getRemoteIP(r.RemoteAddr) + if !httpIPLimiter.get(ip).Allow() { + metricHTTPRequests.WithLabelValues(r.Method, "rate_limited", "429").Inc() http.Error(w, "Too many requests", http.StatusTooManyRequests) return } @@ -332,7 +376,7 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) { id := strings.TrimPrefix(r.URL.Path, "/") if strings.Contains(id, "..") || strings.Contains(id, "/") { - metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "400").Inc() + metricHTTPRequests.WithLabelValues(r.Method, "invalid_path", "400").Inc() http.Error(w, "Invalid path", http.StatusBadRequest) return } @@ -343,35 +387,49 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) { switch id { case "paste": + if err := r.ParseForm(); err != nil { + metricHTTPRequests.WithLabelValues(r.Method, "paste", "400").Inc() + http.Error(w, "Invalid form data", http.StatusBadRequest) + return + } data := r.FormValue("paste") if data == "" { - metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "400").Inc() + metricHTTPRequests.WithLabelValues(r.Method, "paste", "400").Inc() http.Error(w, "Empty data", http.StatusBadRequest) return } if len(data) > *buff { - metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "413").Inc() + metricHTTPRequests.WithLabelValues(r.Method, "paste", "413").Inc() http.Error(w, "Data too large", http.StatusRequestEntityTooLarge) return } newID := handleData([]byte(data)) if newID == "" { - metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "500").Inc() + metricHTTPRequests.WithLabelValues(r.Method, "paste", "500").Inc() http.Error(w, "Error generating file", http.StatusInternalServerError) return } - metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "303").Inc() + metricHTTPRequests.WithLabelValues(r.Method, "paste", "303").Inc() http.Redirect(w, r, "/"+newID, http.StatusSeeOther) case "remove": + if err := r.ParseForm(); err != nil { + metricHTTPRequests.WithLabelValues(r.Method, "remove", "400").Inc() + http.Error(w, "Invalid form data", http.StatusBadRequest) + return + } removeID := r.FormValue("remove") if removeID != "" { metricRemovesTotal.Inc() - go handleRemove(removeID) + wg.Add(1) + go func() { + defer wg.Done() + handleRemove(removeID) + }() } - metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "303").Inc() + metricHTTPRequests.WithLabelValues(r.Method, "remove", "303").Inc() http.Redirect(w, r, "/", http.StatusSeeOther) default: - metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "404").Inc() + metricHTTPRequests.WithLabelValues(r.Method, "not_found", "404").Inc() http.Error(w, "Not found", http.StatusNotFound) } case "GET": @@ -380,35 +438,34 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "public, max-age=3600") serveFile(w, "index.html") - metricHTTPRequests.WithLabelValues(r.Method, "/", "200").Inc() + metricHTTPRequests.WithLabelValues(r.Method, "index", "200").Inc() case strings.HasPrefix(id, "favicon"): w.Header().Set("Content-Type", "image/png") w.Header().Set("Cache-Control", "public, max-age=86400") serveFile(w, "favicon.png") - metricHTTPRequests.WithLabelValues(r.Method, "/favicon", "200").Inc() + metricHTTPRequests.WithLabelValues(r.Method, "favicon", "200").Inc() case id == "example": w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Write([]byte("Hello there\n")) - metricHTTPRequests.WithLabelValues(r.Method, "/example", "200").Inc() + metricHTTPRequests.WithLabelValues(r.Method, "example", "200").Inc() return case id == "purge": if !isLocalhost(r.RemoteAddr) { logger.Warn("unauthorized purge attempt", "remote", r.RemoteAddr) - metricHTTPRequests.WithLabelValues(r.Method, "/purge", "401").Inc() + metricHTTPRequests.WithLabelValues(r.Method, "purge", "401").Inc() http.Error(w, "Unauthorized", http.StatusUnauthorized) return } logger.Info("purge requested", "remote", r.RemoteAddr) - metricHTTPRequests.WithLabelValues(r.Method, "/purge", "200").Inc() - go handlePurge() + metricHTTPRequests.WithLabelValues(r.Method, "purge", "200").Inc() + wg.Add(1) + go func() { + defer wg.Done() + handlePurge() + }() w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Write([]byte("OK\n")) return - case id == "health": - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"status":"ok"}`)) - metricHTTPRequests.WithLabelValues(r.Method, "/health", "200").Inc() - return default: w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("X-Robots-Tag", "noindex,nofollow") @@ -424,7 +481,7 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) { io.CopyN(w, f, int64(*buff)) } default: - metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "405").Inc() + metricHTTPRequests.WithLabelValues(r.Method, "method_not_allowed", "405").Inc() http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } } @@ -460,17 +517,13 @@ func handleTCP(conn net.Conn) { conn.Close() }() - if tcpLimiter != nil { - host, _, err := net.SplitHostPort(remoteAddr) - if err != nil { - host = remoteAddr - } - if !tcpLimiter.Allow() { + if tcpIPLimiter != nil { + ip := getRemoteIP(remoteAddr) + if !tcpIPLimiter.get(ip).Allow() { logger.Warn("rate limit exceeded", "remote", remoteAddr) conn.Write([]byte("Error: rate limit exceeded, slow down\n")) return } - _ = host } logger.Debug("tcp connection", "remote", remoteAddr) @@ -622,7 +675,6 @@ func handleRemove(id string) { logger.Error("error removing file", "file", filename, "error", err) } else { logger.Info("file removed", "file", filename) - metricRemovesTotal.Inc() } } @@ -633,12 +685,6 @@ func handlePurge() { } defer purgeMu.Unlock() - if !purgeRunning.CompareAndSwap(false, true) { - logger.Debug("purge already in progress, skipping") - return - } - defer purgeRunning.Store(false) - metricPurgeRuns.Inc() logger.Info("purge started") -- 2.54.1 From c400569181b8642e14d64dd4e4e18c37547c1c79 Mon Sep 17 00:00:00 2001 From: tchivert Date: Thu, 22 Oct 2026 13:58:15 +0200 Subject: [PATCH 5/6] Fix CI test job and remaining review nits CI (blocker): - Replace container: golang:1.27-alpine with actions/setup-go@v5 (runner couldn't pull from Docker Hub, job failed in ~1s) - Use go-version-file: go.mod to auto-sync Go version Code nits: - Return proper 413 for oversized bodies using errors.As with http.MaxBytesError (was: always 400 'Invalid form data' when MaxBytesReader triggered) - Apply same 413 handling to /remove endpoint - Add maxIPLimiterEntries=10000 cap to ipLimiter.get() Evicts idle entries when full, returns zero-rate limiter if still full (was: unbounded map growth between 10-min cleanup intervals) All checks pass: go build, go vet, gofmt -l clean --- .gitea/workflows/build.yml | 7 +++++-- tbin.go | 33 +++++++++++++++++++++++++++++---- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 7cc53cf..f108904 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -12,14 +12,17 @@ on: jobs: test: runs-on: ubuntu-latest - container: - image: golang:1.27-alpine steps: - name: Checkout uses: actions/checkout@v4 with: fetch-depth: 0 + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + - name: go mod download run: go mod download diff --git a/tbin.go b/tbin.go index d78656e..0450a42 100644 --- a/tbin.go +++ b/tbin.go @@ -61,6 +61,8 @@ var ( metricRemovesTotal prometheus.Counter ) +const maxIPLimiterEntries = 10000 + type ipLimiter struct { mu sync.Mutex limiters map[string]*rate.Limiter @@ -83,6 +85,17 @@ func (il *ipLimiter) get(ip string) *rate.Limiter { defer il.mu.Unlock() l, ok := il.limiters[ip] if !ok { + if len(il.limiters) >= maxIPLimiterEntries { + for k, v := range il.limiters { + if v.Tokens() == float64(il.burst) { + delete(il.limiters, k) + break + } + } + } + if len(il.limiters) >= maxIPLimiterEntries { + return rate.NewLimiter(rate.Limit(0), 0) + } l = rate.NewLimiter(il.limit, il.burst) il.limiters[ip] = l } @@ -388,8 +401,14 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) { switch id { case "paste": if err := r.ParseForm(); err != nil { - metricHTTPRequests.WithLabelValues(r.Method, "paste", "400").Inc() - http.Error(w, "Invalid form data", http.StatusBadRequest) + var maxErr *http.MaxBytesError + if errors.As(err, &maxErr) { + metricHTTPRequests.WithLabelValues(r.Method, "paste", "413").Inc() + http.Error(w, "Data too large", http.StatusRequestEntityTooLarge) + } else { + metricHTTPRequests.WithLabelValues(r.Method, "paste", "400").Inc() + http.Error(w, "Invalid form data", http.StatusBadRequest) + } return } data := r.FormValue("paste") @@ -413,8 +432,14 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/"+newID, http.StatusSeeOther) case "remove": if err := r.ParseForm(); err != nil { - metricHTTPRequests.WithLabelValues(r.Method, "remove", "400").Inc() - http.Error(w, "Invalid form data", http.StatusBadRequest) + var maxErr *http.MaxBytesError + if errors.As(err, &maxErr) { + metricHTTPRequests.WithLabelValues(r.Method, "remove", "413").Inc() + http.Error(w, "Data too large", http.StatusRequestEntityTooLarge) + } else { + metricHTTPRequests.WithLabelValues(r.Method, "remove", "400").Inc() + http.Error(w, "Invalid form data", http.StatusBadRequest) + } return } removeID := r.FormValue("remove") -- 2.54.1 From 52914207bf75e6c64d6f0bf024a6cddfe88c2296 Mon Sep 17 00:00:00 2001 From: tchivert Date: Thu, 22 Oct 2026 14:05:41 +0200 Subject: [PATCH 6/6] Split CI into separate test and build workflows - test.yml: runs on any push or PR (branches: main) - go build, go vet, gofmt check, go test - Fast feedback on PRs without pushing images - build.yml: runs only on push to main - Builds and pushes Docker image to registry - No longer triggered by PRs or feature branches - Removes 'needs: test' dependency (separate workflows now) This ensures the :latest Docker image is only updated after code is merged to main, not from unvalidated PR branches. --- .gitea/workflows/build.yml | 33 --------------------------------- .gitea/workflows/test.yml | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 33 deletions(-) create mode 100644 .gitea/workflows/test.yml diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index f108904..e1c176a 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -4,42 +4,9 @@ on: push: branches: - "main" - - "security-performance-improvements" - pull_request: - branches: - - "main" jobs: - test: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Set up Go - uses: actions/setup-go@v5 - with: - go-version-file: go.mod - - - name: go mod download - run: go mod download - - - name: go build - run: go build -v ./... - - - name: go vet - run: go vet ./... - - - name: gofmt check - run: test -z "$(gofmt -l .)" || (echo "gofmt issues found:" && gofmt -l . && exit 1) - - - name: go test - run: go test -v ./... - build: - needs: test runs-on: ubuntu-latest container: image: registry.rznet.fr/tchivert/ubuntu:act-latest diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml new file mode 100644 index 0000000..0a5abf5 --- /dev/null +++ b/.gitea/workflows/test.yml @@ -0,0 +1,36 @@ +name: test + +on: + push: + pull_request: + branches: + - "main" + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: go mod download + run: go mod download + + - name: go build + run: go build -v ./... + + - name: go vet + run: go vet ./... + + - name: gofmt check + run: test -z "$(gofmt -l .)" || (echo "gofmt issues found:" && gofmt -l . && exit 1) + + - name: go test + run: go test -v ./... -- 2.54.1