diff --git a/.env.example b/.env.example index 095a33c..b1b024e 100644 --- a/.env.example +++ b/.env.example @@ -8,3 +8,8 @@ UPTIME_CHECKER_REGION=local # Generate with: echo "k1:$(head -c32 /dev/urandom | base64)" UPTIME_SECRET_KEYS=dev:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + +UPTIME_PUBLIC_URL=http://localhost:8080 +# Lets organizations use IdPs on private networks (e.g. an internal Keycloak). +# auto = allowed for UPTIME_EDITION=selfhosted, denied for cloud. +UPTIME_SSO_ALLOW_PRIVATE_NETWORKS=auto diff --git a/internal/api/pages.go b/internal/api/pages.go index 2d208cd..398e84f 100644 --- a/internal/api/pages.go +++ b/internal/api/pages.go @@ -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 } diff --git a/internal/api/server.go b/internal/api/server.go index 537a894..c0ba9d3 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -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) } diff --git a/internal/api/sso.go b/internal/api/sso.go new file mode 100644 index 0000000..252e9b5 --- /dev/null +++ b/internal/api/sso.go @@ -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 +} diff --git a/internal/api/sso_admin.go b/internal/api/sso_admin.go new file mode 100644 index 0000000..5d72986 --- /dev/null +++ b/internal/api/sso_admin.go @@ -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) +} diff --git a/internal/api/sso_test.go b/internal/api/sso_test.go new file mode 100644 index 0000000..9c9d57d --- /dev/null +++ b/internal/api/sso_test.go @@ -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) + } + }) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 92d7ae8..3aead1d 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -5,6 +5,8 @@ package config import ( "fmt" "log/slog" + "net/url" + "strings" "time" "github.com/caarlos0/env/v11" @@ -61,6 +63,22 @@ type API struct { Signup SignupMode `env:"UPTIME_SIGNUP" envDefault:"first-user"` SessionIdle time.Duration `env:"UPTIME_SESSION_IDLE" envDefault:"168h"` SessionAbsolute time.Duration `env:"UPTIME_SESSION_ABSOLUTE" envDefault:"720h"` + // PublicURL is the externally reachable base URL, used for SSO callbacks. + PublicURL string `env:"UPTIME_PUBLIC_URL" envDefault:"http://localhost:8080"` + // SSOPrivateNetworks is "auto", "true" or "false". Auto allows + // organizations' IdPs on private networks only in the self-hosted edition. + SSOPrivateNetworks string `env:"UPTIME_SSO_ALLOW_PRIVATE_NETWORKS" envDefault:"auto"` +} + +// SSOAllowPrivate resolves SSOPrivateNetworks. +func (a API) SSOAllowPrivate() bool { + switch a.SSOPrivateNetworks { + case "true": + return true + case "false": + return false + } + return a.Edition == EditionSelfHosted } // Validate checks API-specific settings in addition to Common.Validate. @@ -76,6 +94,14 @@ func (a API) Validate() error { default: return fmt.Errorf("config: unknown UPTIME_SIGNUP %q", a.Signup) } + switch a.SSOPrivateNetworks { + case "auto", "true", "false": + default: + return fmt.Errorf("config: UPTIME_SSO_ALLOW_PRIVATE_NETWORKS must be auto, true or false") + } + if u, err := url.Parse(a.PublicURL); err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") || strings.HasSuffix(a.PublicURL, "/") { + return fmt.Errorf("config: UPTIME_PUBLIC_URL must be an absolute http(s) URL without trailing slash") + } if a.SessionIdle <= 0 || a.SessionAbsolute < a.SessionIdle { return fmt.Errorf("config: UPTIME_SESSION_ABSOLUTE must be >= UPTIME_SESSION_IDLE > 0") } diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go index 614fe8c..998a6d6 100644 --- a/internal/i18n/i18n_test.go +++ b/internal/i18n/i18n_test.go @@ -61,6 +61,9 @@ var usagePatterns = []struct { {regexp.MustCompile(`i18n\.T\(ctx, "([a-z0-9_.]+)"[,)]`), ""}, {regexp.MustCompile(`\bfail\(c, [^,]+, "([a-z_]+)"`), "error."}, {regexp.MustCompile(`\b(?:pageFor\(c|s\.page\()(?:, )?"([a-z0-9_.]+)"`), ""}, + {regexp.MustCompile(`[^(]"(sso_[a-z_]+)"`), "error."}, + {regexp.MustCompile(`return "(invalid_[a-z_]+)"`), "error."}, + {regexp.MustCompile(`NoticeID = "([a-z0-9_.]+)"`), ""}, } // TestUsedKeysExist scans the source tree for literal message IDs so a typo diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index b59be86..df5e12e 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -1,57 +1,96 @@ { "app.network_error": "Verbindung fehlgeschlagen.", - "lang.en": "English", - "lang.de": "Deutsch", - - "auth.login.title": "Anmelden", - "auth.login.totp_hint": "Code aus der Authenticator-App eingeben.", - "auth.login.submit": "Weiter", - "auth.login.no_account": "Noch kein Konto?", - "auth.login.to_signup": "Registrieren", - "auth.signup.title": "Konto anlegen", - "auth.signup.submit": "Anlegen", - "auth.signup.to_login": "Zur Anmeldung", - "auth.field.name": "Name", + "auth.field.code": "Code", "auth.field.email": "E-Mail", - "auth.field.password": "Passwort", + "auth.field.name": "Name", "auth.field.new_password": "Passwort (min. {{.Min}} Zeichen)", "auth.field.org_name": "Organisation", "auth.field.org_slug": "Kurzname (a–z, 0–9, -)", - "auth.field.code": "Code", - - "console.nav.security": "Sicherheit", + "auth.field.password": "Passwort", + "auth.login.no_account": "Noch kein Konto?", + "auth.login.submit": "Weiter", + "auth.login.title": "Anmelden", + "auth.login.to_signup": "Registrieren", + "auth.login.totp_hint": "Code aus der Authenticator-App eingeben.", + "auth.signup.submit": "Anlegen", + "auth.signup.title": "Konto anlegen", + "auth.signup.to_login": "Zur Anmeldung", + "auth.sso.heading": "Single Sign-on", + "auth.sso.org_placeholder": "Kurzname der Organisation", + "auth.sso.submit": "Weiter", + "common.no": "nein", + "common.save": "Speichern", + "common.yes": "ja", + "console.monitors.empty": "Noch keine Monitore angelegt.", + "console.monitors.title": "Monitore", "console.nav.logout": "Abmelden", + "console.nav.security": "Sicherheit", + "console.nav.sso": "SSO", "console.totp_missing": "Deine Organisation verlangt Zwei-Faktor-Anmeldung.", "console.totp_missing_action": "Jetzt einrichten", - "console.monitors.title": "Monitore", - "console.monitors.empty": "Noch keine Monitore angelegt.", - - "security.title": "Sicherheit", - "security.totp.heading": "Zwei-Faktor (TOTP)", - "security.totp.active": "aktiv", - "security.totp.inactive": "nicht eingerichtet", - "security.totp.disable": "Deaktivieren", - "security.totp.current_code": "Aktueller Code", - "security.totp.start": "Einrichten", - "security.totp.qr_alt": "QR-Code für die Authenticator-App", - "security.totp.app_code": "Code aus der App", - "security.totp.confirm": "Bestätigen", - + "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.", + "error.forbidden": "Dafür fehlt dir die Berechtigung.", "error.internal": "Interner Fehler.", + "error.invalid_code": "Code ungültig.", + "error.invalid_credentials": "E-Mail oder Passwort falsch.", + "error.invalid_domain": "Eine der Domains ist ungültig.", "error.invalid_input": "Eingaben prüfen.", + "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.", + "error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.", + "error.no_password": "Konto ohne Passwort.", + "error.not_found": "Nicht gefunden.", + "error.org_not_found": "Organisation nicht gefunden.", + "error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.", "error.rate_limited": "Zu viele Versuche, bitte später erneut.", "error.signup_closed": "Registrierung ist deaktiviert.", - "error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.", - "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.", "error.slug_taken": "Dieser Kurzname ist bereits vergeben.", - "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.", - "error.invalid_credentials": "E-Mail oder Passwort falsch.", - "error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.", - "error.invalid_code": "Code ungültig.", - "error.org_not_found": "Organisation nicht gefunden.", + "error.sso_denied": "Die Anmeldung wurde beim Identity Provider abgebrochen.", + "error.sso_discovery_failed": "Der Identity Provider ist nicht erreichbar oder lieferte keine gültige Konfiguration.", + "error.sso_expired": "Der Anmeldeversuch ist abgelaufen, bitte neu starten.", + "error.sso_forbidden_address": "Der Issuer zeigt auf eine nicht öffentliche Adresse.", + "error.sso_identity_taken": "Diese SSO-Anmeldung ist bereits mit einem anderen Konto verknüpft.", + "error.sso_invalid_issuer": "Der Issuer muss eine https-URL ohne Query und Zugangsdaten sein.", + "error.sso_link_required": "Es gibt bereits ein Konto mit dieser E-Mail. Melde dich mit Passwort an und verknüpfe SSO unter Sicherheit.", + "error.sso_not_member": "Dein Konto ist kein Mitglied dieser Organisation.", + "error.sso_not_provisioned": "Für diese Anmeldung gibt es kein Konto. Bitte lass dich von einem Admin einladen.", + "error.sso_provider_error": "Der Identity Provider konnte die Anmeldung nicht abschließen.", + "error.sso_unavailable": "Für diese Organisation ist kein Single Sign-on verfügbar.", "error.totp_already_enabled": "TOTP ist bereits aktiv.", - "error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.", "error.totp_required_by_org": "Eine deiner Organisationen verlangt TOTP.", - "error.no_password": "Konto ohne Passwort.", - "error.unsupported_locale": "Sprache wird nicht unterstützt." + "error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.", + "error.unsupported_locale": "Sprache wird nicht unterstützt.", + "lang.de": "Deutsch", + "lang.en": "English", + "security.sso.heading": "Single Sign-on", + "security.sso.link": "SSO-Anmeldung verknüpfen", + "security.sso.linked": "SSO-Anmeldung verknüpft.", + "security.sso.none": "In dieser Organisation ist keine SSO-Anmeldung verknüpft.", + "security.title": "Sicherheit", + "security.totp.active": "aktiv", + "security.totp.app_code": "Code aus der App", + "security.totp.confirm": "Bestätigen", + "security.totp.current_code": "Aktueller Code", + "security.totp.disable": "Deaktivieren", + "security.totp.heading": "Zwei-Faktor (TOTP)", + "security.totp.inactive": "nicht eingerichtet", + "security.totp.qr_alt": "QR-Code für die Authenticator-App", + "security.totp.start": "Einrichten", + "sso.action.delete": "Provider löschen", + "sso.action.delete_confirm": "Diesen Provider löschen? Verknüpfte Anmeldungen funktionieren dann nicht mehr.", + "sso.action.edit": "Bearbeiten", + "sso.choose.title": "Anmeldung wählen", + "sso.field.allowed_domains": "Erlaubte E-Mail-Domains", + "sso.field.allowed_domains_hint": "Kommagetrennt. Gilt nur für automatisch angelegte Konten; leer erlaubt jede Domain.", + "sso.field.auto_provision": "Konten automatisch anlegen", + "sso.field.client_id": "Client-ID", + "sso.field.client_secret": "Client-Secret", + "sso.field.client_secret_keep": "unverändert", + "sso.field.enabled": "Aktiv", + "sso.field.issuer": "Issuer-URL", + "sso.field.name": "Name", + "sso.settings.add": "Provider hinzufügen", + "sso.settings.intro": "Mitglieder dieser Organisation können sich über euren eigenen OpenID-Connect-Identity-Provider anmelden. Tragt die Redirect-URL unten bei eurem Provider als erlaubten Callback ein.", + "sso.settings.login_url": "Anmelde-URL", + "sso.settings.redirect_url": "Redirect-URL", + "sso.settings.title": "Single Sign-on" } diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 8023c23..a480d22 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -1,57 +1,96 @@ { "app.network_error": "Connection failed.", - "lang.en": "English", - "lang.de": "Deutsch", - - "auth.login.title": "Sign in", - "auth.login.totp_hint": "Enter the code from your authenticator app.", - "auth.login.submit": "Continue", - "auth.login.no_account": "No account yet?", - "auth.login.to_signup": "Sign up", - "auth.signup.title": "Create account", - "auth.signup.submit": "Create", - "auth.signup.to_login": "Back to sign in", - "auth.field.name": "Name", + "auth.field.code": "Code", "auth.field.email": "Email", - "auth.field.password": "Password", + "auth.field.name": "Name", "auth.field.new_password": "Password (min. {{.Min}} characters)", "auth.field.org_name": "Organization", "auth.field.org_slug": "Short name (a–z, 0–9, -)", - "auth.field.code": "Code", - - "console.nav.security": "Security", + "auth.field.password": "Password", + "auth.login.no_account": "No account yet?", + "auth.login.submit": "Continue", + "auth.login.title": "Sign in", + "auth.login.to_signup": "Sign up", + "auth.login.totp_hint": "Enter the code from your authenticator app.", + "auth.signup.submit": "Create", + "auth.signup.title": "Create account", + "auth.signup.to_login": "Back to sign in", + "auth.sso.heading": "Single sign-on", + "auth.sso.org_placeholder": "Organization short name", + "auth.sso.submit": "Continue", + "common.no": "no", + "common.save": "Save", + "common.yes": "yes", + "console.monitors.empty": "No monitors yet.", + "console.monitors.title": "Monitors", "console.nav.logout": "Sign out", + "console.nav.security": "Security", + "console.nav.sso": "SSO", "console.totp_missing": "Your organization requires two-factor sign-in.", "console.totp_missing_action": "Set up now", - "console.monitors.title": "Monitors", - "console.monitors.empty": "No monitors yet.", - - "security.title": "Security", - "security.totp.heading": "Two-factor (TOTP)", - "security.totp.active": "active", - "security.totp.inactive": "not set up", - "security.totp.disable": "Disable", - "security.totp.current_code": "Current code", - "security.totp.start": "Set up", - "security.totp.qr_alt": "QR code for your authenticator app", - "security.totp.app_code": "Code from the app", - "security.totp.confirm": "Confirm", - + "error.email_taken": "This email address is already registered.", + "error.forbidden": "You are not allowed to do this.", "error.internal": "Internal error.", + "error.invalid_code": "Invalid code.", + "error.invalid_credentials": "Wrong email or password.", + "error.invalid_domain": "One of the domains is not valid.", "error.invalid_input": "Please check your input.", + "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.", + "error.mfa_expired": "Sign-in expired, please start again.", + "error.no_password": "This account has no password.", + "error.not_found": "Not found.", + "error.org_not_found": "Organization not found.", + "error.password_too_short": "The password needs at least {{.Min}} characters.", "error.rate_limited": "Too many attempts, please try again later.", "error.signup_closed": "Sign-up is disabled.", - "error.password_too_short": "The password needs at least {{.Min}} characters.", - "error.email_taken": "This email address is already registered.", "error.slug_taken": "This short name is already taken.", - "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.", - "error.invalid_credentials": "Wrong email or password.", - "error.mfa_expired": "Sign-in expired, please start again.", - "error.invalid_code": "Invalid code.", - "error.org_not_found": "Organization not found.", + "error.sso_denied": "Sign-in was cancelled at the identity provider.", + "error.sso_discovery_failed": "The identity provider could not be reached or returned no valid configuration.", + "error.sso_expired": "The sign-in attempt expired, please start again.", + "error.sso_forbidden_address": "The issuer points to a non-public address.", + "error.sso_identity_taken": "This SSO sign-in is already linked to another account.", + "error.sso_invalid_issuer": "The issuer must be an https URL without query or credentials.", + "error.sso_link_required": "An account with this email already exists. Sign in with your password and link SSO under Security.", + "error.sso_not_member": "Your account is not a member of this organization.", + "error.sso_not_provisioned": "No account exists for this sign-in. Ask an administrator to invite you.", + "error.sso_provider_error": "The identity provider could not complete the sign-in.", + "error.sso_unavailable": "Single sign-on is not available for this organization.", "error.totp_already_enabled": "TOTP is already active.", - "error.totp_setup_expired": "Setup expired, please start again.", "error.totp_required_by_org": "One of your organizations requires TOTP.", - "error.no_password": "This account has no password.", - "error.unsupported_locale": "Unsupported language." + "error.totp_setup_expired": "Setup expired, please start again.", + "error.unsupported_locale": "Unsupported language.", + "lang.de": "Deutsch", + "lang.en": "English", + "security.sso.heading": "Single sign-on", + "security.sso.link": "Link SSO sign-in", + "security.sso.linked": "SSO sign-in linked.", + "security.sso.none": "No SSO sign-in linked in this organization.", + "security.title": "Security", + "security.totp.active": "active", + "security.totp.app_code": "Code from the app", + "security.totp.confirm": "Confirm", + "security.totp.current_code": "Current code", + "security.totp.disable": "Disable", + "security.totp.heading": "Two-factor (TOTP)", + "security.totp.inactive": "not set up", + "security.totp.qr_alt": "QR code for your authenticator app", + "security.totp.start": "Set up", + "sso.action.delete": "Delete provider", + "sso.action.delete_confirm": "Delete this provider? Linked sign-ins stop working.", + "sso.action.edit": "Edit", + "sso.choose.title": "Choose sign-in", + "sso.field.allowed_domains": "Allowed email domains", + "sso.field.allowed_domains_hint": "Comma-separated. Only applies to automatically created accounts; empty allows any domain.", + "sso.field.auto_provision": "Create accounts automatically", + "sso.field.client_id": "Client ID", + "sso.field.client_secret": "Client secret", + "sso.field.client_secret_keep": "unchanged", + "sso.field.enabled": "Enabled", + "sso.field.issuer": "Issuer URL", + "sso.field.name": "Name", + "sso.settings.add": "Add provider", + "sso.settings.intro": "Members of this organization can sign in through your own OpenID Connect identity provider. Register the redirect URL below as an allowed callback at your provider.", + "sso.settings.login_url": "Sign-in URL", + "sso.settings.redirect_url": "Redirect URL", + "sso.settings.title": "Single sign-on" } diff --git a/internal/web/assets/app.js b/internal/web/assets/app.js index 9f8fb8b..6ad947f 100644 --- a/internal/web/assets/app.js +++ b/internal/web/assets/app.js @@ -17,24 +17,33 @@ el.classList.toggle("hidden", !text); }; + // Inputs inside a hidden [data-step] are skipped, checkboxes become + // booleans and [data-list] inputs become comma-separated arrays. + const serialize = (form) => { + const out = {}; + for (const el of form.elements) { + if (!el.name || el.disabled || el.closest("[data-step]")?.hidden) continue; + if (el.type === "checkbox") out[el.name] = el.checked; + else if (el.dataset.list !== undefined) + out[el.name] = el.value.split(",").map((v) => v.trim()).filter(Boolean); + else out[el.name] = el.value; + } + return out; + }; + document.addEventListener("submit", async (ev) => { const form = ev.target.closest("form[data-api]"); if (!form) return; ev.preventDefault(); const button = form.querySelector("button[type=submit]"); - const body = Object.fromEntries( - [...new FormData(form)].filter(([k]) => { - const step = form.querySelector(`[name="${k}"]`)?.closest("[data-step]"); - return !step || !step.hidden; - }), - ); + const body = serialize(form); const totpStep = form.querySelector('[data-step="totp"]'); const url = totpStep && !totpStep.hidden ? `${form.dataset.api}/totp` : form.dataset.api; showError(form, ""); button && (button.disabled = true); try { - const res = await api.post(url, body); + const res = await api.request({ method: form.dataset.method || "post", url, data: body }); if (res.data?.status === "totp_required" && totpStep) { form.querySelector('[data-step="password"]').hidden = true; totpStep.hidden = false; @@ -56,6 +65,17 @@ location.reload(); return; } + const del = ev.target.closest("[data-delete]"); + if (del) { + if (del.dataset.confirm && !confirm(del.dataset.confirm)) return; + try { + await api.delete(del.dataset.delete); + location.reload(); + } catch (err) { + alert(message(err)); + } + return; + } if (ev.target.closest("[data-logout]")) { await api.post("/auth/logout").catch(() => {}); location.assign("/login"); diff --git a/internal/web/auth.templ b/internal/web/auth.templ index c0f86d6..14d9f59 100644 --- a/internal/web/auth.templ +++ b/internal/web/auth.templ @@ -19,6 +19,20 @@ templ Login(p Page, signupAllowed bool) { @submit(i18n.T(ctx, "auth.login.submit")) +
+

