/api/openapi.json is generated from a table of endpoints and the Go types the handlers bind and return, including the limits of their binding tags, so the document follows the code. A test fails for routes missing from the table or documented but not served. /api/docs shows it with Swagger UI from our own assets, usable without internet access; "Try it out" works with the browser session. Closes #84 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
343 lines
8.9 KiB
Go
343 lines
8.9 KiB
Go
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})
|
|
}
|
|
}
|
|
|
|
// invitationView is a pending invitation.
|
|
type invitationView struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Email string `json:"email"`
|
|
RoleName string `json:"role_name"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
}
|
|
|
|
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
|
|
}
|
|
out := make([]invitationView, len(rows))
|
|
for i, r := range rows {
|
|
out[i] = invitationView{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
|
|
}
|
|
auditOrg(c, inv.OrgID)
|
|
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))
|
|
}
|