Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ MAX_REQUEST_BODY_BYTES=10485760
# Token bucket: BURST is the capacity, RPS the sustained refill rate.
RATE_LIMIT_BURST=30
RATE_LIMIT_RPS=10
# Who may say who the client is (X-Forwarded-For): the reverse proxy, or the
# private network the service is published on. Empty trusts nobody, which is
# right when clients connect directly; behind a proxy it makes every client
# share the proxy's one allowance.
TRUSTED_PROXIES=

# --- Logging ------------------------------------------------------------------
LOG_LEVEL=debug
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),

## [Unreleased]

### Security
- **The rate limiter now limits.** It keyed on the client's address *with its port*, which every new connection changes, and believed `X-Forwarded-For` from anyone, which a client can set to anything: either way each request could arrive as a new caller with a full bucket, so password guessing went unthrottled. A caller is now its address without the port (an IPv6 address by its /64), and `X-Forwarded-For` is read only from a trusted proxy, right to left, past every trusted hop. The table is capped (`DefaultMaxClients`, `WithMaxClients`); when full, callers whose bucket has refilled are dropped and new ones share one strict bucket.
- **Behaviour change:** set `TRUSTED_PROXIES` (addresses and CIDR ranges) when running behind a reverse proxy. Left empty, nobody is trusted and every client shares the proxy's one allowance.
- New: `middleware.ClientIP`, `ParseTrustedProxies`, `WithTrustedProxies`, and `RateLimiter.Allow(key)` for limits on something other than an address, such as an account.

### Fixed
- **`internal/testdb`** takes the database lock before migrating, so parallel test packages no longer race on the schema.
- **The logger middleware's response writer** exposes `Unwrap`, so handlers reach the connection behind it (`http.ResponseController`).

### Added
- **Code-First RBAC Engine (`pkg/authz`)**: Multi-tenant-ready Role-Based Access Control system with permission constants, global registry, and runtime GORM DB synchronization.
- **Huma v2 Integration**: Strongly-typed HTTP API framework built on Chi with automated OpenAPI 3.0 specification (`/openapi.json`) and interactive documentation UI (`/docs`).
Expand Down
8 changes: 8 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ type Config struct {
RateLimitBurst float64 // bucket capacity — how large a spike is tolerated
RateLimitRPS float64 // sustained refill rate, requests per second

// TrustedProxies lists the addresses and CIDR ranges allowed to say who
// the client is in X-Forwarded-For, comma-separated. Empty means nobody:
// the connection's own address is the client. Behind a reverse proxy,
// name it (or the private network the service is published on), or
// every client shares the proxy's one allowance.
TrustedProxies string

// DocsEnabled controls whether /docs and /openapi.json are served.
// Defaults to false in production. API endpoints are unaffected either way.
DocsEnabled bool
Expand Down Expand Up @@ -195,6 +202,7 @@ func LoadConfig() (*Config, error) {
// --- Rate limiting ---
cfg.RateLimitBurst = float64(envInt("RATE_LIMIT_BURST", 30))
cfg.RateLimitRPS = float64(envInt("RATE_LIMIT_RPS", 10))
cfg.TrustedProxies = os.Getenv("TRUSTED_PROXIES")

// --- API documentation ---
// Off by default in production; on by default everywhere else. An explicit
Expand Down
7 changes: 6 additions & 1 deletion pkg/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,12 @@ func New(opts Options) (*App, error) {
// Recovery above the handlers so a panic becomes a 500 rather than killing the
// process; rate limiting and the body cap before any handler allocates memory
// on behalf of an unauthenticated caller.
rateLimiter := middleware.NewRateLimiter(cfg.RateLimitBurst, cfg.RateLimitRPS, log)
trusted, err := middleware.ParseTrustedProxies(cfg.TrustedProxies)
if err != nil {
return nil, fmt.Errorf("TRUSTED_PROXIES: %w", err)
}
rateLimiter := middleware.NewRateLimiter(cfg.RateLimitBurst, cfg.RateLimitRPS, log,
middleware.WithTrustedProxies(trusted))

r.Use(middleware.RequestID())
r.Use(middleware.Logger(log))
Expand Down
9 changes: 9 additions & 0 deletions pkg/middleware/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,12 @@ func (lrw *loggingResponseWriter) WriteHeader(code int) {
lrw.statusCode = code
lrw.ResponseWriter.WriteHeader(code)
}

// Unwrap returns the writer underneath, so http.ResponseController can reach
// the connection through this middleware: extend a write deadline, flush,
// take over the connection. Without it every handler behind the logger is
// stuck with the server's WriteTimeout, and a long download (an APK over a
// slow connection takes half an hour) is cut off part way.
func (lrw *loggingResponseWriter) Unwrap() http.ResponseWriter {
return lrw.ResponseWriter
}
46 changes: 46 additions & 0 deletions pkg/middleware/logger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package middleware

import (
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
)

// A handler behind the logger must still be able to extend its own write
// deadline: http.ResponseController finds the connection through Unwrap.
func TestLoggerLetsHandlersReachTheConnection(t *testing.T) {
var deadlineErr, flushErr error
handler := Logger(newDummyLogger())(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rc := http.NewResponseController(w)
deadlineErr = rc.SetWriteDeadline(time.Now().Add(time.Hour))
_, _ = io.WriteString(w, "ok")
flushErr = rc.Flush()
}))

srv := httptest.NewServer(handler)
defer srv.Close()
res, err := http.Get(srv.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()

if deadlineErr != nil {
t.Errorf("SetWriteDeadline through the logger: %v", deadlineErr)
}
if flushErr != nil {
t.Errorf("Flush through the logger: %v", flushErr)
}
}

func TestLoggerRecordsTheStatus(t *testing.T) {
rec := httptest.NewRecorder()
Logger(newDummyLogger())(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTeapot)
})).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
if rec.Code != http.StatusTeapot {
t.Fatalf("got %d", rec.Code)
}
}
Loading
Loading