feat(api): let each organization sign in through its own identity provider
Owners manage OIDC providers under /settings/sso. Users start at /sso/<org>. New users can be provisioned for verified emails in allowed domains; existing accounts are never matched by email and must link their SSO sign-in while signed in. Closes #4 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
9ad5f29f1b
commit
3f21361995
19 files changed
+2731
-231
No files matched your search
@@ -0,0 +1,246 @@
|
||||
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/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
const ctxOrgKey = "api.org"
|
||||
|
||||
// requireOwner admits only the owner of the session's active org. It is a
|
||||
// stand-in until role-based permissions exist (#6).
|
||||
func (s *Server) requireOwner() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil || sess.OrgID == uuid.Nil {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var m store.Membership
|
||||
err := s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error {
|
||||
var err error
|
||||
m, err = q.GetMembership(ctx, store.GetMembershipParams{OrgID: sess.OrgID, UserID: sess.UserID})
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !m.IsOwner) {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Set(ctxOrgKey, sess.OrgID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func orgOf(c *gin.Context) uuid.UUID { return c.MustGet(ctxOrgKey).(uuid.UUID) }
|
||||
|
||||
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"`
|
||||
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, 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"`
|
||||
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, tenant.Org(orgOf(c), auth.Current(c).UserID), 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 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, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateSSOProvider(ctx, store.CreateSSOProviderParams{
|
||||
ID: id, OrgID: orgOf(c), Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID,
|
||||
ClientSecret: secret, Scopes: req.Scopes, AllowedDomains: req.AllowedDomains,
|
||||
AutoProvision: req.AutoProvision, 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, tenant.Org(orgOf(c), auth.Current(c).UserID), 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,
|
||||
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, tenant.Org(orgOf(c), auth.Current(c).UserID), 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)
|
||||
}
|
||||
Reference in new issue
Block a user