Add tenant-aware HTTP middleware and router
internal/httpapi/ provides:
- Tenant{UserID, Email} carried on context.Context, with
WithTenant / TenantFrom helpers and ErrNoTenant for the
programming-error case (route reached without middleware).
- AuthMiddleware verifies an Authorization: Bearer <jwt> on every
request via auth.Signer.Verify (which already enforces HS256
and rejects alg=none). On failure: 401, with the underlying
reason logged server-side but not exposed to the client.
- RequireTenantOwnership(ownerID) compares the request's tenant
against the resource owner; returns 403 on mismatch. Handlers
that touch tenant-owned resources call this guard.
- Server.Routes() mounts /auth/* unauthenticated and wraps
/api/* with the middleware. /api/whoami is included as the
canonical example of a tenant-scoped endpoint.
Tests cover: valid JWT pass-through, missing/empty Authorization,
wrong scheme, malformed JWT, tampered signature, JWT signed with
a different secret (cross-tenant key confusion), and the 200/403
matrix for RequireTenantOwnership.
Closes #11.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"git.librete.ch/public/librenotes/internal/auth"
|
||||
)
|
||||
|
||||
// Server wires routes for the multi-tenant backend. The auth endpoints
|
||||
// live under /auth/* and are unauthenticated. Everything under /api/*
|
||||
// is wrapped by AuthMiddleware and receives a Tenant on the context.
|
||||
type Server struct {
|
||||
Auth auth.Handlers
|
||||
Signer *auth.Signer
|
||||
Logger *log.Logger
|
||||
}
|
||||
|
||||
// Routes returns an http.Handler with all routes mounted.
|
||||
func (s *Server) Routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("/auth/login", s.Auth.HandleLogin)
|
||||
mux.HandleFunc("/auth/verify", s.Auth.HandleVerify)
|
||||
|
||||
protected := http.NewServeMux()
|
||||
protected.HandleFunc("/api/whoami", s.handleWhoami)
|
||||
|
||||
mw := AuthMiddleware(s.Signer, s.Logger)
|
||||
mux.Handle("/api/", mw(protected))
|
||||
|
||||
return mux
|
||||
}
|
||||
|
||||
// handleWhoami returns the verified tenant identity. Useful for
|
||||
// frontend session-bootstrapping and as the canonical example of a
|
||||
// tenant-scoped handler.
|
||||
func (s *Server) handleWhoami(w http.ResponseWriter, r *http.Request) {
|
||||
t, err := TenantFrom(r.Context())
|
||||
if err != nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"user_id": t.UserID,
|
||||
"email": t.Email,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user