refactor(api): one password rule, one hash, one unique-violation check (#8002)

The length check and bcrypt call were copied into sign-up, reset,
change and both admin paths; the unique-violation test into three api
handlers and the library. checkNewPassword and hashPassword now sit in
api/prelude.go, and db.IsUniqueViolation serves api and library. The
taken-username and taken-email conflicts now carry a message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 12:45:18 -05:00
co-authored by Claude Opus 5.5
parent cfdd6b916f
commit 074d9ffb0e
10 changed files with 66 additions and 55 deletions
+7 -12
View File
@@ -5,14 +5,12 @@ import (
"net/http" "net/http"
"time" "time"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"golang.org/x/crypto/bcrypt"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/audit" "git.fabledsword.com/bvandeusen/minstrel/internal/audit"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth" "git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
) )
@@ -146,12 +144,11 @@ func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request)
writeErr(w, apierror.BadRequest("username_invalid", "username must be 3-32 chars, alphanumeric + underscore + hyphen")) writeErr(w, apierror.BadRequest("username_invalid", "username must be 3-32 chars, alphanumeric + underscore + hyphen"))
return return
} }
if len(req.Password) < minPasswordLength { if !checkNewPassword(w, req.Password) {
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
return return
} }
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) hash, err := hashPassword(req.Password)
if err != nil { if err != nil {
writeErrWithLog(w, h.logger, "admin create user: hash failed", apierror.Internal(err)) writeErrWithLog(w, h.logger, "admin create user: hash failed", apierror.Internal(err))
return return
@@ -171,9 +168,8 @@ func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request)
DisplayName: req.DisplayName, DisplayName: req.DisplayName,
}) })
if err != nil { if err != nil {
var pgErr *pgconn.PgError if db.IsUniqueViolation(err) {
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation { writeErr(w, apierror.Conflict("username_taken", "username is already taken"))
writeErr(w, apierror.Conflict("username_taken", ""))
return return
} }
writeErrWithLog(w, h.logger, "admin create user: insert failed", apierror.Internal(err)) writeErrWithLog(w, h.logger, "admin create user: insert failed", apierror.Internal(err))
@@ -252,8 +248,7 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque
if !decodeBody(w, r, &req) { if !decodeBody(w, r, &req) {
return return
} }
if len(req.Password) < minPasswordLength { if !checkNewPassword(w, req.Password) {
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
return return
} }
@@ -268,7 +263,7 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque
return return
} }
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) hash, err := hashPassword(req.Password)
if err != nil { if err != nil {
writeErrWithLog(w, h.logger, "admin reset password: hash failed", apierror.Internal(err)) writeErrWithLog(w, h.logger, "admin reset password: hash failed", apierror.Internal(err))
return return
+4 -10
View File
@@ -9,15 +9,13 @@ import (
"regexp" "regexp"
"time" "time"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/bcrypt"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/audit" "git.fabledsword.com/bvandeusen/minstrel/internal/audit"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth" "git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
) )
@@ -26,8 +24,6 @@ import (
// the frontend for live validation. // the frontend for live validation.
var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_-]{3,32}$`) var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_-]{3,32}$`)
const minPasswordLength = 8
type registerReq struct { type registerReq struct {
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` Password string `json:"password"`
@@ -80,8 +76,7 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
writeErr(w, apierror.BadRequest("username_invalid", "username must be 3-32 chars, alphanumeric + underscore + hyphen")) writeErr(w, apierror.BadRequest("username_invalid", "username must be 3-32 chars, alphanumeric + underscore + hyphen"))
return return
} }
if len(req.Password) < minPasswordLength { if !checkNewPassword(w, req.Password) {
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
return return
} }
@@ -135,7 +130,7 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
} }
// Hash password. // Hash password.
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) hash, err := hashPassword(req.Password)
if err != nil { if err != nil {
h.logger.Error("register: hash password failed", "err", err) h.logger.Error("register: hash password failed", "err", err)
writeErr(w, apierror.Internal(err)) writeErr(w, apierror.Internal(err))
@@ -158,8 +153,7 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
DisplayName: req.DisplayName, DisplayName: req.DisplayName,
}) })
if err != nil { if err != nil {
var pgErr *pgconn.PgError if db.IsUniqueViolation(err) {
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation {
writeErr(w, apierror.Conflict("username_taken", "username is already taken")) writeErr(w, apierror.Conflict("username_taken", "username is already taken"))
return return
} }
+2 -4
View File
@@ -6,7 +6,6 @@ import (
"net/http" "net/http"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"golang.org/x/crypto/bcrypt"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/audit" "git.fabledsword.com/bvandeusen/minstrel/internal/audit"
@@ -34,8 +33,7 @@ func (h *handlers) handleResetPassword(w http.ResponseWriter, r *http.Request) {
writeErr(w, apierror.BadRequest("invalid_body", "")) writeErr(w, apierror.BadRequest("invalid_body", ""))
return return
} }
if len(req.NewPassword) < minPasswordLength { if !checkNewPassword(w, req.NewPassword) {
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
return return
} }
if req.Token == "" { if req.Token == "" {
@@ -89,7 +87,7 @@ func (h *handlers) handleResetPassword(w http.ResponseWriter, r *http.Request) {
// claim, the token is "burned" but the password isn't reset — // claim, the token is "burned" but the password isn't reset —
// user has to request another. That's acceptable; bcrypt and // user has to request another. That's acceptable; bcrypt and
// UPDATE rarely fail in healthy systems. // UPDATE rarely fail in healthy systems.
hash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost) hash, err := hashPassword(req.NewPassword)
if err != nil { if err != nil {
h.logger.Error("reset password: hash failed", "err", err) h.logger.Error("reset password: hash failed", "err", err)
writeErr(w, apierror.Internal(err)) writeErr(w, apierror.Internal(err))
+2 -3
View File
@@ -30,8 +30,7 @@ func (h *handlers) handleChangePassword(w http.ResponseWriter, r *http.Request)
writeErr(w, apierror.BadRequest("invalid_body", "")) writeErr(w, apierror.BadRequest("invalid_body", ""))
return return
} }
if len(req.NewPassword) < minPasswordLength { if !checkNewPassword(w, req.NewPassword) {
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
return return
} }
@@ -47,7 +46,7 @@ func (h *handlers) handleChangePassword(w http.ResponseWriter, r *http.Request)
return return
} }
hash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost) hash, err := hashPassword(req.NewPassword)
if err != nil { if err != nil {
h.logger.Error("change password: hash failed", "err", err) h.logger.Error("change password: hash failed", "err", err)
writeErr(w, apierror.Internal(err)) writeErr(w, apierror.Internal(err))
+3 -7
View File
@@ -2,15 +2,12 @@ package api
import ( import (
"encoding/json" "encoding/json"
"errors"
"net/http" "net/http"
"regexp" "regexp"
"strings" "strings"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5/pgconn"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
) )
@@ -109,9 +106,8 @@ func (h *handlers) handleUpdateMyProfile(w http.ResponseWriter, r *http.Request)
Email: email, Email: email,
}) })
if err != nil { if err != nil {
var pgErr *pgconn.PgError if db.IsUniqueViolation(err) {
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation { writeErr(w, apierror.Conflict("email_taken", "email is already in use"))
writeErr(w, apierror.Conflict("email_taken", ""))
return return
} }
h.logger.Error("update profile: update failed", "err", err) h.logger.Error("update profile: update failed", "err", err)
+23
View File
@@ -2,10 +2,12 @@ package api
import ( import (
"encoding/json" "encoding/json"
"fmt"
"net/http" "net/http"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"golang.org/x/crypto/bcrypt"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth" "git.fabledsword.com/bvandeusen/minstrel/internal/auth"
@@ -25,6 +27,27 @@ func requireUser(w http.ResponseWriter, r *http.Request) (dbq.User, bool) {
return user, true return user, true
} }
// minPasswordLength is the shortest password any account may set: at
// sign-up, on reset, on change, and when an admin sets one.
const minPasswordLength = 8
// checkNewPassword answers 400 password_too_short and returns false when pw
// is too short to set. Every path that sets a password calls it, so the
// rule lives in one place.
func checkNewPassword(w http.ResponseWriter, pw string) bool {
if len(pw) < minPasswordLength {
writeErr(w, apierror.BadRequest("password_too_short",
fmt.Sprintf("password must be at least %d characters", minPasswordLength)))
return false
}
return true
}
// hashPassword is the one place a password is hashed for storage.
func hashPassword(pw string) ([]byte, error) {
return bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost)
}
// requireURLUUID parses the chi URL parameter named key as a UUID. On // requireURLUUID parses the chi URL parameter named key as a UUID. On
// invalid input, writes a 400 envelope and returns ok=false; the caller // invalid input, writes a 400 envelope and returns ok=false; the caller
// MUST return immediately on ok=false. // MUST return immediately on ok=false.
+17
View File
@@ -0,0 +1,17 @@
package db
import (
"errors"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5/pgconn"
)
// IsUniqueViolation reports whether err is Postgres refusing a row because
// another row already holds the same unique value: a username or email
// that is taken, or a second album row claiming one MBID. Callers use it to
// tell "that already exists" apart from a write that failed.
func IsUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation
}
+2 -1
View File
@@ -12,6 +12,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
) )
@@ -99,7 +100,7 @@ func (s *Scanner) SetRoots(ctx context.Context, changes []RootChange) (RerootRes
for _, m := range moves { for _, m := range moves {
n, err := tq.RerootTrackPaths(ctx, dbq.RerootTrackPathsParams{NewRoot: m.Path, OldRoot: m.Was}) n, err := tq.RerootTrackPaths(ctx, dbq.RerootTrackPathsParams{NewRoot: m.Path, OldRoot: m.Was})
if err != nil { if err != nil {
if isUniqueViolation(err) { if db.IsUniqueViolation(err) {
return badRoots("Some tracks under %s are already in the library at %s, "+ return badRoots("Some tracks under %s are already in the library at %s, "+
"so its tracks cannot move there.", m.Was, m.Path) "so its tracks cannot move there.", m.Was, m.Path)
} }
+3 -16
View File
@@ -2,30 +2,17 @@ package library
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"log/slog" "log/slog"
"os" "os"
"github.com/dhowden/tag" "github.com/dhowden/tag"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
) )
// pgUniqueViolation is the SQLSTATE for a unique-constraint conflict.
const pgUniqueViolation = "23505"
// isUniqueViolation reports whether err is a Postgres unique-constraint
// conflict. Used to distinguish "another row already owns this MBID" (a
// duplicate album/artist row in our DB, for an admin to merge) from genuine
// write failures.
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolation
}
// BackfillMBIDsResult tallies what the one-shot worker did. // BackfillMBIDsResult tallies what the one-shot worker did.
type BackfillMBIDsResult struct { type BackfillMBIDsResult struct {
Processed int // Albums considered (mbid IS NULL). Processed int // Albums considered (mbid IS NULL).
@@ -80,7 +67,7 @@ func BackfillMBIDs(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger,
if err := q.SetAlbumMbidIfNull(ctx, dbq.SetAlbumMbidIfNullParams{ if err := q.SetAlbumMbidIfNull(ctx, dbq.SetAlbumMbidIfNullParams{
ID: r.AlbumID, Mbid: &m, ID: r.AlbumID, Mbid: &m,
}); err != nil { }); err != nil {
if isUniqueViolation(err) { if db.IsUniqueViolation(err) {
// Another album row already owns this MBID — i.e. our DB // Another album row already owns this MBID — i.e. our DB
// has two rows for the same MusicBrainz release (split by // has two rows for the same MusicBrainz release (split by
// title/artist disagreements during the pre-MBID scan). // title/artist disagreements during the pre-MBID scan).
@@ -109,7 +96,7 @@ func BackfillMBIDs(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger,
if err := q.SetArtistMbidIfNull(ctx, dbq.SetArtistMbidIfNullParams{ if err := q.SetArtistMbidIfNull(ctx, dbq.SetArtistMbidIfNullParams{
ID: r.ArtistID, Mbid: &am, ID: r.ArtistID, Mbid: &am,
}); err != nil { }); err != nil {
if isUniqueViolation(err) { if db.IsUniqueViolation(err) {
logger.Info("mbid backfill: duplicate artist mbid (canonical row already owns it)", logger.Info("mbid backfill: duplicate artist mbid (canonical row already owns it)",
"artist_id", r.ArtistID, "mbid", artistMBID) "artist_id", r.ArtistID, "mbid", artistMBID)
} else { } else {
+3 -2
View File
@@ -20,6 +20,7 @@ import (
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
) )
@@ -616,7 +617,7 @@ func (s *Scanner) resolveArtist(ctx context.Context, q *dbq.Queries, name, mbid
ID: existing.ID, ID: existing.ID,
Mbid: &m, Mbid: &m,
}); uerr != nil { }); uerr != nil {
if isUniqueViolation(uerr) { if db.IsUniqueViolation(uerr) {
// Another artist row already owns this MBID — two rows that // Another artist row already owns this MBID — two rows that
// should be merged (usually two spellings of one name). // should be merged (usually two spellings of one name).
// Expected, not a fault: leave NULL and let an admin // Expected, not a fault: leave NULL and let an admin
@@ -687,7 +688,7 @@ func (s *Scanner) resolveAlbum(ctx context.Context, q *dbq.Queries, artistID pgt
ID: existing.ID, ID: existing.ID,
Mbid: &m, Mbid: &m,
}); uerr != nil { }); uerr != nil {
if isUniqueViolation(uerr) { if db.IsUniqueViolation(uerr) {
// Another album row already owns this MBID — duplicate // Another album row already owns this MBID — duplicate
// release in the DB. Leave NULL; operator merges later. // release in the DB. Leave NULL; operator merges later.
s.logger.Info("library scan: duplicate album mbid (canonical row already owns it)", s.logger.Info("library scan: duplicate album mbid (canonical row already owns it)",