Repository Public
1// Package api is the public HTTP API (/api/v1) of control-api.2//3// Security model: the contract (OpenAPI) declares, per operation, which4// credentials are accepted, the permission required and whether a recent5// passkey verification (step-up) is needed. Those declarations are generated6// into Operations and enforced HERE, centrally, before any handler runs.7// Handlers add resource-scoped checks (core.authorize) where a decision8// depends on the specific resource or on request content.9package api1011import (12 "context"13 "encoding/json"14 "errors"15 "net/http"16 "net/http/httputil"17 "net/url"18 "strings"19 "sync"20 "time"2122 "github.com/google/uuid"23 "github.com/jackc/pgx/v5"24 "github.com/jackc/pgx/v5/pgxpool"2526 "clustr.spboucher.ai/mcc/internal/audit"27 "clustr.spboucher.ai/mcc/internal/authz"28 "clustr.spboucher.ai/mcc/internal/config"29 "clustr.spboucher.ai/mcc/internal/events"30 "clustr.spboucher.ai/mcc/internal/httpx"31 "clustr.spboucher.ai/mcc/internal/identity"32)3334// Build information, set by the linker.35var (36 Version = "dev"37 Commit = ""38 BuiltAt = ""39)4041const maxBody = 1 << 204243type Deps struct {44 Pool *pgxpool.Pool45 Cfg *config.Config46 Identity *identity.Service47 Hub *events.Hub48}4950// core is shared by every handler group.51type core struct {52 Deps53 authLimiter *httpx.Limiter // unauthenticated ceremonies, per IP54 userLimiter *httpx.Limiter // authenticated requests, per session55 grantsMu sync.Mutex56 grants []authz.Grant57 grantsAt time.Time58}5960// Server implements StrictServerInterface by composition: each handler group61// provides a subset of the operations; anything not provided answers 501.62type Server struct {63 fallback64 *identityHandlers65 *adminHandlers66 *clusterHandlers67 *opsHandlers68 core *core69}7071type fallback struct{ Unimplemented }7273var _ StrictServerInterface = (*Server)(nil)7475func NewServer(d Deps) *Server {76 c := &core{Deps: d, authLimiter: httpx.NewLimiter(30, 15), userLimiter: httpx.NewLimiter(900, 300)}77 return &Server{core: c, identityHandlers: &identityHandlers{c}, adminHandlers: &adminHandlers{c},78 clusterHandlers: &clusterHandlers{c}, opsHandlers: &opsHandlers{c}}79}8081// ── Request principal ──────────────────────────────────────────────────────8283type principal struct {84 Session *identity.Session85 SessionToken string // clear cookie token (to derive the CSRF token); empty for bearer86 SetupToken string // clear setup-transaction token, when presented87 Policy OpPolicy88 Op string89 w http.ResponseWriter90 r *http.Request91}9293type principalKey struct{}9495func principalFrom(ctx context.Context) *principal {96 p, _ := ctx.Value(principalKey{}).(*principal)97 if p == nil {98 panic("api: handler reached without a principal") // programming error: middleware not installed99 }100 return p101}102103func (c *core) meta(ctx context.Context) identity.ReqMeta {104 m := identity.ReqMeta{Correlation: httpx.Correlation(ctx)}105 if ip, ok := httpx.ClientIP(ctx); ok {106 m.IP = &ip107 }108 if p, _ := ctx.Value(principalKey{}).(*principal); p != nil && p.r != nil {109 m.UserAgent = p.r.UserAgent()110 }111 return m112}113114func (c *core) cookieName(base string) string {115 if c.Cfg.Secure() {116 return "__Host-" + base117 }118 return base // plain-HTTP development: the __Host- prefix requires Secure119}120121func (c *core) setCookie(ctx context.Context, base, value string, maxAge time.Duration) {122 ck := &http.Cookie{Name: c.cookieName(base), Value: value, Path: "/", HttpOnly: true, Secure: c.Cfg.Secure(), SameSite: http.SameSiteStrictMode}123 if value == "" {124 ck.MaxAge = -1125 } else if maxAge > 0 {126 ck.MaxAge = int(maxAge.Seconds())127 }128 http.SetCookie(principalFrom(ctx).w, ck)129}130131func (c *core) readCookie(r *http.Request, base string) string {132 if ck, err := r.Cookie(c.cookieName(base)); err == nil {133 return ck.Value134 }135 return ""136}137138// ── Authorization ──────────────────────────────────────────────────────────139140func (c *core) loadGrants(ctx context.Context) ([]authz.Grant, error) {141 c.grantsMu.Lock()142 defer c.grantsMu.Unlock()143 if time.Since(c.grantsAt) < 3*time.Second && c.grants != nil {144 return c.grants, nil145 }146 rows, err := c.Pool.Query(ctx, `select subject_kind, subject, permission, coalesce(resource_kind,''), coalesce(resource_id,''), effect::text from policy_grants`)147 if err != nil {148 return nil, err149 }150 gs, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (authz.Grant, error) {151 var g authz.Grant152 var perm, eff string153 err := r.Scan(&g.SubjectKind, &g.Subject, &perm, &g.ResourceKind, &g.ResourceID, &eff)154 g.Permission, g.Effect = authz.Permission(perm), authz.Effect(eff)155 return g, err156 })157 if err != nil {158 return nil, err159 }160 if gs == nil {161 gs = []authz.Grant{}162 }163 c.grants, c.grantsAt = gs, time.Now()164 return gs, nil165}166167// invalidateGrants drops the cache after a policy change.168func (c *core) invalidateGrants() {169 c.grantsMu.Lock()170 c.grantsAt = time.Time{}171 c.grantsMu.Unlock()172}173174// can reports whether the session may exercise perm on res (zero res = any).175func (c *core) can(ctx context.Context, sess *identity.Session, perm authz.Permission, res authz.Resource) (bool, error) {176 grants, err := c.loadGrants(ctx)177 if err != nil {178 return false, err179 }180 return authz.Decide(sess.Subject(), perm, res, grants), nil181}182183// authorize is the resource-scoped check used inside handlers. A refusal is184// audited and returned as 403.185func (c *core) authorize(ctx context.Context, perm authz.Permission, res authz.Resource) error {186 p := principalFrom(ctx)187 if p.Session == nil {188 return httpx.ErrUnauthenticated189 }190 ok, err := c.can(ctx, p.Session, perm, res)191 if err != nil {192 return err193 }194 if !ok {195 c.auditDenied(ctx, p, string(perm), res)196 return httpx.ErrForbidden.With("permission", string(perm))197 }198 return nil199}200201// requireStepUp is used by handlers whose need for step-up depends on the request content.202func (c *core) requireStepUp(ctx context.Context) error {203 p := principalFrom(ctx)204 if p.Session == nil {205 return httpx.ErrUnauthenticated206 }207 if !c.Identity.StepUpFresh(p.Session) {208 return httpx.ErrStepUp209 }210 return nil211}212213func (c *core) auditDenied(ctx context.Context, p *principal, perm string, res authz.Resource) {214 e := audit.Entry{ActorKind: "user", Action: "authz.denied", TargetKind: res.Kind, TargetID: res.ID, Outcome: audit.Denied,215 CorrelationID: httpx.Correlation(ctx), Params: map[string]any{"operation": p.Op, "permission": perm}}216 if p.Session != nil {217 e.ActorID, e.ActorLabel, e.SessionID, e.DeviceID = &p.Session.User.ID, p.Session.User.Handle, &p.Session.ID, &p.Session.DeviceID218 }219 if ip, ok := httpx.ClientIP(ctx); ok {220 e.IP = &ip221 }222 audit.Append(ctx, c.Pool, e)223}224225// audit records an action performed by the current principal.226func (c *core) audit(ctx context.Context, db audit.DB, action, targetKind, targetID string, outcome audit.Outcome, detail string, params map[string]any) error {227 p := principalFrom(ctx)228 e := audit.Entry{ActorKind: "system", Action: action, TargetKind: targetKind, TargetID: targetID, Outcome: outcome, Detail: detail,229 Params: params, CorrelationID: httpx.Correlation(ctx)}230 if p.Session != nil {231 e.ActorKind, e.ActorID, e.ActorLabel, e.SessionID, e.DeviceID = "user", &p.Session.User.ID, p.Session.User.Handle, &p.Session.ID, &p.Session.DeviceID232 }233 if ip, ok := httpx.ClientIP(ctx); ok {234 e.IP = &ip235 }236 _, err := audit.Append(ctx, db, e)237 return err238}239240// ── Central enforcement ────────────────────────────────────────────────────241242func safeMethod(m string) bool {243 return m == http.MethodGet || m == http.MethodHead || m == http.MethodOptions244}245246// originOK validates the Origin header of a state-changing browser request.247// Native clients send no Origin; browsers always do on non-GET requests.248func (c *core) originOK(r *http.Request, required bool) bool {249 o := r.Header.Get("Origin")250 if o == "" {251 return !required252 }253 return strings.EqualFold(strings.TrimRight(o, "/"), c.Cfg.PublicOrigin)254}255256// admit authenticates and authorizes a request for the named operation.257func (c *core) admit(w http.ResponseWriter, r *http.Request, op string) (*principal, error) {258 policy, known := Operations[op]259 if !known {260 return nil, errors.New("api: operation " + op + " has no security policy")261 }262 ctx := r.Context()263 p := &principal{Policy: policy, Op: op, w: w, r: r}264 ip, _ := httpx.ClientIP(ctx)265266 // Credentials. An Authorization header takes precedence and disables cookie handling entirely.267 bearer := ""268 if h := r.Header.Get("Authorization"); h != "" {269 tok, ok := strings.CutPrefix(h, "Bearer ")270 if !ok {271 return nil, httpx.ErrUnauthenticated272 }273 bearer = strings.TrimSpace(tok)274 }275 cookieTok := ""276 if bearer == "" {277 cookieTok = c.readCookie(r, "mcc_session")278 }279 p.SetupToken = r.Header.Get("X-MCC-Setup-Transaction")280 setupFromCookie := false281 if p.SetupToken == "" {282 p.SetupToken = c.readCookie(r, "mcc_setup")283 setupFromCookie = p.SetupToken != ""284 }285286 if policy.Auth == AuthPublic || policy.Auth == AuthSetup {287 if ok, wait := c.authLimiter.Allow("pub:" + ip.String()); !ok {288 e := *httpx.ErrRateLimited289 e.RetryAfter = wait290 return nil, &e291 }292 }293294 needSession := policy.Auth == AuthSession || policy.Auth == AuthSessionAndSetup ||295 (policy.Auth == AuthSessionOrSetup && (bearer != "" || cookieTok != "") && p.SetupToken == "")296 if needSession {297 var err error298 switch {299 case bearer != "":300 p.Session, err = c.Identity.Authenticate(ctx, bearer, "bearer")301 case cookieTok != "":302 p.Session, err = c.Identity.Authenticate(ctx, cookieTok, "cookie")303 p.SessionToken = cookieTok304 default:305 err = httpx.ErrUnauthenticated306 }307 if err != nil {308 return nil, err309 }310 if ok, wait := c.userLimiter.Allow("sess:" + p.Session.ID.String()); !ok {311 e := *httpx.ErrRateLimited312 e.RetryAfter = wait313 return nil, &e314 }315 }316 switch policy.Auth {317 case AuthSetup, AuthSessionAndSetup:318 if p.SetupToken == "" {319 return nil, identity.ErrSetupTx320 }321 case AuthSessionOrSetup:322 if p.Session == nil && p.SetupToken == "" {323 return nil, httpx.ErrUnauthenticated324 }325 }326327 // Cross-site request forgery.328 if !safeMethod(r.Method) {329 switch {330 case p.SessionToken != "": // cookie session: Origin must match AND the session-bound token must be present331 if !c.originOK(r, true) || !c.Identity.CheckCSRF(p.SessionToken, r.Header.Get("X-MCC-CSRF")) {332 return nil, httpx.ErrCSRF333 }334 case setupFromCookie: // setup cookie (SameSite=Strict): Origin must match335 if !c.originOK(r, true) {336 return nil, httpx.ErrCSRF337 }338 default: // public or bearer: reject a browser request coming from another origin339 if !c.originOK(r, false) {340 return nil, httpx.ErrCSRF341 }342 }343 }344345 if p.Session != nil {346 if policy.Permission != "" {347 ok, err := c.can(ctx, p.Session, authz.Permission(policy.Permission), authz.Resource{})348 if err != nil {349 return nil, err350 }351 if !ok {352 c.auditDenied(ctx, p, policy.Permission, authz.Resource{})353 return nil, httpx.ErrForbidden.With("permission", policy.Permission)354 }355 }356 if policy.StepUp && !c.Identity.StepUpFresh(p.Session) {357 return nil, httpx.ErrStepUp358 }359 }360 return p, nil361}362363func (s *Server) middleware(next StrictHandlerFunc, op string) StrictHandlerFunc {364 return func(ctx context.Context, w http.ResponseWriter, r *http.Request, request any) (any, error) {365 p, err := s.core.admit(w, r, op)366 if err != nil {367 return nil, err368 }369 return next(context.WithValue(ctx, principalKey{}, p), w, r, request)370 }371}372373// Handler assembles the public HTTP handler: API, event stream, Apple374// association file, and the web application behind everything else.375func (s *Server) Handler() http.Handler {376 c := s.core377 onErr := func(w http.ResponseWriter, r *http.Request, err error) { httpx.WriteError(w, r, err) }378 strict := NewStrictHandlerWithOptions(s, []StrictMiddlewareFunc{s.middleware}, StrictHTTPServerOptions{379 RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) {380 httpx.WriteError(w, r, httpx.Validation("Malformed request: "+firstLine(err.Error())))381 },382 ResponseErrorHandlerFunc: onErr,383 })384 apiMux := http.NewServeMux()385 HandlerWithOptions(strict, StdHTTPServerOptions{BaseURL: "/api/v1", BaseRouter: apiMux,386 ErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) {387 httpx.WriteError(w, r, httpx.Validation("Invalid parameter: "+firstLine(err.Error())))388 }})389390 root := http.NewServeMux()391 root.Handle("/api/v1/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {392 if r.URL.Path == "/api/v1/events" && r.Method == http.MethodGet {393 s.serveEvents(w, r) // streamed outside the generated wrapper so each event is flushed394 return395 }396 if _, pattern := apiMux.Handler(r); pattern == "" {397 httpx.WriteError(w, r, httpx.ErrNotFound)398 return399 }400 r.Body = http.MaxBytesReader(w, r.Body, maxBody)401 w.Header().Set("Cache-Control", "no-store")402 apiMux.ServeHTTP(w, r)403 }))404 root.HandleFunc("GET /.well-known/apple-app-site-association", s.serveAASA)405 root.Handle(agentPrefix, s.agentProxy())406 if c.Cfg.WebUpstream != "" {407 if u, err := url.Parse(c.Cfg.WebUpstream); err == nil {408 rp := httputil.NewSingleHostReverseProxy(u)409 rp.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {410 httpx.WriteError(w, r, httpx.ErrUnavailable)411 }412 root.Handle("/", rp)413 }414 }415 var h http.Handler = root416 h = httpx.SecurityHeaders(c.Cfg.Secure(), h)417 h = httpx.Recover(h)418 h = httpx.AccessLog(h)419 h = httpx.WithRequestContext(c.Cfg.TrustedProxies, h)420 return h421}422423func firstLine(s string) string {424 if i := strings.IndexByte(s, '\n'); i >= 0 {425 s = s[:i]426 }427 if len(s) > 200 {428 s = s[:200]429 }430 return s431}432433// serveAASA publishes the Apple App Site Association file that lets the434// native apps use this domain's passkeys and open its universal links.435func (s *Server) serveAASA(w http.ResponseWriter, r *http.Request) {436 ids := s.core.Cfg.AppleAppIDs437 if ids == nil {438 ids = []string{}439 }440 body := map[string]any{441 "webcredentials": map[string]any{"apps": ids},442 "applinks": map[string]any{"details": []any{map[string]any{443 "appIDs": ids,444 "components": []any{map[string]any{"/": "/setup", "comment": "invitation setup"}, map[string]any{"/": "/open/*", "comment": "deep links"}},445 }}},446 }447 w.Header().Set("Content-Type", "application/json")448 w.Header().Set("Cache-Control", "public, max-age=3600")449 json.NewEncoder(w).Encode(body)450}451452func ptr[T any](v T) *T { return &v }453454func corr(ctx context.Context) *uuid.UUID { id := httpx.Correlation(ctx); return &id }455