Security & Authentication
GoForge ships with defense-in-depth defaults across HTTP, gRPC, database DSNs, and container builds.
Built-In Security Hardening
1. Constant-Time X-App-Key Validation & Fail-Closed Startup
core/config:ValidateForServe()blocks server startup ifAPP_KEYis empty or whitespace-only.boot/server/middleware/auth.go:ValidateAppKeyValue(provided, expected string)usescrypto/subtle.ConstantTimeCompareand rejects empty values.- On HTTP, missing/invalid
X-App-Keyreturns401 UNAUTHORIZED(AppErrorJSON) and aborts. - On gRPC, missing/invalid
x-app-keyincoming metadata returnscodes.Unauthenticated.
2. Debug-Gated OpenAPI Documentation
Routes under /api/docs, /openapi, and /docs bypass X-App-Key only when APP_DEBUG=true. When APP_DEBUG=false, OpenAPI endpoints are protected by X-App-Key just like API routes.
3. Strict CORS (CORS_ALLOWED_ORIGINS)
middleware.CORSWithConfig(cfg.HTTP):
- Wildcard (
*or empty): setsAccess-Control-Allow-Origin: *and never setsAccess-Control-Allow-Credentials. - Explicit comma-separated origins (e.g.
https://app.example.com,http://localhost:5173): echoes only exactOriginmatches, addsVary: Origin, and setsAccess-Control-Allow-Credentials: true. - Allowed headers include
X-App-Key,X-Request-ID,Authorization,X-CSRF-Token, andContent-Type.
4. Bounded Memory Rate Limiter (LimiterStore)
middleware.LimiterStore protects against memory exhaustion from spoofed or high-cardinality IPs:
- Token-bucket rate limiter (
golang.org/x/time/rate) keyed byc.ClientIP()(HTTP) or port-strippedpeerIP(ctx)(gRPC). - Hard cap:
10,000tracked clients (defaultMaxLimiterClients). - Idle eviction: entries idle for
3m(defaultLimiterIdleTTL) are swept every 1 minute; if full, the oldest entry is evicted. - Lifecycle:
HTTPServer.Stop()andGRPCServer.Stop()callstore.Close()to stop the background cleanup goroutine. - Exceeded limits return canonical
429 TOO_MANY_REQUESTS(HTTP) orcodes.ResourceExhausted(gRPC).
5. RequestID Validation & Generation
middleware.RequestID() (boot/server/middleware/request_id.go):
- Accepts an incoming
X-Request-IDheader only if it is 1–128 printable non-whitespace ASCII characters (0x21..0x7e). - Otherwise generates a 128-bit
crypto/randhex ID (32 chars). - Attaches the ID to Gin (
"request_id"), the response headerX-Request-ID, andc.Request.Context()(middleware.RequestIDFromContext(ctx)).
6. Trusted Proxies, Error Masking & Safe DSNs
TRUSTED_PROXIESdefaults tonil(trusts noX-Forwarded-Forheaders unless explicitly configured).Recovery()andErrorHandler()log full stack traces / causes withrequest_idserver-side while returning sanitized500 INTERNAL_SERVER_ERRORJSON to clients.core/database/dsn.goescapes credentials viamysqldriver.Config.FormatDSN()andurl.URL/url.UserPassword.
7. TLS & Production Container
- HTTP TLS enforces
MinVersion: tls.VersionTLS12(TLS_ENABLED,TLS_CERT_FILE,TLS_KEY_FILE). - gRPC TLS uses
credentials.NewServerTLSFromFile(GRPC_TLS_ENABLED,GRPC_TLS_CERT_FILE,GRPC_TLS_KEY_FILE). - Generate self-signed dev certs with
.agent/skills/tls/gen-cert.sh. - Production builds use
-tags prod(excluding theloaderCLI command) and run as non-rootappuserin Alpine.
User Authentication
Option A: Limen Session Auth (Recommended)
GoForge ships a .agent/skills/limen-auth/ skill for github.com/thecodearcher/limen with limen/adapters/gorm and limen/plugins/credential-password:
- Endpoints:
POST /api/auth/register,POST /api/auth/login,GET /api/auth/me,POST /api/auth/logout. - Models:
User(Password *stringwithjson:"-",DeletedAt gorm.DeletedAt),Session,Verification,Account. - DI Wiring: Initialize
limen.New(...)once inside a DI provider receiving*database.Databaseand*config.AllConfig, mountengine.Any("/api/auth/*action", gin.WrapH(svc.Engine().Handler())), and inject aRequireAuth()middleware callingsvc.SessionFromRequest(c.Request).
See Chapter 2 of the TaskForge Tutorial for the complete, copy-paste implementation.
Option B: Stateless Bearer / JWT Middleware
If you prefer stateless bearer tokens (e.g., for mobile/CLI clients without cookies), provide a RequireJWT() middleware in internal/services/auth/ that parses Authorization: Bearer <token>, validates the signature against cfg.App.Key, sets "auth_user_id" on *gin.Context, and returns _ = c.Error(apperrors.ErrUnauthorized(...)) on failure.
