ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 9m21s
ci / test (pull_request) Successful in 13m53s
ci / build (pull_request) Successful in 11m22s
ci / image (pull_request) Successful in 4m36s
Terms of service join the legal notice and privacy policy, for the platform only. Every account accepts the platform's privacy policy and terms: on sign-up (also through an invitation) by ticking a box for the versions shown, and after a sign-in through a provider right away. When an admin saves a material change with "everyone has to accept again", the document gets a new version and each account is asked at its next request; corrections ask nobody. Acceptances are kept per version with their time, as proof, and are part of the data export. Until an account accepted, and while it is suspended, it can read the documents, export its data, delete itself and sign out, nothing else: pages lead to /consent or /account/suspended, other API calls answer 403 consent_required or account_suspended. Suspended accounts therefore sign in again, by password or provider; their API tokens stay blocked. Deleting an account deletes the organizations it owns, monitors and all, also when they have other members (each organization has one owner); it no longer refuses. The account settings name those organizations first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
381 lines
10 KiB
Go
381 lines
10 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
|
"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/store"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
|
)
|
|
|
|
const (
|
|
mfaCookie = "__Host-mfa"
|
|
mfaTTL = 5 * time.Minute
|
|
)
|
|
|
|
type signupRequest struct {
|
|
Email string `json:"email" binding:"required,email,max=320"`
|
|
Password string `json:"password" binding:"required,max=1024"`
|
|
DisplayName string `json:"display_name" binding:"max=200"`
|
|
// OrgName and OrgSlug create a first organization at once, when no
|
|
// email confirmation is needed; otherwise the account creates one
|
|
// after confirming.
|
|
OrgName string `json:"org_name" binding:"max=200"`
|
|
OrgSlug string `json:"org_slug" binding:"max=63"`
|
|
// Consent accepts the platform's privacy policy and terms in the
|
|
// versions the form showed (ConsentVersions, "privacy:12,terms:14").
|
|
Consent bool `json:"consent"`
|
|
ConsentVersions string `json:"consent_versions" binding:"max=200"`
|
|
}
|
|
|
|
func (s *Server) signup(c *gin.Context) {
|
|
var req signupRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
if !s.limit(c, "signup:"+c.ClientIP(), 10, time.Hour) {
|
|
return
|
|
}
|
|
if allowed, err := s.signupAllowed(ctx); err != nil {
|
|
internalError(c, err)
|
|
return
|
|
} else if !allowed {
|
|
fail(c, http.StatusForbidden, "signup_closed")
|
|
return
|
|
}
|
|
if left, err := s.signupsLeft(c); err != nil {
|
|
internalError(c, err)
|
|
return
|
|
} else if !left {
|
|
fail(c, http.StatusTooManyRequests, "signup_limit")
|
|
return
|
|
}
|
|
consent, ok := s.signupConsent(c, req.Consent, req.ConsentVersions)
|
|
if !ok {
|
|
return
|
|
}
|
|
verify := s.verificationRequired()
|
|
withOrg := !verify && strings.TrimSpace(req.OrgName) != "" && strings.TrimSpace(req.OrgSlug) != ""
|
|
hash, err := auth.HashPassword(req.Password)
|
|
if errors.Is(err, auth.ErrPasswordTooShort) {
|
|
fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength)
|
|
return
|
|
} else if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
|
|
orgID := uuid.New()
|
|
var user store.User
|
|
err = s.db.Tx(ctx, tenant.Org(orgID, uuid.Nil), func(q *store.Queries) error {
|
|
var err error
|
|
params := store.CreateUserParams{
|
|
Email: normalizeEmail(req.Email),
|
|
DisplayName: strings.TrimSpace(req.DisplayName),
|
|
PasswordHash: &hash,
|
|
Locale: ptr(i18n.Lang(ctx)),
|
|
EmailKey: ptr(emailKey(req.Email)),
|
|
}
|
|
if !verify {
|
|
params.EmailVerifiedAt = ptr(time.Now())
|
|
}
|
|
user, err = q.CreateUser(ctx, params)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if withOrg {
|
|
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(req.OrgSlug), Name: strings.TrimSpace(req.OrgName)}); err != nil {
|
|
return err
|
|
}
|
|
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: user.ID, IsOwner: true}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
// Whoever sets up a self-hosted installation operates it.
|
|
if s.cfg.Signup == config.SignupFirstUser && s.cfg.Edition == config.EditionSelfHosted {
|
|
return q.MakeAdmin(ctx, user.ID)
|
|
}
|
|
return nil
|
|
})
|
|
if err == nil {
|
|
err = s.db.Tx(ctx, tenant.User(user.ID), func(q *store.Queries) error {
|
|
return recordConsent(ctx, q, user.ID, consent)
|
|
})
|
|
}
|
|
switch {
|
|
case isUniqueViolation(err, "users_email_key"), isUniqueViolation(err, "users_email_key_idx"):
|
|
fail(c, http.StatusConflict, "email_taken")
|
|
return
|
|
case isUniqueViolation(err, "orgs_slug_key"):
|
|
fail(c, http.StatusConflict, "slug_taken")
|
|
return
|
|
case isCheckViolation(err):
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_slug")
|
|
return
|
|
case err != nil:
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
s.countSignup(c)
|
|
if verify {
|
|
auditActor(c, user.ID)
|
|
if err := s.sendVerification(ctx, user); err != nil {
|
|
s.log.ErrorContext(ctx, "sending verification failed", "error", err)
|
|
fail(c, http.StatusBadGateway, "verification_mail_failed")
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"status": "verification_sent", "redirect": "/signup/sent"})
|
|
return
|
|
}
|
|
if !withOrg {
|
|
orgID = uuid.Nil
|
|
}
|
|
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) {
|
|
if s.signupClosedWithoutMail() {
|
|
return false, nil
|
|
}
|
|
switch s.cfg.Signup {
|
|
case config.SignupOpen:
|
|
return true, nil
|
|
case config.SignupFirstUser:
|
|
var exists bool
|
|
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
|
var err error
|
|
exists, err = q.AnyUserExists(ctx)
|
|
return err
|
|
})
|
|
return !exists, err
|
|
}
|
|
return false, nil
|
|
}
|
|
|
|
type loginRequest struct {
|
|
Email string `json:"email" binding:"required,max=320"`
|
|
Password string `json:"password" binding:"required,max=1024"`
|
|
}
|
|
|
|
func (s *Server) login(c *gin.Context) {
|
|
var req loginRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
email := normalizeEmail(req.Email)
|
|
auditDetail(c, "email", email)
|
|
if !s.limit(c, "login:ip:"+c.ClientIP(), 30, 15*time.Minute) || !s.limit(c, "login:email:"+email, 10, 15*time.Minute) {
|
|
return
|
|
}
|
|
|
|
var user store.User
|
|
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
|
var err error
|
|
user, err = q.GetUserByEmail(ctx, email)
|
|
return err
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) || (err == nil && user.PasswordHash == nil) {
|
|
auth.BurnPasswordCheck(req.Password)
|
|
invalidCredentials(c)
|
|
return
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
auditActor(c, user.ID)
|
|
ok, rehash, err := auth.VerifyPassword(*user.PasswordHash, req.Password)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if !ok {
|
|
invalidCredentials(c)
|
|
return
|
|
}
|
|
// Only someone who knows the password learns of a missing
|
|
// confirmation. Suspended accounts sign in, but only to export or
|
|
// delete their data.
|
|
if user.EmailVerifiedAt == nil {
|
|
fail(c, http.StatusForbidden, "email_unverified")
|
|
return
|
|
}
|
|
if rehash {
|
|
s.rehashPassword(ctx, user.ID, req.Password)
|
|
}
|
|
|
|
if user.TotpSecret != nil {
|
|
token := auth.RandomToken()
|
|
if err := s.rdb.Set(ctx, mfaKey(token), user.ID.String(), mfaTTL).Err(); err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
setCookie(c, mfaCookie, token, int(mfaTTL.Seconds()))
|
|
auditSkip(c)
|
|
c.JSON(http.StatusOK, gin.H{"status": "totp_required"})
|
|
return
|
|
}
|
|
s.finishLogin(c, user.ID, auth.MethodPassword)
|
|
}
|
|
|
|
// secondFactorRequest carries a TOTP code or a recovery code.
|
|
type secondFactorRequest struct {
|
|
Code string `json:"code" binding:"required,max=32"`
|
|
}
|
|
|
|
type totpRequest struct {
|
|
Code string `json:"code" binding:"required,len=6,numeric"`
|
|
}
|
|
|
|
func (s *Server) loginTOTP(c *gin.Context) {
|
|
var req secondFactorRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
token, _ := c.Cookie(mfaCookie)
|
|
if token == "" {
|
|
fail(c, http.StatusUnauthorized, "mfa_expired")
|
|
return
|
|
}
|
|
if !s.limit(c, "mfa:"+mfaKey(token), 5, mfaTTL) {
|
|
return
|
|
}
|
|
raw, err := s.rdb.Get(ctx, mfaKey(token)).Result()
|
|
if err != nil {
|
|
fail(c, http.StatusUnauthorized, "mfa_expired")
|
|
return
|
|
}
|
|
userID, err := uuid.Parse(raw)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
auditActor(c, userID)
|
|
ok, err := s.verifySecondFactor(ctx, userID, req.Code)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if !ok {
|
|
fail(c, http.StatusUnauthorized, "invalid_code")
|
|
return
|
|
}
|
|
_ = s.rdb.Del(ctx, mfaKey(token)).Err()
|
|
setCookie(c, mfaCookie, "", -1)
|
|
s.finishLogin(c, userID, auth.MethodPasswordTOTP)
|
|
}
|
|
|
|
func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID, method auth.Method) {
|
|
ctx := c.Request.Context()
|
|
var (
|
|
user store.User
|
|
orgs []store.ListUserOrgsRow
|
|
)
|
|
err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
|
|
var err error
|
|
if user, err = q.GetUser(ctx, userID); err != nil {
|
|
return err
|
|
}
|
|
orgs, err = q.ListUserOrgs(ctx, userID)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
var org uuid.UUID
|
|
if len(orgs) > 0 {
|
|
org = orgs[0].ID
|
|
}
|
|
s.startSession(c, auth.NewSession{UserID: userID, OrgID: org, Locale: deref(user.Locale), Method: method})
|
|
}
|
|
|
|
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(), n)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
auditActor(c, n.UserID)
|
|
auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds()))
|
|
c.JSON(http.StatusOK, gin.H{"status": "ok", "csrf_token": sess.CSRF})
|
|
}
|
|
|
|
func (s *Server) logout(c *gin.Context) {
|
|
if sess := auth.Current(c); sess != nil {
|
|
if err := s.sessions.Delete(c.Request.Context(), sess); err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
}
|
|
auth.ClearCookie(c)
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
|
|
func (s *Server) rehashPassword(ctx context.Context, user uuid.UUID, pw string) {
|
|
hash, err := auth.HashPassword(pw)
|
|
if err != nil {
|
|
return
|
|
}
|
|
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
|
return q.SetPasswordHash(ctx, store.SetPasswordHashParams{ID: user, PasswordHash: &hash})
|
|
})
|
|
if err != nil {
|
|
s.log.WarnContext(ctx, "password rehash failed", "error", err)
|
|
}
|
|
}
|
|
|
|
func (s *Server) limit(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")
|
|
fail(c, http.StatusTooManyRequests, "rate_limited")
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func mfaKey(token string) string {
|
|
sum := sha256.Sum256([]byte(token))
|
|
return "login_mfa:" + hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
func normalizeEmail(e string) string { return strings.ToLower(strings.TrimSpace(e)) }
|
|
|
|
func invalidCredentials(c *gin.Context) {
|
|
fail(c, http.StatusUnauthorized, "invalid_credentials")
|
|
}
|
|
|
|
func isUniqueViolation(err error, constraint string) bool {
|
|
var pgErr *pgconn.PgError
|
|
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == constraint
|
|
}
|
|
|
|
func isCheckViolation(err error) bool {
|
|
var pgErr *pgconn.PgError
|
|
return errors.As(err, &pgErr) && pgErr.Code == "23514"
|
|
}
|