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
238 lines
6.9 KiB
Go
238 lines
6.9 KiB
Go
package api
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"regexp"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
|
)
|
|
|
|
type ssoProviderView struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Name string `json:"name"`
|
|
Issuer string `json:"issuer"`
|
|
ClientID string `json:"client_id"`
|
|
HasClientSecret bool `json:"has_client_secret"`
|
|
Scopes []string `json:"scopes"`
|
|
AllowedDomains []string `json:"allowed_domains"`
|
|
AutoProvision bool `json:"auto_provision"`
|
|
DefaultRoleID *uuid.UUID `json:"default_role_id"`
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
|
|
func viewSSOProvider(p store.SsoProvider) ssoProviderView {
|
|
return ssoProviderView{
|
|
ID: p.ID, Name: p.Name, Issuer: p.Issuer, ClientID: p.ClientID,
|
|
HasClientSecret: p.ClientSecret != nil, Scopes: p.Scopes,
|
|
AllowedDomains: p.AllowedDomains, AutoProvision: p.AutoProvision, DefaultRoleID: p.DefaultRoleID, Enabled: p.Enabled,
|
|
}
|
|
}
|
|
|
|
type ssoProviderRequest struct {
|
|
Name string `json:"name" binding:"required,max=100"`
|
|
Issuer string `json:"issuer" binding:"required,max=500"`
|
|
ClientID string `json:"client_id" binding:"required,max=500"`
|
|
// Empty on update keeps the stored secret; it is never returned.
|
|
ClientSecret string `json:"client_secret" binding:"max=2000"`
|
|
Scopes []string `json:"scopes" binding:"max=20,dive,max=100"`
|
|
AllowedDomains []string `json:"allowed_domains" binding:"max=50,dive,max=253"`
|
|
AutoProvision bool `json:"auto_provision"`
|
|
// DefaultRoleID is assigned to auto-provisioned users; nil means Viewer.
|
|
DefaultRoleID *uuid.UUID `json:"default_role_id"`
|
|
Enabled *bool `json:"enabled"`
|
|
}
|
|
|
|
var domainRE = regexp.MustCompile(`^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$`)
|
|
|
|
// normalize cleans the request and returns an error code for invalid input.
|
|
func (r *ssoProviderRequest) normalize() string {
|
|
r.Name = strings.TrimSpace(r.Name)
|
|
r.Issuer = strings.TrimSuffix(strings.TrimSpace(r.Issuer), "/")
|
|
r.ClientID = strings.TrimSpace(r.ClientID)
|
|
if r.Name == "" || r.ClientID == "" {
|
|
return "invalid_input"
|
|
}
|
|
scopes := []string{"openid"}
|
|
for _, sc := range r.Scopes {
|
|
if sc = strings.TrimSpace(sc); sc != "" && !slices.Contains(scopes, sc) {
|
|
scopes = append(scopes, sc)
|
|
}
|
|
}
|
|
if len(r.Scopes) == 0 {
|
|
scopes = append(scopes, "email", "profile")
|
|
}
|
|
r.Scopes = scopes
|
|
domains := []string{}
|
|
for _, d := range r.AllowedDomains {
|
|
d = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(d)), "@")
|
|
if d == "" {
|
|
continue
|
|
}
|
|
if !domainRE.MatchString(d) {
|
|
return "invalid_domain"
|
|
}
|
|
if !slices.Contains(domains, d) {
|
|
domains = append(domains, d)
|
|
}
|
|
}
|
|
r.AllowedDomains = domains
|
|
return ""
|
|
}
|
|
|
|
func (s *Server) listSSOProviders(c *gin.Context) {
|
|
ctx := c.Request.Context()
|
|
var rows []store.SsoProvider
|
|
err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
|
var err error
|
|
rows, err = q.ListSSOProviders(ctx)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
out := make([]ssoProviderView, len(rows))
|
|
for i, r := range rows {
|
|
out[i] = viewSSOProvider(r)
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"providers": out, "redirect_url": s.sso.RedirectURL()})
|
|
}
|
|
|
|
func (s *Server) validateSSORequest(c *gin.Context, req *ssoProviderRequest) bool {
|
|
if code := req.normalize(); code != "" {
|
|
fail(c, http.StatusUnprocessableEntity, code)
|
|
return false
|
|
}
|
|
if req.DefaultRoleID != nil {
|
|
ctx := c.Request.Context()
|
|
var role store.Role
|
|
err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
|
var err error
|
|
role, err = q.GetRole(ctx, *req.DefaultRoleID)
|
|
return err
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
fail(c, http.StatusUnprocessableEntity, "role_not_found")
|
|
return false
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return false
|
|
}
|
|
// Auto-provisioning hands this role to anyone the IdP vouches for.
|
|
if !current(c).Grants.CanGrant(authz.NewSet(role.Permissions...), nil) {
|
|
fail(c, http.StatusForbidden, "permission_escalation")
|
|
return false
|
|
}
|
|
}
|
|
if err := s.sso.ValidateIssuer(c.Request.Context(), req.Issuer); err != nil {
|
|
code := "sso_discovery_failed"
|
|
switch {
|
|
case errors.Is(err, sso.ErrInvalidIssuer):
|
|
code = "sso_invalid_issuer"
|
|
case errors.Is(err, sso.ErrForbiddenAddress):
|
|
code = "sso_forbidden_address"
|
|
}
|
|
fail(c, http.StatusUnprocessableEntity, code)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (s *Server) createSSOProvider(c *gin.Context) {
|
|
var req ssoProviderRequest
|
|
if !bind(c, &req) || !s.validateSSORequest(c, &req) {
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
id := uuid.New()
|
|
var secret []byte
|
|
if req.ClientSecret != "" {
|
|
secret = s.keys.Seal([]byte(req.ClientSecret), id[:])
|
|
}
|
|
var row store.SsoProvider
|
|
err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
|
var err error
|
|
row, err = q.CreateSSOProvider(ctx, store.CreateSSOProviderParams{
|
|
ID: id, OrgID: current(c).Org.ID, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID,
|
|
ClientSecret: secret, Scopes: req.Scopes, AllowedDomains: req.AllowedDomains,
|
|
AutoProvision: req.AutoProvision, DefaultRoleID: req.DefaultRoleID, Enabled: req.Enabled == nil || *req.Enabled,
|
|
})
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusCreated, viewSSOProvider(row))
|
|
}
|
|
|
|
func (s *Server) updateSSOProvider(c *gin.Context) {
|
|
id, err := uuid.Parse(c.Param("id"))
|
|
if err != nil {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
var req ssoProviderRequest
|
|
if !bind(c, &req) || !s.validateSSORequest(c, &req) {
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
var secret []byte
|
|
if req.ClientSecret != "" {
|
|
secret = s.keys.Seal([]byte(req.ClientSecret), id[:])
|
|
}
|
|
var row store.SsoProvider
|
|
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
|
var err error
|
|
row, err = q.UpdateSSOProvider(ctx, store.UpdateSSOProviderParams{
|
|
ID: id, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID, ClientSecret: secret,
|
|
Scopes: req.Scopes, AllowedDomains: req.AllowedDomains, AutoProvision: req.AutoProvision,
|
|
DefaultRoleID: req.DefaultRoleID, Enabled: req.Enabled == nil || *req.Enabled,
|
|
})
|
|
return err
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, viewSSOProvider(row))
|
|
}
|
|
|
|
func (s *Server) deleteSSOProvider(c *gin.Context) {
|
|
id, err := uuid.Parse(c.Param("id"))
|
|
if err != nil {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
var n int64
|
|
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
|
var err error
|
|
n, err = q.DeleteSSOProvider(ctx, id)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if n == 0 {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|