Skip to content

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 if APP_KEY is empty or whitespace-only.
  • boot/server/middleware/auth.go: ValidateAppKeyValue(provided, expected string) uses crypto/subtle.ConstantTimeCompare and rejects empty values.
  • On HTTP, missing/invalid X-App-Key returns 401 UNAUTHORIZED (AppError JSON) and aborts.
  • On gRPC, missing/invalid x-app-key incoming metadata returns codes.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): sets Access-Control-Allow-Origin: * and never sets Access-Control-Allow-Credentials.
  • Explicit comma-separated origins (e.g. https://app.example.com,http://localhost:5173): echoes only exact Origin matches, adds Vary: Origin, and sets Access-Control-Allow-Credentials: true.
  • Allowed headers include X-App-Key, X-Request-ID, Authorization, X-CSRF-Token, and Content-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 by c.ClientIP() (HTTP) or port-stripped peerIP(ctx) (gRPC).
  • Hard cap: 10,000 tracked clients (defaultMaxLimiterClients).
  • Idle eviction: entries idle for 3m (defaultLimiterIdleTTL) are swept every 1 minute; if full, the oldest entry is evicted.
  • Lifecycle: HTTPServer.Stop() and GRPCServer.Stop() call store.Close() to stop the background cleanup goroutine.
  • Exceeded limits return canonical 429 TOO_MANY_REQUESTS (HTTP) or codes.ResourceExhausted (gRPC).

5. RequestID Validation & Generation ​

middleware.RequestID() (boot/server/middleware/request_id.go):

  • Accepts an incoming X-Request-ID header only if it is 1–128 printable non-whitespace ASCII characters (0x21..0x7e).
  • Otherwise generates a 128-bit crypto/rand hex ID (32 chars).
  • Attaches the ID to Gin ("request_id"), the response header X-Request-ID, and c.Request.Context() (middleware.RequestIDFromContext(ctx)).

6. Trusted Proxies, Error Masking & Safe DSNs ​

  • TRUSTED_PROXIES defaults to nil (trusts no X-Forwarded-For headers unless explicitly configured).
  • Recovery() and ErrorHandler() log full stack traces / causes with request_id server-side while returning sanitized 500 INTERNAL_SERVER_ERROR JSON to clients.
  • core/database/dsn.go escapes credentials via mysqldriver.Config.FormatDSN() and url.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 the loader CLI command) and run as non-root appuser in Alpine.

User Authentication ​

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 *string with json:"-", DeletedAt gorm.DeletedAt), Session, Verification, Account.
  • DI Wiring: Initialize limen.New(...) once inside a DI provider receiving *database.Database and *config.AllConfig, mount engine.Any("/api/auth/*action", gin.WrapH(svc.Engine().Handler())), and inject a RequireAuth() middleware calling svc.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.

Released under the Apache-2.0 License.