{ i18n.T(ctx, "auth.sso.heading") }

+
+ + +
+
if signupAllowed {

{ i18n.T(ctx, "auth.login.no_account") } diff --git a/internal/web/auth_templ.go b/internal/web/auth_templ.go index 3e4ffba..6ed711c 100644 --- a/internal/web/auth_templ.go +++ b/internal/web/auth_templ.go @@ -92,38 +92,90 @@ func Login(p Page, signupAllowed bool) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var4 string + templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.heading")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 23, Col: 108} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if signupAllowed { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var4 string - templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account")) + var templ_7745c5c3_Var8 string + templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 24, Col: 42} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 38, Col: 42} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, " ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var5 string - templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup")) + var templ_7745c5c3_Var9 string + templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 25, Col: 105} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 39, Col: 105} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -155,7 +207,7 @@ func Signup(p Page) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var7 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var11 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -167,7 +219,7 @@ func Signup(p Page) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -187,7 +239,7 @@ func Signup(p Page) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -203,26 +255,26 @@ func Signup(p Page) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var8 string - templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login")) + var templ_7745c5c3_Var12 string + templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 43, Col: 137} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 57, Col: 137} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var7), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var11), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/internal/web/console.templ b/internal/web/console.templ index 4a7a5f0..fca2b8e 100644 --- a/internal/web/console.templ +++ b/internal/web/console.templ @@ -4,6 +4,9 @@ import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" // Me is the signed-in user as the console templates see it. type Me struct { + // IsOwner refers to the active organization. + IsOwner bool + ActiveSlug string Email string DisplayName string TOTP bool @@ -35,6 +38,9 @@ templ consoleShell(p Page, me Me) { { me.Orgs[0].Name } }