Files
uptimesebi/internal/api/me.go
T
Sebastian UnterschützandClaude Opus 5.5 7b063d2cd8 feat(api): accept recovery codes as second factor and let users regenerate them
Enabling TOTP returns ten codes that are shown once. Disabling TOTP and
regenerating codes require the password plus a current code.

Closes #40

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

330 lines
8.6 KiB
Go

package api
import (
"bytes"
"context"
"encoding/base64"
"errors"
"image/png"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/pquerna/otp"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
const totpSetupTTL = 10 * time.Minute
type orgView struct {
ID uuid.UUID `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
IsOwner bool `json:"is_owner"`
RequireTOTP bool `json:"require_totp"`
}
type meView struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
TOTP bool `json:"totp_enabled"`
ActiveOrg uuid.UUID `json:"active_org"`
Orgs []orgView `json:"orgs"`
// Set when an org the user belongs to enforces TOTP and the user has none.
TOTPEnrollmentRequired bool `json:"totp_enrollment_required"`
RecoveryCodesLeft int `json:"recovery_codes_left"`
}
func (s *Server) loadMe(ctx context.Context, sess *auth.Session) (meView, error) {
var me meView
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
u, err := q.GetUser(ctx, sess.UserID)
if err != nil {
return err
}
left, err := q.CountUnusedRecoveryCodes(ctx, sess.UserID)
if err != nil {
return err
}
orgs, err := q.ListUserOrgs(ctx, sess.UserID)
if err != nil {
return err
}
me = meView{ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, TOTP: u.TotpSecret != nil, ActiveOrg: sess.OrgID, Orgs: []orgView{}, RecoveryCodesLeft: int(left)}
for _, o := range orgs {
me.Orgs = append(me.Orgs, orgView{ID: o.ID, Slug: o.Slug, Name: o.Name, IsOwner: o.IsOwner, RequireTOTP: o.RequireTotp})
if o.RequireTotp && !me.TOTP {
me.TOTPEnrollmentRequired = true
}
}
return nil
})
return me, err
}
func (s *Server) me(c *gin.Context) {
me, err := s.loadMe(c.Request.Context(), auth.Current(c))
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, me)
}
type switchOrgRequest struct {
OrgID uuid.UUID `json:"org_id" binding:"required"`
}
func (s *Server) switchOrg(c *gin.Context) {
var req switchOrgRequest
if !bind(c, &req) {
return
}
sess := auth.Current(c)
me, err := s.loadMe(c.Request.Context(), sess)
if err != nil {
internalError(c, err)
return
}
for _, o := range me.Orgs {
if o.ID == req.OrgID {
if err := s.sessions.SwitchOrg(c.Request.Context(), sess, o.ID); err != nil {
internalError(c, err)
return
}
c.Status(http.StatusNoContent)
return
}
}
fail(c, http.StatusNotFound, "org_not_found")
}
func totpSetupKey(user uuid.UUID) string { return "totp_setup:" + user.String() }
func (s *Server) totpSetup(c *gin.Context) {
ctx := c.Request.Context()
me, err := s.loadMe(ctx, auth.Current(c))
if err != nil {
internalError(c, err)
return
}
if me.TOTP {
fail(c, http.StatusConflict, "totp_already_enabled")
return
}
key, err := auth.NewTOTPKey(me.Email)
if err != nil {
internalError(c, err)
return
}
if err := s.rdb.Set(ctx, totpSetupKey(me.ID), key.Secret(), totpSetupTTL).Err(); err != nil {
internalError(c, err)
return
}
qr, err := qrDataURI(key)
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"secret": key.Secret(), "otpauth_url": key.URL(), "qr": qr})
}
func (s *Server) totpEnable(c *gin.Context) {
var req totpRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
sess := auth.Current(c)
secret, err := s.rdb.Get(ctx, totpSetupKey(sess.UserID)).Result()
if err != nil {
fail(c, http.StatusConflict, "totp_setup_expired")
return
}
if !s.limit(c, "totp_enable:"+sess.UserID.String(), 10, totpSetupTTL) {
return
}
ok, err := s.totp.Verify(ctx, sess.UserID, secret, req.Code)
if err != nil {
internalError(c, err)
return
}
if !ok {
fail(c, http.StatusUnprocessableEntity, "invalid_code")
return
}
sealedSecret := s.keys.Seal([]byte(secret), sess.UserID[:])
codes := auth.NewRecoveryCodes()
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
if err := q.EnableTOTP(ctx, store.EnableTOTPParams{ID: sess.UserID, TotpSecret: sealedSecret}); err != nil {
return err
}
return replaceRecoveryCodes(ctx, q, sess.UserID, codes)
})
if err != nil {
internalError(c, err)
return
}
_ = s.rdb.Del(ctx, totpSetupKey(sess.UserID)).Err()
c.JSON(http.StatusOK, gin.H{"recovery_codes": codes})
}
func replaceRecoveryCodes(ctx context.Context, q *store.Queries, user uuid.UUID, codes []string) error {
if err := q.DeleteRecoveryCodes(ctx, user); err != nil {
return err
}
rows := make([]store.InsertRecoveryCodesParams, len(codes))
for i, c := range codes {
rows[i] = store.InsertRecoveryCodesParams{UserID: user, CodeHash: auth.HashRecoveryCode(auth.NormalizeRecoveryCode(c))}
}
_, err := q.InsertRecoveryCodes(ctx, rows)
return err
}
// reauthRequest confirms a sensitive change with the password and a second
// factor, so a hijacked session alone cannot weaken the account.
type reauthRequest struct {
Password string `json:"password" binding:"required,max=1024"`
Code string `json:"code" binding:"required,max=32"`
}
// reauthenticate checks req for the session user and writes the error
// response itself when it fails.
func (s *Server) reauthenticate(c *gin.Context, req reauthRequest) bool {
ctx := c.Request.Context()
sess := auth.Current(c)
if !s.limit(c, "reauth:"+sess.UserID.String(), 5, 15*time.Minute) {
return false
}
var user store.User
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
var err error
user, err = q.GetUser(ctx, sess.UserID)
return err
})
if err != nil {
internalError(c, err)
return false
}
if user.PasswordHash == nil {
fail(c, http.StatusConflict, "no_password")
return false
}
if ok, _, err := auth.VerifyPassword(*user.PasswordHash, req.Password); err != nil || !ok {
invalidCredentials(c)
return false
}
ok, err := s.verifySecondFactor(ctx, sess.UserID, req.Code)
if err != nil {
internalError(c, err)
return false
}
if !ok {
fail(c, http.StatusUnauthorized, "invalid_code")
return false
}
return true
}
func (s *Server) totpDisable(c *gin.Context) {
var req reauthRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
sess := auth.Current(c)
me, err := s.loadMe(ctx, sess)
if err != nil {
internalError(c, err)
return
}
for _, o := range me.Orgs {
if o.RequireTOTP {
fail(c, http.StatusConflict, "totp_required_by_org")
return
}
}
if !s.reauthenticate(c, req) {
return
}
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
if err := q.DisableTOTP(ctx, sess.UserID); err != nil {
return err
}
return q.DeleteRecoveryCodes(ctx, sess.UserID)
})
if err != nil {
internalError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func (s *Server) regenerateRecoveryCodes(c *gin.Context) {
var req reauthRequest
if !bind(c, &req) || !s.reauthenticate(c, req) {
return
}
ctx := c.Request.Context()
sess := auth.Current(c)
codes := auth.NewRecoveryCodes()
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
return replaceRecoveryCodes(ctx, q, sess.UserID, codes)
})
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"recovery_codes": codes})
}
var errNoTOTP = errors.New("api: user has no totp")
// verifySecondFactor accepts a current TOTP code or an unused recovery code,
// which is consumed.
func (s *Server) verifySecondFactor(ctx context.Context, userID uuid.UUID, code string) (bool, error) {
if rc := auth.NormalizeRecoveryCode(code); rc != "" {
var n int64
err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
var err error
n, err = q.UseRecoveryCode(ctx, store.UseRecoveryCodeParams{UserID: userID, CodeHash: auth.HashRecoveryCode(rc)})
return err
})
return n == 1, err
}
var user store.User
err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
var err error
user, err = q.GetUser(ctx, userID)
return err
})
if err != nil {
return false, err
}
if user.TotpSecret == nil {
return false, errNoTOTP
}
secret, err := s.keys.Open(user.TotpSecret, userID[:])
if err != nil {
return false, err
}
return s.totp.Verify(ctx, userID, string(secret), code)
}
func qrDataURI(key *otp.Key) (string, error) {
img, err := key.Image(240, 240)
if err != nil {
return "", err
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
return "", err
}
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()), nil
}