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
+101
-1
@@ -2,11 +2,15 @@ package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
@@ -14,7 +18,16 @@ func (s *Server) registerPages(r gin.IRouter) {
|
||||
r.GET("/login", s.loginPage)
|
||||
r.GET("/signup", s.signupPage)
|
||||
r.GET("/", s.page("console.monitors.title", web.Dashboard))
|
||||
r.GET("/settings/security", s.page("security.title", web.Security))
|
||||
r.GET("/settings/security", s.securityPage)
|
||||
r.GET("/settings/sso", s.ssoSettingsPage)
|
||||
}
|
||||
|
||||
// flashErrors lists the codes a redirect may ask a page to display. Anything
|
||||
// else in the query string is ignored so links cannot inject messages.
|
||||
var flashErrors = map[ssoError]bool{
|
||||
"sso_unavailable": true, "sso_provider_error": true, "sso_expired": true,
|
||||
"sso_denied": true, "sso_not_member": true, "sso_not_provisioned": true,
|
||||
"sso_link_required": true, "sso_identity_taken": true, "invalid_credentials": true,
|
||||
}
|
||||
|
||||
func (s *Server) pageFor(c *gin.Context, titleID string) web.Page {
|
||||
@@ -22,6 +35,12 @@ func (s *Server) pageFor(c *gin.Context, titleID string) web.Page {
|
||||
if sess := auth.Current(c); sess != nil {
|
||||
p.CSRF = sess.CSRF
|
||||
}
|
||||
if code := ssoError(c.Query("sso_error")); flashErrors[code] {
|
||||
p.ErrorID = "error." + string(code)
|
||||
}
|
||||
if c.Query("sso") == "linked" {
|
||||
p.NoticeID = "security.sso.linked"
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
@@ -67,6 +86,83 @@ func (s *Server) page(titleID string, view func(web.Page, web.Me) templ.Componen
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) securityPage(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
me, err := s.loadMe(ctx, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
var (
|
||||
identities []web.Identity
|
||||
canLink bool
|
||||
)
|
||||
if sess.OrgID != uuid.Nil {
|
||||
err = s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error {
|
||||
rows, err := q.ListUserIdentitiesInOrg(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range rows {
|
||||
identities = append(identities, web.Identity{Provider: r.ProviderName, Email: deref(r.Email)})
|
||||
}
|
||||
providers, err := q.ListEnabledSSOProviders(ctx)
|
||||
canLink = len(providers) > 0
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), toWebMe(me), identities, canLink))
|
||||
}
|
||||
|
||||
func (s *Server) ssoSettingsPage(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
me, err := s.loadMe(ctx, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
wm := toWebMe(me)
|
||||
if !wm.IsOwner {
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
return
|
||||
}
|
||||
var rows []store.SsoProvider
|
||||
err = s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error {
|
||||
rows, err = q.ListSSOProviders(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
view := web.SSOSettings{
|
||||
RedirectURL: s.sso.RedirectURL(),
|
||||
LoginURL: s.cfg.PublicURL + "/sso/" + wm.ActiveSlug,
|
||||
}
|
||||
for _, r := range rows {
|
||||
view.Providers = append(view.Providers, web.SSOProvider{
|
||||
ID: r.ID.String(), Name: r.Name, Issuer: r.Issuer, ClientID: r.ClientID,
|
||||
HasSecret: r.ClientSecret != nil, AllowedDomains: strings.Join(r.AllowedDomains, ", "),
|
||||
AutoProvision: r.AutoProvision, Enabled: r.Enabled,
|
||||
})
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.SSOSettingsPage(s.pageFor(c, "sso.settings.title"), wm, view))
|
||||
}
|
||||
|
||||
func toWebMe(m meView) web.Me {
|
||||
out := web.Me{
|
||||
Email: m.Email,
|
||||
@@ -77,6 +173,10 @@ func toWebMe(m meView) web.Me {
|
||||
}
|
||||
for _, o := range m.Orgs {
|
||||
out.Orgs = append(out.Orgs, web.Org{ID: o.ID.String(), Name: o.Name, Slug: o.Slug, IsOwner: o.IsOwner})
|
||||
if o.ID == m.ActiveOrg {
|
||||
out.IsOwner = o.IsOwner
|
||||
out.ActiveSlug = o.Slug
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
|
||||
"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"
|
||||
)
|
||||
@@ -33,6 +34,7 @@ type Server struct {
|
||||
sessions *auth.Sessions
|
||||
limiter *auth.Limiter
|
||||
totp *auth.TOTPVerifier
|
||||
sso *sso.Client
|
||||
}
|
||||
|
||||
// Deps are the external resources a Server needs.
|
||||
@@ -46,6 +48,7 @@ type Deps struct {
|
||||
|
||||
// New returns a Server. It does not register any routes; see Mount.
|
||||
func New(cfg config.API, d Deps) *Server {
|
||||
allowPrivate := cfg.SSOAllowPrivate()
|
||||
return &Server{
|
||||
cfg: cfg,
|
||||
log: d.Log,
|
||||
@@ -56,6 +59,7 @@ func New(cfg config.API, d Deps) *Server {
|
||||
sessions: auth.NewSessions(d.Redis, cfg.SessionIdle, cfg.SessionAbsolute),
|
||||
limiter: auth.NewLimiter(d.Redis),
|
||||
totp: auth.NewTOTPVerifier(d.Redis),
|
||||
sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +84,17 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
me.POST("/totp/enable", s.totpEnable)
|
||||
me.POST("/totp/disable", s.totpDisable)
|
||||
|
||||
org := v1.Group("/org", auth.Require(), s.requireOwner())
|
||||
org.GET("/sso", s.listSSOProviders)
|
||||
org.POST("/sso", s.createSSOProvider)
|
||||
org.PUT("/sso/:id", s.updateSSOProvider)
|
||||
org.DELETE("/sso/:id", s.deleteSSOProvider)
|
||||
|
||||
g.GET("/sso", s.ssoLookup)
|
||||
g.GET("/sso/callback", s.ssoCallback)
|
||||
g.GET("/sso/:slug", s.ssoChoose)
|
||||
g.GET("/sso/:slug/:provider", s.ssoStartProvider)
|
||||
|
||||
s.registerPages(g)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"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/i18n"
|
||||
"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"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
const (
|
||||
ssoCookie = "__Host-sso"
|
||||
ssoFlowTTL = 10 * time.Minute
|
||||
)
|
||||
|
||||
// ssoFlow is kept in Redis between the redirect to the IdP and the callback.
|
||||
type ssoFlow struct {
|
||||
Provider uuid.UUID `json:"provider"`
|
||||
Org uuid.UUID `json:"org"`
|
||||
Nonce string `json:"nonce"`
|
||||
Verifier string `json:"verifier"`
|
||||
// LinkUser is set when a signed-in user connects this IdP to their
|
||||
// existing account instead of signing in.
|
||||
LinkUser uuid.UUID `json:"link_user,omitempty"`
|
||||
}
|
||||
|
||||
// ssoError aborts a browser flow by redirecting with a code the target page
|
||||
// translates. Unlike JSON errors, the user has navigated away from our page.
|
||||
type ssoError string
|
||||
|
||||
func ssoFlowKey(state string) string {
|
||||
sum := sha256.Sum256([]byte(state))
|
||||
return "sso_flow:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *Server) ssoProvider(row store.SsoProvider) (sso.Provider, error) {
|
||||
p := sso.Provider{Issuer: row.Issuer, ClientID: row.ClientID, Scopes: row.Scopes}
|
||||
if row.ClientSecret != nil {
|
||||
secret, err := s.keys.Open(row.ClientSecret, row.ID[:])
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
p.ClientSecret = string(secret)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// ssoLookup redirects the login page's slug form to the org's SSO URL.
|
||||
func (s *Server) ssoLookup(c *gin.Context) {
|
||||
slug := strings.ToLower(strings.TrimSpace(c.Query("org")))
|
||||
if slug == "" {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
c.Redirect(http.StatusSeeOther, "/sso/"+url.PathEscape(slug))
|
||||
}
|
||||
|
||||
// ssoChoose starts the flow if the org has exactly one enabled provider and
|
||||
// otherwise lets the user pick.
|
||||
func (s *Server) ssoChoose(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !s.limitPage(c, "sso:ip:"+c.ClientIP(), 30, time.Minute) {
|
||||
return
|
||||
}
|
||||
org, err := s.orgIDBySlug(ctx, c.Param("slug"))
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
var providers []store.ListEnabledSSOProvidersRow
|
||||
if org != uuid.Nil {
|
||||
err = s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error {
|
||||
providers, err = q.ListEnabledSSOProviders(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
switch len(providers) {
|
||||
case 0:
|
||||
s.ssoAbort(c, uuid.Nil, "sso_unavailable")
|
||||
case 1:
|
||||
s.ssoStart(c, org, providers[0].ID)
|
||||
default:
|
||||
opts := make([]web.SSOOption, len(providers))
|
||||
for i, p := range providers {
|
||||
opts[i] = web.SSOOption{Name: p.Name, URL: "/sso/" + url.PathEscape(c.Param("slug")) + "/" + p.ID.String() + linkSuffix(c)}
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.SSOChooser(s.pageFor(c, "sso.choose.title"), opts))
|
||||
}
|
||||
}
|
||||
|
||||
func linkSuffix(c *gin.Context) string {
|
||||
if c.Query("link") == "1" {
|
||||
return "?link=1"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) ssoStartProvider(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !s.limitPage(c, "sso:ip:"+c.ClientIP(), 30, time.Minute) {
|
||||
return
|
||||
}
|
||||
org, err := s.orgIDBySlug(ctx, c.Param("slug"))
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
id, err := uuid.Parse(c.Param("provider"))
|
||||
if err != nil || org == uuid.Nil {
|
||||
s.ssoAbort(c, uuid.Nil, "sso_unavailable")
|
||||
return
|
||||
}
|
||||
s.ssoStart(c, org, id)
|
||||
}
|
||||
|
||||
func (s *Server) ssoStart(c *gin.Context, org, providerID uuid.UUID) {
|
||||
ctx := c.Request.Context()
|
||||
var linkUser uuid.UUID
|
||||
if c.Query("link") == "1" {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
linkUser = sess.UserID
|
||||
}
|
||||
var row store.SsoProvider
|
||||
err := s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.GetSSOProvider(ctx, providerID)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !row.Enabled) {
|
||||
s.ssoAbort(c, linkUser, "sso_unavailable")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
p, err := s.ssoProvider(row)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
flow := sso.NewFlow(auth.RandomToken)
|
||||
authURL, err := s.sso.AuthURL(ctx, p, flow)
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "sso discovery failed", "provider", providerID, "error", err)
|
||||
s.ssoAbort(c, linkUser, "sso_provider_error")
|
||||
return
|
||||
}
|
||||
state, _ := json.Marshal(ssoFlow{Provider: row.ID, Org: org, Nonce: flow.Nonce, Verifier: flow.Verifier, LinkUser: linkUser})
|
||||
if err := s.rdb.Set(ctx, ssoFlowKey(flow.State), state, ssoFlowTTL).Err(); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
// Binding the state to this browser stops an attacker from completing
|
||||
// their own flow in a victim's browser (login CSRF).
|
||||
setCookie(c, ssoCookie, flow.State, int(ssoFlowTTL.Seconds()))
|
||||
c.Redirect(http.StatusFound, authURL)
|
||||
}
|
||||
|
||||
func (s *Server) ssoCallback(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
state := c.Query("state")
|
||||
cookie, _ := c.Cookie(ssoCookie)
|
||||
setCookie(c, ssoCookie, "", -1)
|
||||
if state == "" || cookie != state {
|
||||
s.ssoAbort(c, uuid.Nil, "sso_expired")
|
||||
return
|
||||
}
|
||||
raw, err := s.rdb.GetDel(ctx, ssoFlowKey(state)).Bytes()
|
||||
if err != nil {
|
||||
s.ssoAbort(c, uuid.Nil, "sso_expired")
|
||||
return
|
||||
}
|
||||
var f ssoFlow
|
||||
if err := json.Unmarshal(raw, &f); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if c.Query("error") != "" {
|
||||
s.ssoAbort(c, f.LinkUser, "sso_denied")
|
||||
return
|
||||
}
|
||||
|
||||
var row store.SsoProvider
|
||||
err = s.db.Tx(ctx, tenant.Org(f.Org, uuid.Nil), func(q *store.Queries) error {
|
||||
row, err = q.GetSSOProvider(ctx, f.Provider)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !row.Enabled) {
|
||||
s.ssoAbort(c, f.LinkUser, "sso_unavailable")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
p, err := s.ssoProvider(row)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
claims, err := s.sso.Exchange(ctx, p, sso.Flow{State: state, Nonce: f.Nonce, Verifier: f.Verifier}, c.Query("code"))
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "sso exchange failed", "provider", row.ID, "error", err)
|
||||
s.ssoAbort(c, f.LinkUser, "sso_provider_error")
|
||||
return
|
||||
}
|
||||
|
||||
if f.LinkUser != uuid.Nil {
|
||||
s.ssoLink(c, row, f.LinkUser, claims)
|
||||
return
|
||||
}
|
||||
userID, code, err := s.ssoResolveUser(ctx, row, claims)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if code != "" {
|
||||
s.ssoAbort(c, uuid.Nil, code)
|
||||
return
|
||||
}
|
||||
var user store.User
|
||||
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
user, err = q.GetUser(ctx, userID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if user.DisabledAt != nil {
|
||||
s.ssoAbort(c, uuid.Nil, "invalid_credentials")
|
||||
return
|
||||
}
|
||||
if old := auth.Current(c); old != nil {
|
||||
_ = s.sessions.Delete(ctx, old)
|
||||
}
|
||||
locale := deref(user.Locale)
|
||||
if locale == "" {
|
||||
locale = i18n.Lang(ctx)
|
||||
}
|
||||
sess, err := s.sessions.Create(ctx, userID, row.OrgID, locale)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds()))
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
}
|
||||
|
||||
// ssoResolveUser maps an IdP identity to a user. It returns a non-empty
|
||||
// error code when sign-in must be refused.
|
||||
//
|
||||
// Existing accounts are only ever reached through a stored identity. A
|
||||
// matching email is not enough: the org controls its IdP and could assert
|
||||
// the address of a user who also belongs to other orgs.
|
||||
func (s *Server) ssoResolveUser(ctx context.Context, row store.SsoProvider, cl sso.Claims) (uuid.UUID, ssoError, error) {
|
||||
var (
|
||||
userID uuid.UUID
|
||||
code ssoError
|
||||
)
|
||||
email := normalizeEmail(cl.Email)
|
||||
err := s.db.Tx(ctx, tenant.Org(row.OrgID, uuid.Nil), func(q *store.Queries) error {
|
||||
ident, err := q.GetIdentity(ctx, store.GetIdentityParams{ProviderID: row.ID, Subject: cl.Subject})
|
||||
switch {
|
||||
case err == nil:
|
||||
member, err := q.IsMember(ctx, store.IsMemberParams{OrgID: row.OrgID, UserID: ident.UserID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
code = "sso_not_member"
|
||||
return nil
|
||||
}
|
||||
userID = ident.UserID
|
||||
return q.TouchIdentity(ctx, store.TouchIdentityParams{ProviderID: row.ID, Subject: cl.Subject, Email: nonEmpty(email)})
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return err
|
||||
}
|
||||
|
||||
if !row.AutoProvision || email == "" || !cl.EmailVerified || !domainAllowed(email, row.AllowedDomains) {
|
||||
code = "sso_not_provisioned"
|
||||
return nil
|
||||
}
|
||||
if _, err := q.GetUserByEmail(ctx, email); err == nil {
|
||||
code = "sso_link_required"
|
||||
return nil
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
u, err := q.CreateUser(ctx, store.CreateUserParams{
|
||||
Email: email,
|
||||
DisplayName: truncate(strings.TrimSpace(cl.Name), 200),
|
||||
Locale: ptr(i18n.Lang(ctx)),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: row.OrgID, UserID: u.ID}); err != nil {
|
||||
return err
|
||||
}
|
||||
userID = u.ID
|
||||
return q.CreateIdentity(ctx, store.CreateIdentityParams{ProviderID: row.ID, Subject: cl.Subject, OrgID: row.OrgID, UserID: u.ID, Email: nonEmpty(email)})
|
||||
})
|
||||
return userID, code, err
|
||||
}
|
||||
|
||||
func (s *Server) ssoLink(c *gin.Context, row store.SsoProvider, userID uuid.UUID, cl sso.Claims) {
|
||||
ctx := c.Request.Context()
|
||||
sess := auth.Current(c)
|
||||
if sess == nil || sess.UserID != userID {
|
||||
s.ssoAbort(c, uuid.Nil, "sso_expired")
|
||||
return
|
||||
}
|
||||
var code ssoError
|
||||
err := s.db.Tx(ctx, tenant.Org(row.OrgID, userID), func(q *store.Queries) error {
|
||||
member, err := q.IsMember(ctx, store.IsMemberParams{OrgID: row.OrgID, UserID: userID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
code = "sso_not_member"
|
||||
return nil
|
||||
}
|
||||
ident, err := q.GetIdentity(ctx, store.GetIdentityParams{ProviderID: row.ID, Subject: cl.Subject})
|
||||
switch {
|
||||
case err == nil && ident.UserID == userID:
|
||||
return nil
|
||||
case err == nil:
|
||||
code = "sso_identity_taken"
|
||||
return nil
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return err
|
||||
}
|
||||
return q.CreateIdentity(ctx, store.CreateIdentityParams{
|
||||
ProviderID: row.ID, Subject: cl.Subject, OrgID: row.OrgID, UserID: userID, Email: nonEmpty(normalizeEmail(cl.Email)),
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if code != "" {
|
||||
s.ssoAbort(c, userID, code)
|
||||
return
|
||||
}
|
||||
c.Redirect(http.StatusSeeOther, "/settings/security?sso=linked")
|
||||
}
|
||||
|
||||
// ssoAbort sends the browser back to where the flow started with an error
|
||||
// code the page renders in the user's language.
|
||||
func (s *Server) ssoAbort(c *gin.Context, linkUser uuid.UUID, code ssoError) {
|
||||
target := "/login"
|
||||
if linkUser != uuid.Nil {
|
||||
target = "/settings/security"
|
||||
}
|
||||
c.Redirect(http.StatusSeeOther, target+"?sso_error="+url.QueryEscape(string(code)))
|
||||
}
|
||||
|
||||
func (s *Server) orgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) {
|
||||
var id uuid.UUID
|
||||
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
var err error
|
||||
id, err = q.OrgIDBySlug(ctx, strings.ToLower(slug))
|
||||
return err
|
||||
})
|
||||
return id, err
|
||||
}
|
||||
|
||||
func (s *Server) limitPage(c *gin.Context, key string, n int, window time.Duration) bool {
|
||||
ok, err := s.limiter.Allow(c.Request.Context(), key, n, window)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return false
|
||||
}
|
||||
if !ok {
|
||||
c.Header("Retry-After", "60")
|
||||
c.AbortWithStatus(http.StatusTooManyRequests)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func domainAllowed(email string, allowed []string) bool {
|
||||
if len(allowed) == 0 {
|
||||
return true
|
||||
}
|
||||
at := strings.LastIndexByte(email, '@')
|
||||
if at < 0 {
|
||||
return false
|
||||
}
|
||||
domain := email[at+1:]
|
||||
for _, d := range allowed {
|
||||
if domain == d {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func nonEmpty(s string) *string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return &s
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
if r := []rune(s); len(r) > n {
|
||||
return string(r[:n])
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
type env struct {
|
||||
srv *httptest.Server
|
||||
dbPool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func newEnv(t *testing.T) *env {
|
||||
t.Helper()
|
||||
dsn, redisURL := os.Getenv("UPTIME_TEST_DATABASE_URL"), os.Getenv("UPTIME_TEST_REDIS_URL")
|
||||
if dsn == "" || redisURL == "" {
|
||||
t.Skip("UPTIME_TEST_DATABASE_URL and UPTIME_TEST_REDIS_URL must be set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
if _, err := migrations.Up(ctx, dsn); err != nil {
|
||||
t.Fatalf("migrations.Up() failed: %v", err)
|
||||
}
|
||||
pool, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
opts, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rdb := redis.NewClient(opts)
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
|
||||
key := make([]byte, 32)
|
||||
_, _ = rand.Read(key)
|
||||
keys, err := sealed.Parse("t:" + base64.StdEncoding.EncodeToString(key))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
catalog, err := i18n.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
e := &env{dbPool: pool}
|
||||
r := platform.NewRouter(log)
|
||||
e.srv = httptest.NewUnstartedServer(r)
|
||||
e.srv.StartTLS()
|
||||
t.Cleanup(e.srv.Close)
|
||||
|
||||
cfg := config.API{
|
||||
Common: config.Common{Edition: config.EditionSelfHosted},
|
||||
Signup: config.SignupOpen,
|
||||
SessionIdle: time.Hour,
|
||||
SessionAbsolute: 24 * time.Hour,
|
||||
PublicURL: e.srv.URL,
|
||||
SSOPrivateNetworks: "true",
|
||||
}
|
||||
api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog}).Mount(r)
|
||||
return e
|
||||
}
|
||||
|
||||
// browser is a cookie-keeping client that follows redirects like a browser.
|
||||
type browser struct {
|
||||
t *testing.T
|
||||
base string
|
||||
hc *http.Client
|
||||
csrf string
|
||||
}
|
||||
|
||||
func (e *env) browser(t *testing.T) *browser {
|
||||
jar, _ := cookiejar.New(nil)
|
||||
// Client() returns a shared instance; copy it so each browser has its own jar.
|
||||
hc := *e.srv.Client()
|
||||
hc.Jar = jar
|
||||
return &browser{t: t, base: e.srv.URL, hc: &hc}
|
||||
}
|
||||
|
||||
func (b *browser) do(method, path string, body any) (int, map[string]any) {
|
||||
b.t.Helper()
|
||||
var rd io.Reader
|
||||
if body != nil {
|
||||
raw, _ := json.Marshal(body)
|
||||
rd = bytes.NewReader(raw)
|
||||
}
|
||||
req, _ := http.NewRequest(method, b.base+path, rd)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if b.csrf != "" {
|
||||
req.Header.Set("X-CSRF-Token", b.csrf)
|
||||
}
|
||||
resp, err := b.hc.Do(req)
|
||||
if err != nil {
|
||||
b.t.Fatalf("%s %s failed: %v", method, path, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
var out map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&out)
|
||||
if tok, ok := out["csrf_token"].(string); ok {
|
||||
b.csrf = tok
|
||||
}
|
||||
return resp.StatusCode, out
|
||||
}
|
||||
|
||||
// visit follows redirects and returns the final URL.
|
||||
func (b *browser) visit(path string) *url.URL {
|
||||
b.t.Helper()
|
||||
resp, err := b.hc.Get(b.base + path)
|
||||
if err != nil {
|
||||
b.t.Fatalf("GET %s failed: %v", path, err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
return resp.Request.URL
|
||||
}
|
||||
|
||||
func uniq(prefix string) string { return prefix + strings.ReplaceAll(uuid.NewString()[:8], "-", "") }
|
||||
|
||||
func (b *browser) signup(email, slug string) {
|
||||
b.t.Helper()
|
||||
st, body := b.do("POST", "/api/v1/auth/signup", map[string]any{
|
||||
"email": email, "password": "correct horse battery", "org_name": slug, "org_slug": slug,
|
||||
})
|
||||
if st != http.StatusOK {
|
||||
b.t.Fatalf("signup(%s) = %d %v, want 200", email, st, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSO(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
idp := ssotest.New(t)
|
||||
slug := uniq("sso-")
|
||||
domain := uniq("d") + ".test"
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("owner@"+domain, slug)
|
||||
|
||||
st, body := owner.do("POST", "/api/v1/org/sso", map[string]any{
|
||||
"name": "Corp IdP", "issuer": idp.Issuer(), "client_id": idp.ClientID, "client_secret": idp.Secret,
|
||||
"allowed_domains": []string{domain}, "auto_provision": true,
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create provider = %d %v, want 201", st, body)
|
||||
}
|
||||
if body["has_client_secret"] != true || body["client_secret"] != nil {
|
||||
t.Errorf("create provider response = %v, want has_client_secret and no secret", body)
|
||||
}
|
||||
|
||||
t.Run("other org cannot see provider", func(t *testing.T) {
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("o")+".test", uniq("other-"))
|
||||
st, body := other.do("GET", "/api/v1/org/sso", nil)
|
||||
if st != http.StatusOK || len(body["providers"].([]any)) != 0 {
|
||||
t.Errorf("GET /api/v1/org/sso as other org = %d %v, want 200 with no providers", st, body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("auto provisioning", func(t *testing.T) {
|
||||
idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "new@" + domain, EmailVerified: true, Name: "New"})
|
||||
u := e.browser(t)
|
||||
if got := u.visit("/sso/" + slug); got.Path != "/" || got.Query().Get("sso_error") != "" {
|
||||
t.Fatalf("SSO login landed on %s, want /", got)
|
||||
}
|
||||
st, me := u.do("GET", "/api/v1/me", nil)
|
||||
if st != http.StatusOK || me["email"] != "new@"+domain {
|
||||
t.Errorf("GET /api/v1/me = %d %v, want new@%s", st, me, domain)
|
||||
}
|
||||
st, _ = u.do("GET", "/api/v1/org/sso", nil)
|
||||
if st != http.StatusForbidden {
|
||||
t.Errorf("GET /api/v1/org/sso as member = %d, want 403", st)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unverified email is not provisioned", func(t *testing.T) {
|
||||
idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "unverified@" + domain, EmailVerified: false})
|
||||
if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_not_provisioned" {
|
||||
t.Errorf("SSO login landed on %s, want sso_error=sso_not_provisioned", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("foreign domain is not provisioned", func(t *testing.T) {
|
||||
idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "x@elsewhere.test", EmailVerified: true})
|
||||
if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_not_provisioned" {
|
||||
t.Errorf("SSO login landed on %s, want sso_error=sso_not_provisioned", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("existing email requires explicit linking", func(t *testing.T) {
|
||||
subject := uniq("s")
|
||||
idp.SetUser(ssotest.User{Subject: subject, Email: "owner@" + domain, EmailVerified: true})
|
||||
if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_link_required" {
|
||||
t.Fatalf("SSO login landed on %s, want sso_error=sso_link_required", got)
|
||||
}
|
||||
|
||||
if got := owner.visit("/sso/" + slug + "?link=1"); got.Path != "/settings/security" || got.Query().Get("sso") != "linked" {
|
||||
t.Fatalf("link flow landed on %s, want /settings/security?sso=linked", got)
|
||||
}
|
||||
fresh := e.browser(t)
|
||||
if got := fresh.visit("/sso/" + slug); got.Path != "/" {
|
||||
t.Fatalf("SSO login after linking landed on %s, want /", got)
|
||||
}
|
||||
if _, me := fresh.do("GET", "/api/v1/me", nil); me["email"] != "owner@"+domain {
|
||||
t.Errorf("GET /api/v1/me after linked login = %v, want owner", me)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("callback without browser binding is rejected", func(t *testing.T) {
|
||||
attacker := e.browser(t)
|
||||
attacker.hc.CheckRedirect = func(req *http.Request, _ []*http.Request) error {
|
||||
if strings.HasPrefix(req.URL.Path, "/sso/callback") {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
return nil
|
||||
}
|
||||
resp, err := attacker.hc.Get(attacker.base + "/sso/" + slug)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
callback := resp.Header.Get("Location")
|
||||
if got := e.browser(t).visit(strings.TrimPrefix(callback, attacker.base)); got.Query().Get("sso_error") != "sso_expired" {
|
||||
t.Errorf("replaying callback in another browser landed on %s, want sso_error=sso_expired", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("disabled provider", func(t *testing.T) {
|
||||
_, list := owner.do("GET", "/api/v1/org/sso", nil)
|
||||
p := list["providers"].([]any)[0].(map[string]any)
|
||||
st, body := owner.do("PUT", "/api/v1/org/sso/"+p["id"].(string), map[string]any{
|
||||
"name": p["name"], "issuer": p["issuer"], "client_id": p["client_id"], "enabled": false,
|
||||
})
|
||||
if st != http.StatusOK || body["has_client_secret"] != true {
|
||||
t.Fatalf("PUT provider = %d %v, want 200 keeping the secret", st, body)
|
||||
}
|
||||
if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_unavailable" {
|
||||
t.Errorf("SSO login with disabled provider landed on %s, want sso_error=sso_unavailable", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSSOProviderValidation(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("v")+".test", uniq("val-"))
|
||||
tests := []struct {
|
||||
name string
|
||||
body map[string]any
|
||||
want string
|
||||
}{
|
||||
{"bad scheme", map[string]any{"name": "x", "issuer": "ftp://idp.test", "client_id": "c"}, "sso_invalid_issuer"},
|
||||
{"unreachable", map[string]any{"name": "x", "issuer": "http://127.0.0.1:1", "client_id": "c"}, "sso_discovery_failed"},
|
||||
{"bad domain", map[string]any{"name": "x", "issuer": "https://idp.test", "client_id": "c", "allowed_domains": []string{"not a domain"}}, "invalid_domain"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
st, body := owner.do("POST", "/api/v1/org/sso", tt.body)
|
||||
if st != http.StatusUnprocessableEntity || body["error"] != tt.want {
|
||||
t.Errorf("POST /api/v1/org/sso = %d %v, want 422 %s", st, body["error"], tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user