feat(api): enforce roles, org sign-in policies, invitations and api tokens
Every org route resolves a principal from the session or a bearer token and checks a permission. Nobody can grant, revoke or remove more than they hold. Tokens are capped by their owner's current rights and cannot manage credentials. Orgs can require TOTP or SSO; the owner keeps a password fallback for SSO. Closes #6 Closes #7 Closes #8 Closes #9 Closes #41 Closes #45 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
30409697f7
commit
d7d4821e3e
24 files changed
+4677
-439
No files matched your search
@@ -0,0 +1,206 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
// tokenPrefix makes tokens recognizable to secret scanners and to humans.
|
||||
const tokenPrefix = "ust_"
|
||||
|
||||
func hashToken(tok string) []byte {
|
||||
sum := sha256.Sum256([]byte(tok))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
func bearerToken(c *gin.Context) string {
|
||||
h := c.GetHeader("Authorization")
|
||||
if len(h) < 7 || !strings.EqualFold(h[:7], "bearer ") {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(h[7:])
|
||||
}
|
||||
|
||||
func (s *Server) tokenPrincipal(ctx context.Context, tok string) (*principal, int, string, error) {
|
||||
if !strings.HasPrefix(tok, tokenPrefix) {
|
||||
return nil, http.StatusUnauthorized, "unauthenticated", nil
|
||||
}
|
||||
hash := hashToken(tok)
|
||||
var org uuid.UUID
|
||||
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
var err error
|
||||
org, err = q.APITokenOrg(ctx, hash)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, 0, "", err
|
||||
}
|
||||
if org == uuid.Nil {
|
||||
return nil, http.StatusUnauthorized, "unauthenticated", nil
|
||||
}
|
||||
p := &principal{}
|
||||
var (
|
||||
row store.ApiToken
|
||||
member bool
|
||||
)
|
||||
err = s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error {
|
||||
var err error
|
||||
if row, err = q.GetAPITokenByHash(ctx, hash); err != nil {
|
||||
return err
|
||||
}
|
||||
if row.ExpiresAt != nil && !row.ExpiresAt.After(time.Now()) {
|
||||
return nil
|
||||
}
|
||||
if p.Org, err = q.GetOrg(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Grants, member, err = loadGrants(ctx, q, org, row.UserID); err != nil || !member {
|
||||
return err
|
||||
}
|
||||
return q.TouchAPIToken(ctx, row.ID)
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !member) {
|
||||
return nil, http.StatusUnauthorized, "unauthenticated", nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, 0, "", err
|
||||
}
|
||||
p.UserID, p.TokenID = row.UserID, row.ID
|
||||
p.Grants = p.Grants.Restrict(authz.NewSet(row.Permissions...))
|
||||
return p, 0, "", nil
|
||||
}
|
||||
|
||||
type tokenView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Prefix string `json:"prefix"`
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
UserEmail string `json:"user_email"`
|
||||
Permissions []string `json:"permissions"`
|
||||
ExpiresAt *time.Time `json:"expires_at"`
|
||||
LastUsedAt *time.Time `json:"last_used_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (s *Server) listTokens(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
// Members see their own tokens; members.manage reveals everyone's so
|
||||
// tokens of departing staff can be revoked.
|
||||
var filter *uuid.UUID
|
||||
if !p.Grants.Can(authz.MembersManage) {
|
||||
filter = &p.UserID
|
||||
}
|
||||
var rows []store.ListAPITokensRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListAPITokens(ctx, store.ListAPITokensParams{OrgID: p.Org.ID, UserID: filter})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]tokenView, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = tokenView{
|
||||
ID: r.ID, Name: r.Name, Prefix: r.Prefix, UserID: r.UserID, UserEmail: r.UserEmail,
|
||||
Permissions: r.Permissions, ExpiresAt: r.ExpiresAt, LastUsedAt: r.LastUsedAt, CreatedAt: r.CreatedAt,
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"tokens": out})
|
||||
}
|
||||
|
||||
type createTokenRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Permissions []string `json:"permissions" binding:"required,min=1,max=50,dive,max=50"`
|
||||
// ExpiresInDays of 0 creates a token that does not expire.
|
||||
ExpiresInDays int `json:"expires_in_days" binding:"min=0,max=3650"`
|
||||
}
|
||||
|
||||
func (s *Server) createToken(c *gin.Context) {
|
||||
var req createTokenRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
perms := authz.NewSet(req.Permissions...)
|
||||
if len(perms) == 0 {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_permissions")
|
||||
return
|
||||
}
|
||||
if !p.Grants.CanGrant(perms, nil) {
|
||||
fail(c, http.StatusForbidden, "permission_escalation")
|
||||
return
|
||||
}
|
||||
var expires *time.Time
|
||||
if req.ExpiresInDays > 0 {
|
||||
t := time.Now().AddDate(0, 0, req.ExpiresInDays)
|
||||
expires = &t
|
||||
}
|
||||
tok := tokenPrefix + auth.RandomToken()
|
||||
ctx := c.Request.Context()
|
||||
var row store.ApiToken
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateAPIToken(ctx, store.CreateAPITokenParams{
|
||||
OrgID: p.Org.ID, UserID: p.UserID, Name: strings.TrimSpace(req.Name),
|
||||
TokenHash: hashToken(tok), Prefix: tok[:len(tokenPrefix)+6],
|
||||
Permissions: perms.Strings(), ExpiresAt: expires,
|
||||
})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"id": row.ID, "token": tok, "prefix": row.Prefix, "permissions": row.Permissions})
|
||||
}
|
||||
|
||||
func (s *Server) deleteToken(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var found bool
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
row, err := q.GetAPIToken(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if row.UserID != p.UserID && !p.Grants.Can(authz.MembersManage) {
|
||||
return nil
|
||||
}
|
||||
found = true
|
||||
_, err = q.DeleteAPIToken(ctx, id)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
Reference in new issue
Block a user