Files
Sebastian UnterschützandClaude Opus 5.5 358b191976 feat(api): record an audit log and show it to organizations, users and admins
Every state-changing API route is mapped to an action; a test fails for
unmapped routes. Successful changes are recorded with actor, API token,
target, IP, user agent and request ID; failed sign-ins too. Names are
taken from the response, never secrets. Organizations read their log with
audit.read under Settings, users their account activity on the security
page, admins the platform log. Entries expire after UPTIME_RETENTION_AUDIT.

Closes #65

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 09:59:52 +01:00

325 lines
8.4 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 string `json:"org_name" binding:"required,max=200"`
OrgSlug string `json:"org_slug" binding:"required,max=63"`
}
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
}
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
user, err = q.CreateUser(ctx, store.CreateUserParams{
Email: normalizeEmail(req.Email),
DisplayName: strings.TrimSpace(req.DisplayName),
PasswordHash: &hash,
Locale: ptr(i18n.Lang(ctx)),
})
if err != nil {
return err
}
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
})
switch {
case isUniqueViolation(err, "users_email_key"):
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.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) {
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 || user.DisabledAt != nil {
invalidCredentials(c)
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"
}