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:
@@ -5,14 +5,12 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgerrcode"
|
||||
"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/audit"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
|
||||
"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"))
|
||||
return
|
||||
}
|
||||
if len(req.Password) < minPasswordLength {
|
||||
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
|
||||
if !checkNewPassword(w, req.Password) {
|
||||
return
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
hash, err := hashPassword(req.Password)
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin create user: hash failed", apierror.Internal(err))
|
||||
return
|
||||
@@ -171,9 +168,8 @@ func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request)
|
||||
DisplayName: req.DisplayName,
|
||||
})
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation {
|
||||
writeErr(w, apierror.Conflict("username_taken", ""))
|
||||
if db.IsUniqueViolation(err) {
|
||||
writeErr(w, apierror.Conflict("username_taken", "username is already taken"))
|
||||
return
|
||||
}
|
||||
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) {
|
||||
return
|
||||
}
|
||||
if len(req.Password) < minPasswordLength {
|
||||
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
|
||||
if !checkNewPassword(w, req.Password) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -268,7 +263,7 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque
|
||||
return
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
hash, err := hashPassword(req.Password)
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin reset password: hash failed", apierror.Internal(err))
|
||||
return
|
||||
|
||||
@@ -9,15 +9,13 @@ import (
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
@@ -26,8 +24,6 @@ import (
|
||||
// the frontend for live validation.
|
||||
var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_-]{3,32}$`)
|
||||
|
||||
const minPasswordLength = 8
|
||||
|
||||
type registerReq struct {
|
||||
Username string `json:"username"`
|
||||
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"))
|
||||
return
|
||||
}
|
||||
if len(req.Password) < minPasswordLength {
|
||||
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
|
||||
if !checkNewPassword(w, req.Password) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -135,7 +130,7 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// Hash password.
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
hash, err := hashPassword(req.Password)
|
||||
if err != nil {
|
||||
h.logger.Error("register: hash password failed", "err", err)
|
||||
writeErr(w, apierror.Internal(err))
|
||||
@@ -158,8 +153,7 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||
DisplayName: req.DisplayName,
|
||||
})
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation {
|
||||
if db.IsUniqueViolation(err) {
|
||||
writeErr(w, apierror.Conflict("username_taken", "username is already taken"))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"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", ""))
|
||||
return
|
||||
}
|
||||
if len(req.NewPassword) < minPasswordLength {
|
||||
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
|
||||
if !checkNewPassword(w, req.NewPassword) {
|
||||
return
|
||||
}
|
||||
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 —
|
||||
// user has to request another. That's acceptable; bcrypt and
|
||||
// UPDATE rarely fail in healthy systems.
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
|
||||
hash, err := hashPassword(req.NewPassword)
|
||||
if err != nil {
|
||||
h.logger.Error("reset password: hash failed", "err", err)
|
||||
writeErr(w, apierror.Internal(err))
|
||||
|
||||
@@ -30,8 +30,7 @@ func (h *handlers) handleChangePassword(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, apierror.BadRequest("invalid_body", ""))
|
||||
return
|
||||
}
|
||||
if len(req.NewPassword) < minPasswordLength {
|
||||
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
|
||||
if !checkNewPassword(w, req.NewPassword) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -47,7 +46,7 @@ func (h *handlers) handleChangePassword(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
|
||||
hash, err := hashPassword(req.NewPassword)
|
||||
if err != nil {
|
||||
h.logger.Error("change password: hash failed", "err", err)
|
||||
writeErr(w, apierror.Internal(err))
|
||||
|
||||
@@ -2,15 +2,12 @@ package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
@@ -109,9 +106,8 @@ func (h *handlers) handleUpdateMyProfile(w http.ResponseWriter, r *http.Request)
|
||||
Email: email,
|
||||
})
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation {
|
||||
writeErr(w, apierror.Conflict("email_taken", ""))
|
||||
if db.IsUniqueViolation(err) {
|
||||
writeErr(w, apierror.Conflict("email_taken", "email is already in use"))
|
||||
return
|
||||
}
|
||||
h.logger.Error("update profile: update failed", "err", err)
|
||||
|
||||
@@ -2,10 +2,12 @@ package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"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
|
||||
}
|
||||
|
||||
// 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
|
||||
// invalid input, writes a 400 envelope and returns ok=false; the caller
|
||||
// MUST return immediately on ok=false.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
|
||||
"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 {
|
||||
n, err := tq.RerootTrackPaths(ctx, dbq.RerootTrackPathsParams{NewRoot: m.Path, OldRoot: m.Was})
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
if db.IsUniqueViolation(err) {
|
||||
return badRoots("Some tracks under %s are already in the library at %s, "+
|
||||
"so its tracks cannot move there.", m.Was, m.Path)
|
||||
}
|
||||
|
||||
@@ -2,30 +2,17 @@ package library
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"github.com/dhowden/tag"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
|
||||
"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.
|
||||
type BackfillMBIDsResult struct {
|
||||
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{
|
||||
ID: r.AlbumID, Mbid: &m,
|
||||
}); err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
if db.IsUniqueViolation(err) {
|
||||
// Another album row already owns this MBID — i.e. our DB
|
||||
// has two rows for the same MusicBrainz release (split by
|
||||
// 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{
|
||||
ID: r.ArtistID, Mbid: &am,
|
||||
}); err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
if db.IsUniqueViolation(err) {
|
||||
logger.Info("mbid backfill: duplicate artist mbid (canonical row already owns it)",
|
||||
"artist_id", r.ArtistID, "mbid", artistMBID)
|
||||
} else {
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
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,
|
||||
Mbid: &m,
|
||||
}); uerr != nil {
|
||||
if isUniqueViolation(uerr) {
|
||||
if db.IsUniqueViolation(uerr) {
|
||||
// Another artist row already owns this MBID — two rows that
|
||||
// should be merged (usually two spellings of one name).
|
||||
// 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,
|
||||
Mbid: &m,
|
||||
}); uerr != nil {
|
||||
if isUniqueViolation(uerr) {
|
||||
if db.IsUniqueViolation(uerr) {
|
||||
// Another album row already owns this MBID — duplicate
|
||||
// release in the DB. Leave NULL; operator merges later.
|
||||
s.logger.Info("library scan: duplicate album mbid (canonical row already owns it)",
|
||||
|
||||
Reference in New Issue
Block a user