package api import ( "context" "errors" "net/http" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/jackc/pgx/v5" "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" "git.zb-server.de/ZB-Server/uptimesebi/internal/authz" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) const ctxPrincipal = "api.principal" // principal is whoever acts on an organization in this request: a browser // session or an API token, together with what it may do there. type principal struct { UserID uuid.UUID Org store.Org Grants *authz.Grants // Session is nil for API token requests. Session *auth.Session // TokenID is set for API token requests. TokenID uuid.UUID } func (p *principal) scope() tenant.Scope { return tenant.Org(p.Org.ID, p.UserID) } func current(c *gin.Context) *principal { return c.MustGet(ctxPrincipal).(*principal) } // loadGrants returns the member's permissions, or ok=false if userID is not // a member of org. func loadGrants(ctx context.Context, q *store.Queries, org, userID uuid.UUID) (g *authz.Grants, ok bool, err error) { m, err := q.GetMembership(ctx, store.GetMembershipParams{OrgID: org, UserID: userID}) if errors.Is(err, pgx.ErrNoRows) { return nil, false, nil } if err != nil { return nil, false, err } rows, err := q.MemberGrants(ctx, store.MemberGrantsParams{OrgID: org, UserID: userID}) if err != nil { return nil, false, err } g = &authz.Grants{Owner: m.IsOwner, Org: authz.Set{}, Scoped: map[authz.Resource]authz.Set{}} for _, r := range rows { perms := authz.NewSet(r.Permissions...) if r.ResourceType == nil || r.ResourceID == nil { g.Org = g.Org.Union(perms) continue } res := authz.Resource{Type: authz.ResourceType(*r.ResourceType), ID: *r.ResourceID} g.Scoped[res] = g.Scoped[res].Union(perms) } return g, true, nil } // policyViolation returns the error code if sess may not act on org because // of the org's sign-in policy, or "" if it may. // // SSO sessions satisfy the TOTP requirement: multi-factor authentication is // then the identity provider's job. The owner may always sign in with a // password so a broken IdP cannot lock the organization out. func policyViolation(org store.Org, isOwner bool, sess *auth.Session) string { viaOrgSSO := sess.Method == auth.MethodSSO && sess.SSOOrg == org.ID if org.RequireSso && !viaOrgSSO && !isOwner { return "sso_required_by_org" } if org.RequireTotp && !viaOrgSSO && sess.Method != auth.MethodPasswordTOTP { return "totp_required_by_org" } return "" } // orgAccess authenticates the request against the session's active // organization, enforces its sign-in policy and attaches a principal. func (s *Server) orgAccess() gin.HandlerFunc { return func(c *gin.Context) { p, status, code, err := s.resolvePrincipal(c) if err != nil { internalError(c, err) return } if code != "" { fail(c, status, code) return } c.Set(ctxPrincipal, p) c.Next() } } func (s *Server) resolvePrincipal(c *gin.Context) (*principal, int, string, error) { if tok := bearerToken(c); tok != "" { return s.tokenPrincipal(c.Request.Context(), tok) } sess := auth.Current(c) if sess == nil { return nil, http.StatusUnauthorized, "unauthenticated", nil } if sess.OrgID == uuid.Nil { return nil, http.StatusForbidden, "forbidden", nil } ctx := c.Request.Context() p := &principal{UserID: sess.UserID, Session: sess} var member bool err := s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error { var err error if p.Org, err = q.GetOrg(ctx, sess.OrgID); err != nil { return err } p.Grants, member, err = loadGrants(ctx, q, sess.OrgID, sess.UserID) return err }) if errors.Is(err, pgx.ErrNoRows) || (err == nil && !member) { return nil, http.StatusForbidden, "forbidden", nil } if err != nil { return nil, 0, "", err } if p.Org.SuspendedAt != nil { return nil, http.StatusForbidden, "org_suspended", nil } if code := policyViolation(p.Org, p.Grants.Owner, sess); code != "" { return nil, http.StatusForbidden, code, nil } return p, 0, "", nil } // can aborts unless the principal holds perm organization-wide. func can(perm authz.Permission) gin.HandlerFunc { return func(c *gin.Context) { if !current(c).Grants.Can(perm) { fail(c, http.StatusForbidden, "forbidden") return } c.Next() } } // sessionOnly rejects API tokens on routes that manage credentials, so a // leaked token cannot mint further tokens or change who has access. func sessionOnly() gin.HandlerFunc { return func(c *gin.Context) { if current(c).Session == nil { fail(c, http.StatusForbidden, "session_required") return } c.Next() } }