feat(api): enforce roles, org sign-in policies, invitations and api tokens
Every org route resolves a principal from the session or a bearer token and checks a permission. Nobody can grant, revoke or remove more than they hold. Tokens are capped by their owner's current rights and cannot manage credentials. Orgs can require TOTP or SSO; the owner keeps a password fallback for SSO. Closes #6 Closes #7 Closes #8 Closes #9 Closes #41 Closes #45 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
30409697f7
commit
d7d4821e3e
24 files changed
+4677
-439
No files matched your search
@@ -0,0 +1,153 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
const ctxPrincipal = "api.principal"
|
||||
|
||||
// principal is whoever acts on an organization in this request: a browser
|
||||
// session or an API token, together with what it may do there.
|
||||
type principal struct {
|
||||
UserID uuid.UUID
|
||||
Org store.Org
|
||||
Grants *authz.Grants
|
||||
// Session is nil for API token requests.
|
||||
Session *auth.Session
|
||||
// TokenID is set for API token requests.
|
||||
TokenID uuid.UUID
|
||||
}
|
||||
|
||||
func (p *principal) scope() tenant.Scope { return tenant.Org(p.Org.ID, p.UserID) }
|
||||
|
||||
func current(c *gin.Context) *principal { return c.MustGet(ctxPrincipal).(*principal) }
|
||||
|
||||
// loadGrants returns the member's permissions, or ok=false if userID is not
|
||||
// a member of org.
|
||||
func loadGrants(ctx context.Context, q *store.Queries, org, userID uuid.UUID) (g *authz.Grants, ok bool, err error) {
|
||||
m, err := q.GetMembership(ctx, store.GetMembershipParams{OrgID: org, UserID: userID})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
rows, err := q.MemberGrants(ctx, store.MemberGrantsParams{OrgID: org, UserID: userID})
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
g = &authz.Grants{Owner: m.IsOwner, Org: authz.Set{}, Scoped: map[authz.Resource]authz.Set{}}
|
||||
for _, r := range rows {
|
||||
perms := authz.NewSet(r.Permissions...)
|
||||
if r.ResourceType == nil || r.ResourceID == nil {
|
||||
g.Org = g.Org.Union(perms)
|
||||
continue
|
||||
}
|
||||
res := authz.Resource{Type: authz.ResourceType(*r.ResourceType), ID: *r.ResourceID}
|
||||
g.Scoped[res] = g.Scoped[res].Union(perms)
|
||||
}
|
||||
return g, true, nil
|
||||
}
|
||||
|
||||
// policyViolation returns the error code if sess may not act on org because
|
||||
// of the org's sign-in policy, or "" if it may.
|
||||
//
|
||||
// SSO sessions satisfy the TOTP requirement: multi-factor authentication is
|
||||
// then the identity provider's job. The owner may always sign in with a
|
||||
// password so a broken IdP cannot lock the organization out.
|
||||
func policyViolation(org store.Org, isOwner bool, sess *auth.Session) string {
|
||||
viaOrgSSO := sess.Method == auth.MethodSSO && sess.SSOOrg == org.ID
|
||||
if org.RequireSso && !viaOrgSSO && !isOwner {
|
||||
return "sso_required_by_org"
|
||||
}
|
||||
if org.RequireTotp && !viaOrgSSO && sess.Method != auth.MethodPasswordTOTP {
|
||||
return "totp_required_by_org"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// orgAccess authenticates the request against the session's active
|
||||
// organization, enforces its sign-in policy and attaches a principal.
|
||||
func (s *Server) orgAccess() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
p, status, code, err := s.resolvePrincipal(c)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if code != "" {
|
||||
fail(c, status, code)
|
||||
return
|
||||
}
|
||||
c.Set(ctxPrincipal, p)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) resolvePrincipal(c *gin.Context) (*principal, int, string, error) {
|
||||
if tok := bearerToken(c); tok != "" {
|
||||
return s.tokenPrincipal(c.Request.Context(), tok)
|
||||
}
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
return nil, http.StatusUnauthorized, "unauthenticated", nil
|
||||
}
|
||||
if sess.OrgID == uuid.Nil {
|
||||
return nil, http.StatusForbidden, "forbidden", nil
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
p := &principal{UserID: sess.UserID, Session: sess}
|
||||
var member bool
|
||||
err := s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error {
|
||||
var err error
|
||||
if p.Org, err = q.GetOrg(ctx, sess.OrgID); err != nil {
|
||||
return err
|
||||
}
|
||||
p.Grants, member, err = loadGrants(ctx, q, sess.OrgID, sess.UserID)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !member) {
|
||||
return nil, http.StatusForbidden, "forbidden", nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, 0, "", err
|
||||
}
|
||||
if code := policyViolation(p.Org, p.Grants.Owner, sess); code != "" {
|
||||
return nil, http.StatusForbidden, code, nil
|
||||
}
|
||||
return p, 0, "", nil
|
||||
}
|
||||
|
||||
// can aborts unless the principal holds perm organization-wide.
|
||||
func can(perm authz.Permission) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !current(c).Grants.Can(perm) {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// sessionOnly rejects API tokens on routes that manage credentials, so a
|
||||
// leaked token cannot mint further tokens or change who has access.
|
||||
func sessionOnly() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if current(c).Session == nil {
|
||||
fail(c, http.StatusForbidden, "session_required")
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ func (s *Server) signup(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.startSession(c, user.ID, orgID, i18n.Lang(ctx))
|
||||
s.startSession(c, auth.NewSession{UserID: user.ID, OrgID: orgID, Locale: i18n.Lang(ctx), Method: auth.MethodPassword})
|
||||
}
|
||||
|
||||
func (s *Server) signupAllowed(ctx context.Context) (bool, error) {
|
||||
@@ -164,7 +164,7 @@ func (s *Server) login(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "totp_required"})
|
||||
return
|
||||
}
|
||||
s.finishLogin(c, user.ID)
|
||||
s.finishLogin(c, user.ID, auth.MethodPassword)
|
||||
}
|
||||
|
||||
// secondFactorRequest carries a TOTP code or a recovery code.
|
||||
@@ -211,10 +211,10 @@ func (s *Server) loginTOTP(c *gin.Context) {
|
||||
}
|
||||
_ = s.rdb.Del(ctx, mfaKey(token)).Err()
|
||||
setCookie(c, mfaCookie, "", -1)
|
||||
s.finishLogin(c, userID)
|
||||
s.finishLogin(c, userID, auth.MethodPasswordTOTP)
|
||||
}
|
||||
|
||||
func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID) {
|
||||
func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID, method auth.Method) {
|
||||
ctx := c.Request.Context()
|
||||
var (
|
||||
user store.User
|
||||
@@ -236,14 +236,14 @@ func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID) {
|
||||
if len(orgs) > 0 {
|
||||
org = orgs[0].ID
|
||||
}
|
||||
s.startSession(c, userID, org, deref(user.Locale))
|
||||
s.startSession(c, auth.NewSession{UserID: userID, OrgID: org, Locale: deref(user.Locale), Method: method})
|
||||
}
|
||||
|
||||
func (s *Server) startSession(c *gin.Context, userID, orgID uuid.UUID, locale string) {
|
||||
func (s *Server) startSession(c *gin.Context, n auth.NewSession) {
|
||||
if old := auth.Current(c); old != nil {
|
||||
_ = s.sessions.Delete(c.Request.Context(), old)
|
||||
}
|
||||
sess, err := s.sessions.Create(c.Request.Context(), userID, orgID, locale)
|
||||
sess, err := s.sessions.Create(c.Request.Context(), n)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"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 invitationTTL = 7 * 24 * time.Hour
|
||||
|
||||
type inviteRequest struct {
|
||||
Email string `json:"email" binding:"required,max=320"`
|
||||
RoleID uuid.UUID `json:"role_id" binding:"required"`
|
||||
}
|
||||
|
||||
func (s *Server) createInvitation(c *gin.Context) {
|
||||
var req inviteRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
email := normalizeEmail(req.Email)
|
||||
if addr, err := mail.ParseAddress(email); err != nil || addr.Address != email {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_email")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
tok := auth.RandomToken()
|
||||
var code string
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
role, err := q.GetRole(ctx, req.RoleID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
code = "role_not_found"
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !p.Grants.CanGrant(authz.NewSet(role.Permissions...), nil) {
|
||||
code = "permission_escalation"
|
||||
return nil
|
||||
}
|
||||
members, err := q.ListOrgMembers(ctx, p.Org.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range members {
|
||||
if m.Email == email {
|
||||
code = "already_member"
|
||||
return nil
|
||||
}
|
||||
}
|
||||
_, err = q.CreateInvitation(ctx, store.CreateInvitationParams{
|
||||
OrgID: p.Org.ID, Email: email, RoleID: role.ID, TokenHash: hashToken(tok),
|
||||
InvitedBy: &p.UserID, ExpiresAt: time.Now().Add(invitationTTL),
|
||||
})
|
||||
return err
|
||||
})
|
||||
switch {
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
case code == "role_not_found":
|
||||
fail(c, http.StatusNotFound, code)
|
||||
case code == "permission_escalation":
|
||||
fail(c, http.StatusForbidden, code)
|
||||
case code != "":
|
||||
fail(c, http.StatusConflict, code)
|
||||
default:
|
||||
// There is no mailer yet; the inviter passes the link on.
|
||||
c.JSON(http.StatusCreated, gin.H{"url": s.cfg.PublicURL + "/invite/" + tok})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) listInvitations(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.ListPendingInvitationsRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListPendingInvitations(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
type view struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Email string `json:"email"`
|
||||
RoleName string `json:"role_name"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
out := make([]view, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = view{ID: r.ID, Email: r.Email, RoleName: r.RoleName, ExpiresAt: r.ExpiresAt}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"invitations": out})
|
||||
}
|
||||
|
||||
func (s *Server) deleteInvitation(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
n, err = q.DeleteInvitation(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)
|
||||
}
|
||||
|
||||
// findInvitation returns the invitation for tok, or ok=false if it does not
|
||||
// exist, was used or has expired.
|
||||
func (s *Server) findInvitation(ctx context.Context, tok string) (inv store.GetInvitationByHashRow, ok bool, err error) {
|
||||
hash := hashToken(tok)
|
||||
var org uuid.UUID
|
||||
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
org, err = q.InvitationOrg(ctx, hash)
|
||||
return err
|
||||
})
|
||||
if err != nil || org == uuid.Nil {
|
||||
return inv, false, err
|
||||
}
|
||||
err = s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error {
|
||||
inv, err = q.GetInvitationByHash(ctx, hash)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return inv, false, err
|
||||
}
|
||||
return inv, inv.AcceptedAt == nil && inv.ExpiresAt.After(time.Now()), nil
|
||||
}
|
||||
|
||||
// join makes userID a member with the invited role. The inviter must still
|
||||
// be allowed to grant that role; rights lost since inviting are not passed
|
||||
// on through a pending invitation.
|
||||
func (s *Server) join(ctx context.Context, inv store.GetInvitationByHashRow, userID uuid.UUID) (string, error) {
|
||||
var code string
|
||||
err := s.db.Tx(ctx, tenant.Org(inv.OrgID, userID), func(q *store.Queries) error {
|
||||
if inv.InvitedBy == nil {
|
||||
code = "invitation_invalid"
|
||||
return nil
|
||||
}
|
||||
g, member, err := loadGrants(ctx, q, inv.OrgID, *inv.InvitedBy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
role, err := q.GetRole(ctx, inv.RoleID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member || !g.CanGrant(authz.NewSet(role.Permissions...), nil) {
|
||||
code = "invitation_invalid"
|
||||
return nil
|
||||
}
|
||||
n, err := q.MarkInvitationAccepted(ctx, inv.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
code = "invitation_invalid"
|
||||
return nil
|
||||
}
|
||||
if already, err := q.IsMember(ctx, store.IsMemberParams{OrgID: inv.OrgID, UserID: userID}); err != nil {
|
||||
return err
|
||||
} else if !already {
|
||||
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: inv.OrgID, UserID: userID}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = q.CreateAssignment(ctx, store.CreateAssignmentParams{OrgID: inv.OrgID, UserID: userID, RoleID: inv.RoleID})
|
||||
if isUniqueViolation(err, "role_assignments_org_id_user_id_role_id_resource_type_resou_key") {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
})
|
||||
return code, err
|
||||
}
|
||||
|
||||
func (s *Server) acceptInvitation(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
sess := auth.Current(c)
|
||||
inv, ok, err := s.findInvitation(ctx, c.Param("token"))
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
fail(c, http.StatusGone, "invitation_invalid")
|
||||
return
|
||||
}
|
||||
me, err := s.loadMe(ctx, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if me.Email != inv.Email {
|
||||
fail(c, http.StatusForbidden, "invitation_email_mismatch")
|
||||
return
|
||||
}
|
||||
code, err := s.join(ctx, inv, sess.UserID)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if code != "" {
|
||||
fail(c, http.StatusGone, code)
|
||||
return
|
||||
}
|
||||
if err := s.sessions.SwitchOrg(ctx, sess, inv.OrgID); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type inviteSignupRequest struct {
|
||||
DisplayName string `json:"display_name" binding:"max=200"`
|
||||
Password string `json:"password" binding:"required,max=1024"`
|
||||
}
|
||||
|
||||
// inviteSignup creates an account for an invited address. It bypasses
|
||||
// UPTIME_SIGNUP because the organization vouched for the invitee.
|
||||
func (s *Server) inviteSignup(c *gin.Context) {
|
||||
var req inviteSignupRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
if !s.limit(c, "signup:"+c.ClientIP(), 10, time.Hour) {
|
||||
return
|
||||
}
|
||||
inv, ok, err := s.findInvitation(ctx, c.Param("token"))
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
fail(c, http.StatusGone, "invitation_invalid")
|
||||
return
|
||||
}
|
||||
hash, err := auth.HashPassword(req.Password)
|
||||
if errors.Is(err, auth.ErrPasswordTooShort) {
|
||||
fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
var user store.User
|
||||
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
user, err = q.CreateUser(ctx, store.CreateUserParams{
|
||||
Email: inv.Email, DisplayName: strings.TrimSpace(req.DisplayName),
|
||||
PasswordHash: &hash, Locale: ptr(i18n.Lang(ctx)),
|
||||
})
|
||||
return err
|
||||
})
|
||||
if isUniqueViolation(err, "users_email_key") {
|
||||
fail(c, http.StatusConflict, "email_taken")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
code, err := s.join(ctx, inv, user.ID)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if code != "" {
|
||||
fail(c, http.StatusGone, code)
|
||||
return
|
||||
}
|
||||
s.startSession(c, auth.NewSession{UserID: user.ID, OrgID: inv.OrgID, Locale: i18n.Lang(ctx), Method: auth.MethodPassword})
|
||||
}
|
||||
|
||||
func (s *Server) invitePage(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
tok := c.Param("token")
|
||||
inv, ok, err := s.findInvitation(ctx, tok)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
view := web.Invitation{Token: tok, Valid: ok}
|
||||
if ok {
|
||||
view.OrgName, view.RoleName, view.Email = inv.OrgName, inv.RoleName, inv.Email
|
||||
if sess := auth.Current(c); sess != nil {
|
||||
me, err := s.loadMe(ctx, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
view.SignedInAs = me.Email
|
||||
} else {
|
||||
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
_, err := q.GetUserByEmail(ctx, inv.Email)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
view.AccountExists = err == nil
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.InvitationPage(s.pageFor(c, "invite.title"), view))
|
||||
}
|
||||
@@ -171,6 +171,12 @@ func (s *Server) totpEnable(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
_ = s.rdb.Del(ctx, totpSetupKey(sess.UserID)).Err()
|
||||
if sess.Method == auth.MethodPassword || sess.Method == "" {
|
||||
if err := s.sessions.SetMethod(ctx, sess, auth.MethodPasswordTOTP); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"recovery_codes": codes})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,475 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
)
|
||||
|
||||
type assignmentView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
RoleID uuid.UUID `json:"role_id"`
|
||||
RoleName string `json:"role_name"`
|
||||
RoleKey *string `json:"role_key,omitempty"`
|
||||
ResourceType *string `json:"resource_type,omitempty"`
|
||||
ResourceID *uuid.UUID `json:"resource_id,omitempty"`
|
||||
}
|
||||
|
||||
type memberView struct {
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"display_name"`
|
||||
IsOwner bool `json:"is_owner"`
|
||||
JoinedAt time.Time `json:"joined_at"`
|
||||
Assignments []assignmentView `json:"assignments"`
|
||||
}
|
||||
|
||||
func (s *Server) loadMembers(c *gin.Context) ([]memberView, error) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var out []memberView
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
members, err := q.ListOrgMembers(ctx, p.Org.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
assigns, err := q.ListAssignments(ctx, p.Org.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
byUser := map[uuid.UUID][]assignmentView{}
|
||||
for _, a := range assigns {
|
||||
byUser[a.UserID] = append(byUser[a.UserID], assignmentView{
|
||||
ID: a.ID, RoleID: a.RoleID, RoleName: a.RoleName, RoleKey: a.RoleKey,
|
||||
ResourceType: a.ResourceType, ResourceID: a.ResourceID,
|
||||
})
|
||||
}
|
||||
out = make([]memberView, len(members))
|
||||
for i, m := range members {
|
||||
out[i] = memberView{
|
||||
UserID: m.ID, Email: m.Email, DisplayName: m.DisplayName, IsOwner: m.IsOwner,
|
||||
JoinedAt: m.JoinedAt, Assignments: byUser[m.ID],
|
||||
}
|
||||
if out[i].Assignments == nil {
|
||||
out[i].Assignments = []assignmentView{}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (s *Server) listMembers(c *gin.Context) {
|
||||
members, err := s.loadMembers(c)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"members": members})
|
||||
}
|
||||
|
||||
// removeMember requires the actor to hold every permission the member holds
|
||||
// organization-wide, so a delegated admin cannot remove a stronger one.
|
||||
func (s *Server) removeMember(c *gin.Context) {
|
||||
target, err := uuid.Parse(c.Param("user"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var code string
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
g, member, err := loadGrants(ctx, q, p.Org.ID, target)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case !member:
|
||||
code = "not_found"
|
||||
case g.Owner:
|
||||
code = "owner_cannot_be_removed"
|
||||
case !p.Grants.CanGrant(g.Org, nil):
|
||||
code = "permission_escalation"
|
||||
default:
|
||||
_, err = q.RemoveMembership(ctx, store.RemoveMembershipParams{OrgID: p.Org.ID, UserID: target})
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
switch code {
|
||||
case "":
|
||||
_ = s.sessions.DeleteAllForUser(ctx, target)
|
||||
c.Status(http.StatusNoContent)
|
||||
case "not_found":
|
||||
fail(c, http.StatusNotFound, code)
|
||||
default:
|
||||
fail(c, http.StatusForbidden, code)
|
||||
}
|
||||
}
|
||||
|
||||
type assignRequest struct {
|
||||
RoleID uuid.UUID `json:"role_id" binding:"required"`
|
||||
ResourceType string `json:"resource_type" binding:"omitempty,oneof=monitor_group status_page"`
|
||||
ResourceID *uuid.UUID `json:"resource_id"`
|
||||
}
|
||||
|
||||
func (r assignRequest) scope() (*authz.Resource, bool) {
|
||||
if r.ResourceType == "" && r.ResourceID == nil {
|
||||
return nil, true
|
||||
}
|
||||
if r.ResourceID == nil {
|
||||
return nil, false
|
||||
}
|
||||
res := authz.Resource{Type: authz.ResourceType(r.ResourceType), ID: *r.ResourceID}
|
||||
return &res, res.Valid()
|
||||
}
|
||||
|
||||
func (s *Server) assignRole(c *gin.Context) {
|
||||
target, err := uuid.Parse(c.Param("user"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req assignRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
scope, ok := req.scope()
|
||||
if !ok {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var (
|
||||
code string
|
||||
row store.RoleAssignment
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
role, err := q.GetRole(ctx, req.RoleID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
code = "role_not_found"
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m, err := q.GetMembership(ctx, store.GetMembershipParams{OrgID: p.Org.ID, UserID: target})
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
code = "not_found"
|
||||
return nil
|
||||
case err != nil:
|
||||
return err
|
||||
case m.IsOwner:
|
||||
code = "owner_has_all_permissions"
|
||||
return nil
|
||||
case !p.Grants.CanGrant(authz.NewSet(role.Permissions...), scope):
|
||||
code = "permission_escalation"
|
||||
return nil
|
||||
}
|
||||
params := store.CreateAssignmentParams{OrgID: p.Org.ID, UserID: target, RoleID: role.ID}
|
||||
if scope != nil {
|
||||
rt := string(scope.Type)
|
||||
params.ResourceType, params.ResourceID = &rt, &scope.ID
|
||||
}
|
||||
row, err = q.CreateAssignment(ctx, params)
|
||||
if isUniqueViolation(err, "role_assignments_org_id_user_id_role_id_resource_type_resou_key") {
|
||||
code = "already_assigned"
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
switch code {
|
||||
case "":
|
||||
c.JSON(http.StatusCreated, gin.H{"id": row.ID})
|
||||
case "not_found", "role_not_found":
|
||||
fail(c, http.StatusNotFound, code)
|
||||
case "already_assigned", "owner_has_all_permissions":
|
||||
fail(c, http.StatusConflict, code)
|
||||
default:
|
||||
fail(c, http.StatusForbidden, code)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) unassignRole(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var code string
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
a, err := q.GetAssignment(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
code = "not_found"
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
role, err := q.GetRole(ctx, a.RoleID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var scope *authz.Resource
|
||||
if a.ResourceType != nil && a.ResourceID != nil {
|
||||
scope = &authz.Resource{Type: authz.ResourceType(*a.ResourceType), ID: *a.ResourceID}
|
||||
}
|
||||
if !p.Grants.CanGrant(authz.NewSet(role.Permissions...), scope) {
|
||||
code = "permission_escalation"
|
||||
return nil
|
||||
}
|
||||
_, err = q.DeleteAssignment(ctx, id)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
switch code {
|
||||
case "":
|
||||
c.Status(http.StatusNoContent)
|
||||
case "not_found":
|
||||
fail(c, http.StatusNotFound, code)
|
||||
default:
|
||||
fail(c, http.StatusForbidden, code)
|
||||
}
|
||||
}
|
||||
|
||||
type roleView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Key *string `json:"key,omitempty"`
|
||||
Name string `json:"name"`
|
||||
BuiltIn bool `json:"built_in"`
|
||||
Permissions []string `json:"permissions"`
|
||||
}
|
||||
|
||||
func viewRole(r store.Role) roleView {
|
||||
return roleView{ID: r.ID, Key: r.Key, Name: r.Name, BuiltIn: r.OrgID == nil, Permissions: authz.NewSet(r.Permissions...).Strings()}
|
||||
}
|
||||
|
||||
func (s *Server) listRoles(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.Role
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListRoles(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]roleView, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = viewRole(r)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"roles": out, "permissions": authz.NewSet(authz.All...).Strings()})
|
||||
}
|
||||
|
||||
type roleRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Permissions []string `json:"permissions" binding:"required,min=1,max=50,dive,max=50"`
|
||||
}
|
||||
|
||||
func (s *Server) createRole(c *gin.Context) {
|
||||
var req roleRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
perms := authz.NewSet(req.Permissions...)
|
||||
p := current(c)
|
||||
if len(perms) == 0 || strings.TrimSpace(req.Name) == "" {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_permissions")
|
||||
return
|
||||
}
|
||||
if !p.Grants.CanGrant(perms, nil) {
|
||||
fail(c, http.StatusForbidden, "permission_escalation")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var row store.Role
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateRole(ctx, store.CreateRoleParams{OrgID: &p.Org.ID, Name: strings.TrimSpace(req.Name), Permissions: perms.Strings()})
|
||||
return err
|
||||
})
|
||||
if isUniqueViolation(err, "roles_org_id_name_key") {
|
||||
fail(c, http.StatusConflict, "role_name_taken")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, viewRole(row))
|
||||
}
|
||||
|
||||
// updateRole requires the actor to hold both the old and the new
|
||||
// permissions: otherwise they could strip rights they cannot grant back, or
|
||||
// widen a role they are assigned to.
|
||||
func (s *Server) updateRole(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req roleRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
perms := authz.NewSet(req.Permissions...)
|
||||
if len(perms) == 0 || strings.TrimSpace(req.Name) == "" {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_permissions")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var (
|
||||
code string
|
||||
row store.Role
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
old, err := q.GetRole(ctx, id)
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
code = "not_found"
|
||||
return nil
|
||||
case err != nil:
|
||||
return err
|
||||
case old.OrgID == nil:
|
||||
code = "role_built_in"
|
||||
return nil
|
||||
case !p.Grants.CanGrant(perms.Union(authz.NewSet(old.Permissions...)), nil):
|
||||
code = "permission_escalation"
|
||||
return nil
|
||||
}
|
||||
row, err = q.UpdateRole(ctx, store.UpdateRoleParams{ID: id, Name: strings.TrimSpace(req.Name), Permissions: perms.Strings()})
|
||||
if isUniqueViolation(err, "roles_org_id_name_key") {
|
||||
code = "role_name_taken"
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
})
|
||||
s.roleResult(c, err, code, func() { c.JSON(http.StatusOK, viewRole(row)) })
|
||||
}
|
||||
|
||||
func (s *Server) deleteRole(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var code string
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
old, err := q.GetRole(ctx, id)
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
code = "not_found"
|
||||
return nil
|
||||
case err != nil:
|
||||
return err
|
||||
case old.OrgID == nil:
|
||||
code = "role_built_in"
|
||||
return nil
|
||||
case !p.Grants.CanGrant(authz.NewSet(old.Permissions...), nil):
|
||||
code = "permission_escalation"
|
||||
return nil
|
||||
}
|
||||
n, err := q.CountRoleAssignments(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n > 0 {
|
||||
code = "role_in_use"
|
||||
return nil
|
||||
}
|
||||
_, err = q.DeleteRole(ctx, id)
|
||||
return err
|
||||
})
|
||||
s.roleResult(c, err, code, func() { c.Status(http.StatusNoContent) })
|
||||
}
|
||||
|
||||
func (s *Server) roleResult(c *gin.Context, err error, code string, ok func()) {
|
||||
switch {
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
case code == "":
|
||||
ok()
|
||||
case code == "not_found":
|
||||
fail(c, http.StatusNotFound, code)
|
||||
case code == "permission_escalation":
|
||||
fail(c, http.StatusForbidden, code)
|
||||
default:
|
||||
fail(c, http.StatusConflict, code)
|
||||
}
|
||||
}
|
||||
|
||||
type policyRequest struct {
|
||||
RequireTOTP bool `json:"require_totp"`
|
||||
RequireSSO bool `json:"require_sso"`
|
||||
}
|
||||
|
||||
func (s *Server) updatePolicy(c *gin.Context) {
|
||||
var req policyRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
// The actor must already meet a policy before switching it on, or the
|
||||
// change would lock them out on their next request.
|
||||
probe := p.Org
|
||||
probe.RequireTotp, probe.RequireSso = req.RequireTOTP, req.RequireSSO
|
||||
if code := policyViolation(probe, p.Grants.Owner, p.Session); code != "" {
|
||||
fail(c, http.StatusConflict, "policy_would_lock_you_out")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var org store.Org
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
if req.RequireSSO {
|
||||
providers, err := q.ListEnabledSSOProviders(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(providers) == 0 {
|
||||
return errNoSSOProvider
|
||||
}
|
||||
}
|
||||
var err error
|
||||
org, err = q.UpdateOrgPolicy(ctx, store.UpdateOrgPolicyParams{ID: p.Org.ID, RequireTotp: req.RequireTOTP, RequireSso: req.RequireSSO})
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, errNoSSOProvider) {
|
||||
fail(c, http.StatusConflict, "sso_no_provider")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"require_totp": org.RequireTotp, "require_sso": org.RequireSso})
|
||||
}
|
||||
|
||||
var errNoSSOProvider = errors.New("api: no enabled sso provider")
|
||||
+236
-34
@@ -3,12 +3,15 @@ package api
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"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"
|
||||
@@ -17,9 +20,14 @@ import (
|
||||
func (s *Server) registerPages(r gin.IRouter) {
|
||||
r.GET("/login", s.loginPage)
|
||||
r.GET("/signup", s.signupPage)
|
||||
r.GET("/invite/:token", s.invitePage)
|
||||
r.GET("/", s.page("console.monitors.title", web.Dashboard))
|
||||
r.GET("/settings/security", s.securityPage)
|
||||
r.GET("/settings/sso", s.ssoSettingsPage)
|
||||
r.GET("/settings/sso", s.orgPage("sso.settings.title", authz.OrgManage, s.ssoSettingsView))
|
||||
r.GET("/settings/org", s.orgPage("org.title", authz.OrgManage, s.orgSettingsView))
|
||||
r.GET("/settings/members", s.orgPage("members.title", authz.MembersRead, s.membersView))
|
||||
r.GET("/settings/roles", s.orgPage("roles.title", authz.MembersRead, s.rolesView))
|
||||
r.GET("/settings/tokens", s.orgPage("tokens.title", "", s.tokensView))
|
||||
}
|
||||
|
||||
// flashErrors lists the codes a redirect may ask a page to display. Anything
|
||||
@@ -28,6 +36,7 @@ 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,
|
||||
"totp_required_by_org": true, "sso_required_by_org": true,
|
||||
}
|
||||
|
||||
func (s *Server) pageFor(c *gin.Context, titleID string) web.Page {
|
||||
@@ -44,9 +53,19 @@ func (s *Server) pageFor(c *gin.Context, titleID string) web.Page {
|
||||
return p
|
||||
}
|
||||
|
||||
// localPath returns next if it is a path on this site, so login redirects
|
||||
// cannot send users to another origin.
|
||||
func localPath(next string) string {
|
||||
if strings.HasPrefix(next, "/") && !strings.HasPrefix(next, "//") && !strings.Contains(next, `\`) {
|
||||
return next
|
||||
}
|
||||
return "/"
|
||||
}
|
||||
|
||||
func (s *Server) loginPage(c *gin.Context) {
|
||||
next := localPath(c.Query("next"))
|
||||
if auth.Current(c) != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
c.Redirect(http.StatusSeeOther, next)
|
||||
return
|
||||
}
|
||||
allowed, err := s.signupAllowed(c.Request.Context())
|
||||
@@ -54,7 +73,7 @@ func (s *Server) loginPage(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Login(s.pageFor(c, "auth.login.title"), allowed))
|
||||
web.Render(c, http.StatusOK, web.Login(s.pageFor(c, "auth.login.title"), allowed, next))
|
||||
}
|
||||
|
||||
func (s *Server) signupPage(c *gin.Context) {
|
||||
@@ -70,30 +89,100 @@ func (s *Server) signupPage(c *gin.Context) {
|
||||
web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title")))
|
||||
}
|
||||
|
||||
// consoleMe loads the signed-in user and, if an organization is active,
|
||||
// their permissions and policy state there. The principal is nil when the
|
||||
// user has no active organization or is no longer a member.
|
||||
func (s *Server) consoleMe(c *gin.Context, sess *auth.Session) (web.Me, *principal, error) {
|
||||
ctx := c.Request.Context()
|
||||
m, err := s.loadMe(ctx, sess)
|
||||
if err != nil {
|
||||
return web.Me{}, nil, err
|
||||
}
|
||||
me := toWebMe(m)
|
||||
me.Can = map[string]bool{}
|
||||
if sess.OrgID == uuid.Nil {
|
||||
return me, nil, nil
|
||||
}
|
||||
p := &principal{UserID: sess.UserID, Session: sess}
|
||||
var member bool
|
||||
err = s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error {
|
||||
var err error
|
||||
if p.Org, err = q.GetOrg(ctx, sess.OrgID); err != nil {
|
||||
return err
|
||||
}
|
||||
p.Grants, member, err = loadGrants(ctx, q, sess.OrgID, sess.UserID)
|
||||
return err
|
||||
})
|
||||
if err != nil || !member {
|
||||
return me, nil, err
|
||||
}
|
||||
for _, perm := range authz.All {
|
||||
me.Can[string(perm)] = p.Grants.Can(perm)
|
||||
}
|
||||
me.Policy = policyViolation(p.Org, p.Grants.Owner, sess)
|
||||
return me, p, nil
|
||||
}
|
||||
|
||||
func (s *Server) page(titleID string, view func(web.Page, web.Me) templ.Component) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
c.Redirect(http.StatusSeeOther, "/login?next="+c.Request.URL.Path)
|
||||
return
|
||||
}
|
||||
me, err := s.loadMe(c.Request.Context(), sess)
|
||||
me, _, err := s.consoleMe(c, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, view(s.pageFor(c, titleID), toWebMe(me)))
|
||||
web.Render(c, http.StatusOK, view(s.pageFor(c, titleID), me))
|
||||
}
|
||||
}
|
||||
|
||||
type orgPageView func(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error)
|
||||
|
||||
// orgPage renders an organization settings page. perm may be empty for
|
||||
// pages every member can open.
|
||||
func (s *Server) orgPage(titleID string, perm authz.Permission, view orgPageView) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login?next="+c.Request.URL.Path)
|
||||
return
|
||||
}
|
||||
me, p, err := s.consoleMe(c, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case p == nil:
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
return
|
||||
case me.Policy != "":
|
||||
c.Redirect(http.StatusSeeOther, "/settings/security?sso_error="+me.Policy)
|
||||
return
|
||||
case perm != "" && !p.Grants.Can(perm):
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
return
|
||||
}
|
||||
comp, err := view(c, p, s.pageFor(c, titleID), me)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, comp)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) securityPage(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
c.Redirect(http.StatusSeeOther, "/login?next=/settings/security")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
me, err := s.loadMe(ctx, sess)
|
||||
me, _, err := s.consoleMe(c, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -120,47 +209,161 @@ func (s *Server) securityPage(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), toWebMe(me), identities, canLink))
|
||||
web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), me, identities, canLink))
|
||||
}
|
||||
|
||||
func (s *Server) ssoSettingsPage(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
func toWebRoles(rows []store.Role) []web.Role {
|
||||
out := make([]web.Role, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = web.Role{ID: r.ID.String(), Name: r.Name, BuiltIn: r.OrgID == nil, Permissions: authz.NewSet(r.Permissions...).Strings()}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// grantable lists the permissions p may hand out organization-wide.
|
||||
func grantable(p *principal) []string {
|
||||
var out []string
|
||||
for _, perm := range authz.All {
|
||||
if p.Grants.CanGrant(authz.NewSet(perm), nil) {
|
||||
out = append(out, string(perm))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) ssoSettingsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
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)
|
||||
var (
|
||||
rows []store.SsoProvider
|
||||
roles []store.Role
|
||||
)
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if rows, err = q.ListSSOProviders(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
roles, err = q.ListRoles(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
view := web.SSOSettings{
|
||||
RedirectURL: s.sso.RedirectURL(),
|
||||
LoginURL: s.cfg.PublicURL + "/sso/" + wm.ActiveSlug,
|
||||
LoginURL: s.cfg.PublicURL + "/sso/" + p.Org.Slug,
|
||||
Roles: toWebRoles(roles),
|
||||
}
|
||||
for _, r := range rows {
|
||||
view.Providers = append(view.Providers, web.SSOProvider{
|
||||
pr := 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,
|
||||
})
|
||||
}
|
||||
if r.DefaultRoleID != nil {
|
||||
pr.DefaultRoleID = r.DefaultRoleID.String()
|
||||
}
|
||||
view.Providers = append(view.Providers, pr)
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.SSOSettingsPage(s.pageFor(c, "sso.settings.title"), wm, view))
|
||||
return web.SSOSettingsPage(page, me, view), nil
|
||||
}
|
||||
|
||||
func (s *Server) orgSettingsView(_ *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
return web.OrgSettingsPage(page, me, web.OrgSettings{RequireTOTP: p.Org.RequireTotp, RequireSSO: p.Org.RequireSso}), nil
|
||||
}
|
||||
|
||||
func (s *Server) membersView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
c.Set(ctxPrincipal, p)
|
||||
members, err := s.loadMembers(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var (
|
||||
roles []store.Role
|
||||
pending []store.ListPendingInvitationsRow
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if roles, err = q.ListRoles(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
pending, err = q.ListPendingInvitations(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := web.MembersView{CanManage: p.Grants.Can(authz.MembersManage)}
|
||||
for _, r := range toWebRoles(roles) {
|
||||
if p.Grants.CanGrant(authz.NewSet(r.Permissions...), nil) {
|
||||
v.Roles = append(v.Roles, r)
|
||||
}
|
||||
}
|
||||
for _, m := range members {
|
||||
wm := web.Member{UserID: m.UserID.String(), Email: m.Email, DisplayName: m.DisplayName, IsOwner: m.IsOwner}
|
||||
for _, a := range m.Assignments {
|
||||
wa := web.Assignment{ID: a.ID.String(), RoleName: a.RoleName}
|
||||
if a.ResourceType != nil {
|
||||
wa.Scope = i18n.T(ctx, "scope."+*a.ResourceType)
|
||||
}
|
||||
wm.Assignments = append(wm.Assignments, wa)
|
||||
}
|
||||
v.Members = append(v.Members, wm)
|
||||
}
|
||||
for _, inv := range pending {
|
||||
v.Invitations = append(v.Invitations, web.PendingInvite{ID: inv.ID.String(), Email: inv.Email, RoleName: inv.RoleName})
|
||||
}
|
||||
return web.MembersPage(page, me, v), nil
|
||||
}
|
||||
|
||||
func (s *Server) rolesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
ctx := c.Request.Context()
|
||||
var roles []store.Role
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
roles, err = q.ListRoles(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return web.RolesPage(page, me, web.RolesView{
|
||||
Roles: toWebRoles(roles),
|
||||
Permissions: authz.NewSet(authz.All...).Strings(),
|
||||
Grantable: grantable(p),
|
||||
CanManage: p.Grants.Can(authz.RolesManage),
|
||||
}), nil
|
||||
}
|
||||
|
||||
func (s *Server) tokensView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
ctx := c.Request.Context()
|
||||
showAll := p.Grants.Can(authz.MembersManage)
|
||||
var filter *uuid.UUID
|
||||
if !showAll {
|
||||
filter = &p.UserID
|
||||
}
|
||||
var rows []store.ListAPITokensRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListAPITokens(ctx, store.ListAPITokensParams{OrgID: p.Org.ID, UserID: filter})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := web.TokensView{Grantable: grantable(p), ShowOwner: showAll}
|
||||
never := i18n.T(ctx, "tokens.never")
|
||||
for _, r := range rows {
|
||||
t := web.Token{ID: r.ID.String(), Name: r.Name, Prefix: r.Prefix, UserEmail: r.UserEmail, Permissions: r.Permissions, ExpiresAt: never, LastUsedAt: "–"}
|
||||
if r.ExpiresAt != nil {
|
||||
t.ExpiresAt = r.ExpiresAt.Format(time.DateOnly)
|
||||
}
|
||||
if r.LastUsedAt != nil {
|
||||
t.LastUsedAt = r.LastUsedAt.Format(time.DateTime)
|
||||
}
|
||||
v.Tokens = append(v.Tokens, t)
|
||||
}
|
||||
return web.TokensPage(page, me, v), nil
|
||||
}
|
||||
|
||||
func toWebMe(m meView) web.Me {
|
||||
@@ -169,7 +372,6 @@ func toWebMe(m meView) web.Me {
|
||||
DisplayName: m.DisplayName,
|
||||
TOTP: m.TOTP,
|
||||
ActiveOrg: m.ActiveOrg.String(),
|
||||
TOTPMissing: m.TOTPEnrollmentRequired,
|
||||
RecoveryCodesLeft: m.RecoveryCodesLeft,
|
||||
}
|
||||
for _, o := range m.Orgs {
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pquerna/otp/totp"
|
||||
)
|
||||
|
||||
const password = "correct horse battery"
|
||||
|
||||
// invite creates an invitation from b and returns its token.
|
||||
func (b *browser) invite(email, roleID string) string {
|
||||
b.t.Helper()
|
||||
st, body := b.do("POST", "/api/v1/org/invitations", map[string]any{"email": email, "role_id": roleID})
|
||||
if st != http.StatusCreated {
|
||||
b.t.Fatalf("invite(%s) = %d %v, want 201", email, st, body)
|
||||
}
|
||||
u := body["url"].(string)
|
||||
return u[strings.LastIndex(u, "/")+1:]
|
||||
}
|
||||
|
||||
// joinVia signs up a new account through an invitation.
|
||||
func (e *env) joinVia(t *testing.T, tok string) *browser {
|
||||
t.Helper()
|
||||
b := e.browser(t)
|
||||
st, body := b.do("POST", "/api/v1/invitations/"+tok+"/signup", map[string]any{"password": password})
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("invite signup = %d %v, want 200", st, body)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *browser) roleID(key string) string {
|
||||
b.t.Helper()
|
||||
_, body := b.do("GET", "/api/v1/org/roles", nil)
|
||||
for _, r := range body["roles"].([]any) {
|
||||
r := r.(map[string]any)
|
||||
if r["key"] == key || r["name"] == key {
|
||||
return r["id"].(string)
|
||||
}
|
||||
}
|
||||
b.t.Fatalf("role %q not found in %v", key, body)
|
||||
return ""
|
||||
}
|
||||
|
||||
func (b *browser) userID(email string) string {
|
||||
b.t.Helper()
|
||||
_, body := b.do("GET", "/api/v1/org/members", nil)
|
||||
for _, m := range body["members"].([]any) {
|
||||
m := m.(map[string]any)
|
||||
if m["email"] == email {
|
||||
return m["user_id"].(string)
|
||||
}
|
||||
}
|
||||
b.t.Fatalf("member %q not found", email)
|
||||
return ""
|
||||
}
|
||||
|
||||
func expect(t *testing.T, what string, st int, body map[string]any, wantStatus int, wantCode string) {
|
||||
t.Helper()
|
||||
if st != wantStatus || (wantCode != "" && body["error"] != wantCode) {
|
||||
t.Errorf("%s = %d %v, want %d %s", what, st, body["error"], wantStatus, wantCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPermissions(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
domain := uniq("p") + ".test"
|
||||
owner := e.browser(t)
|
||||
owner.signup("owner@"+domain, uniq("perm-"))
|
||||
|
||||
editorTok := owner.invite("editor@"+domain, owner.roleID("editor"))
|
||||
editor := e.joinVia(t, editorTok)
|
||||
|
||||
t.Run("invitation works once", func(t *testing.T) {
|
||||
st, body := e.browser(t).do("POST", "/api/v1/invitations/"+editorTok+"/signup", map[string]any{"password": password})
|
||||
expect(t, "second use", st, body, http.StatusGone, "invitation_invalid")
|
||||
})
|
||||
|
||||
t.Run("editor permissions", func(t *testing.T) {
|
||||
st, body := editor.do("GET", "/api/v1/org/members", nil)
|
||||
expect(t, "editor GET members", st, body, http.StatusOK, "")
|
||||
st, body = editor.do("GET", "/api/v1/org/sso", nil)
|
||||
expect(t, "editor GET sso", st, body, http.StatusForbidden, "forbidden")
|
||||
st, body = editor.do("POST", "/api/v1/org/invitations", map[string]any{"email": "x@" + domain, "role_id": owner.roleID("viewer")})
|
||||
expect(t, "editor invite", st, body, http.StatusForbidden, "forbidden")
|
||||
})
|
||||
|
||||
// A delegated people manager may only hand out what they hold.
|
||||
st, body := owner.do("POST", "/api/v1/org/roles", map[string]any{"name": "People", "permissions": []string{"members.manage"}})
|
||||
expect(t, "create role", st, body, http.StatusCreated, "")
|
||||
st, body = owner.do("POST", "/api/v1/org/roles", map[string]any{"name": "Readers", "permissions": []string{"members.read"}})
|
||||
expect(t, "create role", st, body, http.StatusCreated, "")
|
||||
manager := e.joinVia(t, owner.invite("manager@"+domain, owner.roleID("People")))
|
||||
|
||||
t.Run("no escalation through delegation", func(t *testing.T) {
|
||||
editorID := owner.userID("editor@" + domain)
|
||||
st, body := manager.do("POST", "/api/v1/org/members/"+editorID+"/roles", map[string]any{"role_id": owner.roleID("admin")})
|
||||
expect(t, "manager assigns admin", st, body, http.StatusForbidden, "permission_escalation")
|
||||
st, body = manager.do("POST", "/api/v1/org/members/"+editorID+"/roles", map[string]any{"role_id": owner.roleID("Readers")})
|
||||
expect(t, "manager assigns readers", st, body, http.StatusCreated, "")
|
||||
st, body = manager.do("DELETE", "/api/v1/org/members/"+editorID, nil)
|
||||
expect(t, "manager removes stronger editor", st, body, http.StatusForbidden, "permission_escalation")
|
||||
st, body = manager.do("DELETE", "/api/v1/org/members/"+owner.userID("owner@"+domain), nil)
|
||||
expect(t, "manager removes owner", st, body, http.StatusForbidden, "owner_cannot_be_removed")
|
||||
st, body = manager.do("POST", "/api/v1/org/invitations", map[string]any{"email": "y@" + domain, "role_id": owner.roleID("editor")})
|
||||
expect(t, "manager invites editor", st, body, http.StatusForbidden, "permission_escalation")
|
||||
st, body = manager.do("POST", "/api/v1/org/roles", map[string]any{"name": "Sneaky", "permissions": []string{"org.manage"}})
|
||||
expect(t, "manager creates role", st, body, http.StatusForbidden, "forbidden")
|
||||
})
|
||||
|
||||
t.Run("settings pages", func(t *testing.T) {
|
||||
pages := []string{"/settings/members", "/settings/roles", "/settings/tokens", "/settings/org", "/settings/sso", "/settings/security", "/"}
|
||||
for _, path := range pages {
|
||||
if got := owner.visit(path); got.Path != path {
|
||||
t.Errorf("owner GET %s ended at %s", path, got.Path)
|
||||
}
|
||||
}
|
||||
for path, want := range map[string]string{"/settings/sso": "/", "/settings/org": "/", "/settings/members": "/settings/members", "/settings/tokens": "/settings/tokens"} {
|
||||
if got := editor.visit(path); got.Path != want {
|
||||
t.Errorf("editor GET %s ended at %s, want %s", path, got.Path, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("built-in roles are read-only", func(t *testing.T) {
|
||||
st, body := owner.do("PUT", "/api/v1/org/roles/"+owner.roleID("viewer"), map[string]any{"name": "Viewer", "permissions": []string{"org.manage"}})
|
||||
expect(t, "update built-in", st, body, http.StatusConflict, "role_built_in")
|
||||
st, body = owner.do("DELETE", "/api/v1/org/roles/"+owner.roleID("People"), nil)
|
||||
expect(t, "delete role in use", st, body, http.StatusConflict, "role_in_use")
|
||||
})
|
||||
|
||||
t.Run("api tokens follow their owner", func(t *testing.T) {
|
||||
st, body := editor.do("POST", "/api/v1/org/tokens", map[string]any{"name": "too much", "permissions": []string{"org.manage"}})
|
||||
expect(t, "token beyond own rights", st, body, http.StatusForbidden, "permission_escalation")
|
||||
st, body = editor.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ci", "permissions": []string{"members.read", "monitors.write"}, "expires_in_days": 30})
|
||||
expect(t, "create token", st, body, http.StatusCreated, "")
|
||||
api := &browser{t: t, base: editor.base, hc: e.srv.Client(), bearer: body["token"].(string)}
|
||||
|
||||
st, body = api.do("GET", "/api/v1/org/members", nil)
|
||||
expect(t, "token GET members", st, body, http.StatusOK, "")
|
||||
st, body = api.do("GET", "/api/v1/org/sso", nil)
|
||||
expect(t, "token GET sso", st, body, http.StatusForbidden, "forbidden")
|
||||
st, body = api.do("POST", "/api/v1/org/tokens", map[string]any{"name": "child", "permissions": []string{"members.read"}})
|
||||
expect(t, "token mints token", st, body, http.StatusForbidden, "session_required")
|
||||
|
||||
// Losing the role that granted members.read removes it from the token.
|
||||
editorID := owner.userID("editor@" + domain)
|
||||
_, members := owner.do("GET", "/api/v1/org/members", nil)
|
||||
for _, m := range members["members"].([]any) {
|
||||
m := m.(map[string]any)
|
||||
if m["user_id"] != editorID {
|
||||
continue
|
||||
}
|
||||
for _, a := range m["assignments"].([]any) {
|
||||
owner.do("DELETE", "/api/v1/org/assignments/"+a.(map[string]any)["id"].(string), nil)
|
||||
}
|
||||
}
|
||||
st, body = api.do("GET", "/api/v1/org/members", nil)
|
||||
expect(t, "token after role removal", st, body, http.StatusForbidden, "forbidden")
|
||||
|
||||
st, body = owner.do("DELETE", "/api/v1/org/members/"+editorID, nil)
|
||||
expect(t, "owner removes editor", st, body, http.StatusNoContent, "")
|
||||
st, body = api.do("GET", "/api/v1/org/members", nil)
|
||||
expect(t, "token after removal", st, body, http.StatusUnauthorized, "unauthenticated")
|
||||
st, _ = editor.do("GET", "/api/v1/me", nil)
|
||||
if st != http.StatusUnauthorized {
|
||||
t.Errorf("removed member's session GET /me = %d, want 401", st)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("org policies", func(t *testing.T) {
|
||||
st, body := owner.do("PUT", "/api/v1/org/policy", map[string]any{"require_sso": true})
|
||||
expect(t, "require sso without provider", st, body, http.StatusConflict, "sso_no_provider")
|
||||
st, body = owner.do("PUT", "/api/v1/org/policy", map[string]any{"require_totp": true})
|
||||
expect(t, "require totp without own totp", st, body, http.StatusConflict, "policy_would_lock_you_out")
|
||||
|
||||
owner.enableTOTP()
|
||||
st, body = owner.do("PUT", "/api/v1/org/policy", map[string]any{"require_totp": true})
|
||||
expect(t, "require totp", st, body, http.StatusOK, "")
|
||||
st, body = manager.do("GET", "/api/v1/org/members", nil)
|
||||
expect(t, "password-only member", st, body, http.StatusForbidden, "totp_required_by_org")
|
||||
|
||||
// The manager enables TOTP in the current session and is let in.
|
||||
_, setup := manager.do("POST", "/api/v1/me/totp/setup", nil)
|
||||
code, _ := totp.GenerateCode(setup["secret"].(string), time.Now())
|
||||
manager.do("POST", "/api/v1/me/totp/enable", map[string]any{"code": code})
|
||||
st, body = manager.do("GET", "/api/v1/org/members", nil)
|
||||
expect(t, "member after enabling totp", st, body, http.StatusOK, "")
|
||||
})
|
||||
|
||||
t.Run("invitation for another address", func(t *testing.T) {
|
||||
tok := owner.invite("someone@"+domain, owner.roleID("viewer"))
|
||||
st, body := manager.do("POST", "/api/v1/invitations/"+tok+"/accept", nil)
|
||||
expect(t, "accept as other user", st, body, http.StatusForbidden, "invitation_email_mismatch")
|
||||
})
|
||||
|
||||
t.Run("custom roles stay in their org", func(t *testing.T) {
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("o")+".test", uniq("other-"))
|
||||
_, body := other.do("GET", "/api/v1/org/roles", nil)
|
||||
for _, r := range body["roles"].([]any) {
|
||||
if name := r.(map[string]any)["name"]; name == "People" || name == "Readers" {
|
||||
t.Errorf("other org sees custom role %v", name)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
+31
-5
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
|
||||
@@ -85,11 +86,36 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
me.POST("/totp/disable", s.totpDisable)
|
||||
me.POST("/totp/recovery-codes", s.regenerateRecoveryCodes)
|
||||
|
||||
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)
|
||||
v1.POST("/invitations/:token/accept", auth.Require(), s.acceptInvitation)
|
||||
v1.POST("/invitations/:token/signup", s.inviteSignup)
|
||||
|
||||
org := v1.Group("/org", s.orgAccess())
|
||||
org.PUT("/policy", sessionOnly(), can(authz.OrgManage), s.updatePolicy)
|
||||
|
||||
org.GET("/sso", can(authz.OrgManage), s.listSSOProviders)
|
||||
org.POST("/sso", sessionOnly(), can(authz.OrgManage), s.createSSOProvider)
|
||||
org.PUT("/sso/:id", sessionOnly(), can(authz.OrgManage), s.updateSSOProvider)
|
||||
org.DELETE("/sso/:id", sessionOnly(), can(authz.OrgManage), s.deleteSSOProvider)
|
||||
|
||||
org.GET("/members", can(authz.MembersRead), s.listMembers)
|
||||
org.DELETE("/members/:user", sessionOnly(), can(authz.MembersManage), s.removeMember)
|
||||
org.POST("/members/:user/roles", sessionOnly(), can(authz.MembersManage), s.assignRole)
|
||||
org.DELETE("/assignments/:id", sessionOnly(), can(authz.MembersManage), s.unassignRole)
|
||||
|
||||
org.GET("/invitations", can(authz.MembersRead), s.listInvitations)
|
||||
org.POST("/invitations", sessionOnly(), can(authz.MembersManage), s.createInvitation)
|
||||
org.DELETE("/invitations/:id", sessionOnly(), can(authz.MembersManage), s.deleteInvitation)
|
||||
|
||||
org.GET("/roles", can(authz.MembersRead), s.listRoles)
|
||||
org.POST("/roles", sessionOnly(), can(authz.RolesManage), s.createRole)
|
||||
org.PUT("/roles/:id", sessionOnly(), can(authz.RolesManage), s.updateRole)
|
||||
org.DELETE("/roles/:id", sessionOnly(), can(authz.RolesManage), s.deleteRole)
|
||||
|
||||
// Every member may hold personal tokens; their rights are capped by the
|
||||
// member's own.
|
||||
org.GET("/tokens", s.listTokens)
|
||||
org.POST("/tokens", sessionOnly(), s.createToken)
|
||||
org.DELETE("/tokens/:id", s.deleteToken)
|
||||
|
||||
g.GET("/sso", s.ssoLookup)
|
||||
g.GET("/sso/callback", s.ssoCallback)
|
||||
|
||||
+13
-1
@@ -23,6 +23,9 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
// viewerRoleID is the built-in Viewer role seeded by migration 00009.
|
||||
var viewerRoleID = uuid.MustParse("00000000-0000-0000-0000-00000000a003")
|
||||
|
||||
const (
|
||||
ssoCookie = "__Host-sso"
|
||||
ssoFlowTTL = 10 * time.Minute
|
||||
@@ -262,7 +265,9 @@ func (s *Server) ssoCallback(c *gin.Context) {
|
||||
if locale == "" {
|
||||
locale = i18n.Lang(ctx)
|
||||
}
|
||||
sess, err := s.sessions.Create(ctx, userID, row.OrgID, locale)
|
||||
sess, err := s.sessions.Create(ctx, auth.NewSession{
|
||||
UserID: userID, OrgID: row.OrgID, Locale: locale, Method: auth.MethodSSO, SSOOrg: row.OrgID,
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -322,6 +327,13 @@ func (s *Server) ssoResolveUser(ctx context.Context, row store.SsoProvider, cl s
|
||||
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: row.OrgID, UserID: u.ID}); err != nil {
|
||||
return err
|
||||
}
|
||||
role := viewerRoleID
|
||||
if row.DefaultRoleID != nil {
|
||||
role = *row.DefaultRoleID
|
||||
}
|
||||
if _, err := q.CreateAssignment(ctx, store.CreateAssignmentParams{OrgID: row.OrgID, UserID: u.ID, RoleID: role}); 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)})
|
||||
})
|
||||
|
||||
+44
-53
@@ -11,62 +11,29 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/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"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Issuer string `json:"issuer"`
|
||||
ClientID string `json:"client_id"`
|
||||
HasClientSecret bool `json:"has_client_secret"`
|
||||
Scopes []string `json:"scopes"`
|
||||
AllowedDomains []string `json:"allowed_domains"`
|
||||
AutoProvision bool `json:"auto_provision"`
|
||||
DefaultRoleID *uuid.UUID `json:"default_role_id"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
func viewSSOProvider(p store.SsoProvider) ssoProviderView {
|
||||
return ssoProviderView{
|
||||
ID: p.ID, Name: p.Name, Issuer: p.Issuer, ClientID: p.ClientID,
|
||||
HasClientSecret: p.ClientSecret != nil, Scopes: p.Scopes,
|
||||
AllowedDomains: p.AllowedDomains, AutoProvision: p.AutoProvision, Enabled: p.Enabled,
|
||||
AllowedDomains: p.AllowedDomains, AutoProvision: p.AutoProvision, DefaultRoleID: p.DefaultRoleID, Enabled: p.Enabled,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +46,9 @@ type ssoProviderRequest struct {
|
||||
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"`
|
||||
// DefaultRoleID is assigned to auto-provisioned users; nil means Viewer.
|
||||
DefaultRoleID *uuid.UUID `json:"default_role_id"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
var domainRE = regexp.MustCompile(`^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$`)
|
||||
@@ -122,7 +91,7 @@ func (r *ssoProviderRequest) normalize() string {
|
||||
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 {
|
||||
err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListSSOProviders(ctx)
|
||||
return err
|
||||
@@ -143,6 +112,28 @@ func (s *Server) validateSSORequest(c *gin.Context, req *ssoProviderRequest) boo
|
||||
fail(c, http.StatusUnprocessableEntity, code)
|
||||
return false
|
||||
}
|
||||
if req.DefaultRoleID != nil {
|
||||
ctx := c.Request.Context()
|
||||
var role store.Role
|
||||
err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
role, err = q.GetRole(ctx, *req.DefaultRoleID)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusUnprocessableEntity, "role_not_found")
|
||||
return false
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return false
|
||||
}
|
||||
// Auto-provisioning hands this role to anyone the IdP vouches for.
|
||||
if !current(c).Grants.CanGrant(authz.NewSet(role.Permissions...), nil) {
|
||||
fail(c, http.StatusForbidden, "permission_escalation")
|
||||
return false
|
||||
}
|
||||
}
|
||||
if err := s.sso.ValidateIssuer(c.Request.Context(), req.Issuer); err != nil {
|
||||
code := "sso_discovery_failed"
|
||||
switch {
|
||||
@@ -169,12 +160,12 @@ func (s *Server) createSSOProvider(c *gin.Context) {
|
||||
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 {
|
||||
err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateSSOProvider(ctx, store.CreateSSOProviderParams{
|
||||
ID: id, OrgID: orgOf(c), Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID,
|
||||
ID: id, OrgID: current(c).Org.ID, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID,
|
||||
ClientSecret: secret, Scopes: req.Scopes, AllowedDomains: req.AllowedDomains,
|
||||
AutoProvision: req.AutoProvision, Enabled: req.Enabled == nil || *req.Enabled,
|
||||
AutoProvision: req.AutoProvision, DefaultRoleID: req.DefaultRoleID, Enabled: req.Enabled == nil || *req.Enabled,
|
||||
})
|
||||
return err
|
||||
})
|
||||
@@ -201,12 +192,12 @@ func (s *Server) updateSSOProvider(c *gin.Context) {
|
||||
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 {
|
||||
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.UpdateSSOProvider(ctx, store.UpdateSSOProviderParams{
|
||||
ID: id, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID, ClientSecret: secret,
|
||||
Scopes: req.Scopes, AllowedDomains: req.AllowedDomains, AutoProvision: req.AutoProvision,
|
||||
Enabled: req.Enabled == nil || *req.Enabled,
|
||||
DefaultRoleID: req.DefaultRoleID, Enabled: req.Enabled == nil || *req.Enabled,
|
||||
})
|
||||
return err
|
||||
})
|
||||
@@ -229,7 +220,7 @@ func (s *Server) deleteSSOProvider(c *gin.Context) {
|
||||
}
|
||||
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 {
|
||||
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
n, err = q.DeleteSSOProvider(ctx, id)
|
||||
return err
|
||||
|
||||
@@ -99,6 +99,8 @@ type browser struct {
|
||||
base string
|
||||
hc *http.Client
|
||||
csrf string
|
||||
// bearer, if set, is sent as an API token instead of relying on cookies.
|
||||
bearer string
|
||||
}
|
||||
|
||||
func (e *env) browser(t *testing.T) *browser {
|
||||
@@ -121,6 +123,9 @@ func (b *browser) do(method, path string, body any) (int, map[string]any) {
|
||||
if b.csrf != "" {
|
||||
req.Header.Set("X-CSRF-Token", b.csrf)
|
||||
}
|
||||
if b.bearer != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+b.bearer)
|
||||
}
|
||||
resp, err := b.hc.Do(req)
|
||||
if err != nil {
|
||||
b.t.Fatalf("%s %s failed: %v", method, path, err)
|
||||
@@ -142,6 +147,9 @@ func (b *browser) visit(path string) *url.URL {
|
||||
b.t.Fatalf("GET %s failed: %v", path, err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b.t.Errorf("GET %s ended with status %d at %s", path, resp.StatusCode, resp.Request.URL)
|
||||
}
|
||||
return resp.Request.URL
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// tokenPrefix makes tokens recognizable to secret scanners and to humans.
|
||||
const tokenPrefix = "ust_"
|
||||
|
||||
func hashToken(tok string) []byte {
|
||||
sum := sha256.Sum256([]byte(tok))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
func bearerToken(c *gin.Context) string {
|
||||
h := c.GetHeader("Authorization")
|
||||
if len(h) < 7 || !strings.EqualFold(h[:7], "bearer ") {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(h[7:])
|
||||
}
|
||||
|
||||
func (s *Server) tokenPrincipal(ctx context.Context, tok string) (*principal, int, string, error) {
|
||||
if !strings.HasPrefix(tok, tokenPrefix) {
|
||||
return nil, http.StatusUnauthorized, "unauthenticated", nil
|
||||
}
|
||||
hash := hashToken(tok)
|
||||
var org uuid.UUID
|
||||
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
var err error
|
||||
org, err = q.APITokenOrg(ctx, hash)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, 0, "", err
|
||||
}
|
||||
if org == uuid.Nil {
|
||||
return nil, http.StatusUnauthorized, "unauthenticated", nil
|
||||
}
|
||||
p := &principal{}
|
||||
var (
|
||||
row store.ApiToken
|
||||
member bool
|
||||
)
|
||||
err = s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error {
|
||||
var err error
|
||||
if row, err = q.GetAPITokenByHash(ctx, hash); err != nil {
|
||||
return err
|
||||
}
|
||||
if row.ExpiresAt != nil && !row.ExpiresAt.After(time.Now()) {
|
||||
return nil
|
||||
}
|
||||
if p.Org, err = q.GetOrg(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Grants, member, err = loadGrants(ctx, q, org, row.UserID); err != nil || !member {
|
||||
return err
|
||||
}
|
||||
return q.TouchAPIToken(ctx, row.ID)
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !member) {
|
||||
return nil, http.StatusUnauthorized, "unauthenticated", nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, 0, "", err
|
||||
}
|
||||
p.UserID, p.TokenID = row.UserID, row.ID
|
||||
p.Grants = p.Grants.Restrict(authz.NewSet(row.Permissions...))
|
||||
return p, 0, "", nil
|
||||
}
|
||||
|
||||
type tokenView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Prefix string `json:"prefix"`
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
UserEmail string `json:"user_email"`
|
||||
Permissions []string `json:"permissions"`
|
||||
ExpiresAt *time.Time `json:"expires_at"`
|
||||
LastUsedAt *time.Time `json:"last_used_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (s *Server) listTokens(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
// Members see their own tokens; members.manage reveals everyone's so
|
||||
// tokens of departing staff can be revoked.
|
||||
var filter *uuid.UUID
|
||||
if !p.Grants.Can(authz.MembersManage) {
|
||||
filter = &p.UserID
|
||||
}
|
||||
var rows []store.ListAPITokensRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListAPITokens(ctx, store.ListAPITokensParams{OrgID: p.Org.ID, UserID: filter})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]tokenView, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = tokenView{
|
||||
ID: r.ID, Name: r.Name, Prefix: r.Prefix, UserID: r.UserID, UserEmail: r.UserEmail,
|
||||
Permissions: r.Permissions, ExpiresAt: r.ExpiresAt, LastUsedAt: r.LastUsedAt, CreatedAt: r.CreatedAt,
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"tokens": out})
|
||||
}
|
||||
|
||||
type createTokenRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Permissions []string `json:"permissions" binding:"required,min=1,max=50,dive,max=50"`
|
||||
// ExpiresInDays of 0 creates a token that does not expire.
|
||||
ExpiresInDays int `json:"expires_in_days" binding:"min=0,max=3650"`
|
||||
}
|
||||
|
||||
func (s *Server) createToken(c *gin.Context) {
|
||||
var req createTokenRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
perms := authz.NewSet(req.Permissions...)
|
||||
if len(perms) == 0 {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_permissions")
|
||||
return
|
||||
}
|
||||
if !p.Grants.CanGrant(perms, nil) {
|
||||
fail(c, http.StatusForbidden, "permission_escalation")
|
||||
return
|
||||
}
|
||||
var expires *time.Time
|
||||
if req.ExpiresInDays > 0 {
|
||||
t := time.Now().AddDate(0, 0, req.ExpiresInDays)
|
||||
expires = &t
|
||||
}
|
||||
tok := tokenPrefix + auth.RandomToken()
|
||||
ctx := c.Request.Context()
|
||||
var row store.ApiToken
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateAPIToken(ctx, store.CreateAPITokenParams{
|
||||
OrgID: p.Org.ID, UserID: p.UserID, Name: strings.TrimSpace(req.Name),
|
||||
TokenHash: hashToken(tok), Prefix: tok[:len(tokenPrefix)+6],
|
||||
Permissions: perms.Strings(), ExpiresAt: expires,
|
||||
})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"id": row.ID, "token": tok, "prefix": row.Prefix, "permissions": row.Permissions})
|
||||
}
|
||||
|
||||
func (s *Server) deleteToken(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var found bool
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
row, err := q.GetAPIToken(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if row.UserID != p.UserID && !p.Grants.Can(authz.MembersManage) {
|
||||
return nil
|
||||
}
|
||||
found = true
|
||||
_, err = q.DeleteAPIToken(ctx, id)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
Reference in new issue
Block a user