feat(auth): add argon2id passwords, sessions, rate limiter, authorization and audit builders

- feat(auth): add argon2id passwords, sessions, rate limiter, authorization and audit builders
- feat(cli): add check and audit commands
- feat(api): add api framework, login, page routes and account, user, delegation and audit handlers
- test(auth): cover passwords, sessions, rate limiter, authorization and audit builders
- test(api): cover the api framework, sessions, client origin, headers and cross-origin refusal
- test(api): cover account, user, delegation and audit handlers and the authorization matrix
- test(ui): cover login, logout, page routes and the page authorization matrix
This commit is contained in:
bryanpedini committed 2026-11-19 15:46:12 +01:00
1 parent 23bec143e3
commit 99fa5de747
28 files changed
+6591 -243

No files matched your search

+131 -70
View File
@@ -14,13 +14,10 @@ import (
"net"
"net/http"
"net/netip"
"regexp"
"strconv"
"strings"
"text/tabwriter"
"time"
"unicode"
"unicode/utf8"
)
const usageText = `usage:
@@ -39,20 +36,14 @@ const usageText = `usage:
const (
healthcheckTimeout = 3 * time.Second
cliActor = "cli"
cliOrigin = "local"
defaultAuditRows = 20
maxAuditRows = 1000000
minPasswordBytes = 12
maxPasswordBytes = 256
maxPasswordLineBytes = 4096
cliTimeLayout = "2006-01-02T15:04:05Z"
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
var (
errNotImplemented = errors.New("not implemented")
errZoneHasNoRows = errors.New("the zone has no records")
errNoActiveUser = errors.New("no active user has this username")
errLastActiveAdmin = errors.New("the last active admin cannot be demoted or deleted")
)
@@ -203,7 +194,7 @@ func (a *app) parseUserCommand(args []string) (cliCommand, error) {
if err := checkUsernameArg(username); err != nil {
return cliCommand{}, err
}
if username == cliActor {
if username == reservedUsername {
return cliCommand{}, usageError("reserved username")
}
if err := checkRoleArg(role); err != nil {
@@ -292,31 +283,12 @@ func checkUsernameArg(username string) error {
}
func checkRoleArg(role string) error {
if role != "admin" && role != "user" {
if !validRole(role) {
return usageError("invalid role")
}
return nil
}
func validUsernameSyntax(username string) bool {
return usernamePattern.MatchString(username)
}
func checkPasswordRules(password string) error {
if len(password) < minPasswordBytes || len(password) > maxPasswordBytes {
return fmt.Errorf("password must be %d to %d bytes", minPasswordBytes, maxPasswordBytes)
}
if !utf8.ValidString(password) {
return errors.New("password must be valid UTF-8")
}
for _, r := range password {
if unicode.IsControl(r) {
return errors.New("password must not contain control characters")
}
}
return nil
}
func (a *app) readPassword() (string, error) {
if a.stdinIsTerminal() {
first, err := a.promptPassword("Password: ")
@@ -402,12 +374,127 @@ func parseAuditCount(s string) (int, error) {
return n, nil
}
type cliReadBackend interface {
ListZones(ctx context.Context) ([]zoneSummary, error)
ZoneRows(ctx context.Context, zone string) ([]recordRow, error)
LatestAudit(ctx context.Context, n int) ([]auditRow, error)
}
type sqlReadBackend struct {
recordStore
auditStore
}
func newSQLReadBackend(db *sql.DB, t tableNames) cliReadBackend {
return sqlReadBackend{recordStore: newRecordStore(db, t), auditStore: newAuditStore(db, t)}
}
var checkHeader = []string{"ZONE", "NAME", "TYPE", "ID", "SEVERITY", "PROBLEM"}
var auditHeader = []string{"TIME", "ACTOR", "ORIGIN", "OPERATION", "STATUS", "ZONE", "RECORD", "TARGET_USER"}
func cliText(s string) string {
s = strings.TrimSpace(printableText(s, -1))
if s == "" {
return "-"
}
return s
}
func checkRows(zone string, problems []zoneProblem) [][]string {
rows := make([][]string, 0, len(problems))
for _, p := range problems {
name, recordType, id := "-", "-", "-"
if p.RecordID != 0 {
name, recordType, id = p.Name, cliText(p.Type), strconv.FormatInt(p.RecordID, 10)
if name == "" {
name = "@"
}
name = cliText(name)
}
rows = append(rows, []string{cliText(zone), name, recordType, id, p.Severity, cliText(p.Code + ": " + p.Message)})
}
return rows
}
func (a *app) runCheck(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger, zone string) error {
return fmt.Errorf("check: %w", errNotImplemented)
return a.checkZones(ctx, a.newReadBackend(db, t), zone)
}
func (a *app) checkZones(ctx context.Context, b cliReadBackend, zone string) error {
zones := []string{zone}
if zone == "" {
summaries, err := b.ListZones(ctx)
if err != nil {
return err
}
zones = zones[:0]
for _, z := range summaries {
zones = append(zones, z.Zone)
}
}
now := a.now()
var table [][]string
for _, z := range zones {
rows, err := b.ZoneRows(ctx, z)
if err != nil {
return err
}
if len(rows) == 0 {
return errZoneHasNoRows
}
table = append(table, checkRows(z, checkZone(z, rows, now))...)
}
if err := writeTable(a.stdout, checkHeader, table); err != nil {
return err
}
if len(table) > 0 {
return errCheckProblems
}
return nil
}
func (a *app) runAudit(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger, n int) error {
return fmt.Errorf("audit: %w", errNotImplemented)
return a.printAudit(ctx, a.newReadBackend(db, t), n)
}
func cliNullInt(v sql.NullInt64) string {
if !v.Valid {
return "-"
}
return strconv.FormatInt(v.Int64, 10)
}
func cliNullText(v sql.NullString) string {
if !v.Valid {
return "-"
}
return cliText(v.String)
}
func auditRows(entries []auditRow) [][]string {
rows := make([][]string, 0, len(entries))
for _, e := range entries {
rows = append(rows, []string{
formatCLITime(e.Time),
cliText(e.Actor),
cliText(e.Origin),
cliText(e.Operation),
cliNullInt(e.Status),
cliNullText(e.Zone),
cliNullInt(e.RecordID),
cliNullText(e.TargetUsername),
})
}
return rows
}
func (a *app) printAudit(ctx context.Context, b cliReadBackend, n int) error {
entries, err := b.LatestAudit(ctx, n)
if err != nil {
return err
}
return writeTable(a.stdout, auditHeader, auditRows(entries))
}
func newHealthClient() *http.Client {
@@ -543,34 +630,8 @@ func (a *app) userList(ctx context.Context, b cliUserBackend, all bool) error {
return writeTable(a.stdout, userListHeader, userListRows(users))
}
func cliAuditEntry(now time.Time, operation string, target userRow, before, after *userRow) (auditEntry, error) {
e := auditEntry{
Time: now,
Actor: cliActor,
Origin: cliOrigin,
Operation: operation,
TargetUserID: sql.NullInt64{Int64: target.ID, Valid: true},
}
var err error
if before != nil {
if e.Before, err = auditUserJSON(*before); err != nil {
return auditEntry{}, err
}
}
if after != nil {
if e.After, err = auditUserJSON(*after); err != nil {
return auditEntry{}, err
}
}
return e, nil
}
func insertCLIAudit(ctx context.Context, tx cliUserTx, now time.Time, operation string, target userRow, before, after *userRow) error {
e, err := cliAuditEntry(now, operation, target, before, after)
if err != nil {
return fmt.Errorf("audit value: %w", err)
}
_, err = tx.InsertAudit(ctx, e)
_, err := tx.InsertAudit(ctx, cliAuditEntry(now, operation, target, before, after))
return err
}
@@ -593,12 +654,12 @@ func (a *app) userAdd(ctx context.Context, b cliUserBackend, log *slog.Logger, u
if err != nil {
return err
}
return insertCLIAudit(ctx, tx, now, "user_create", u, nil, &u)
return insertCLIAudit(ctx, tx, now, opUserCreate, u, nil, &u)
})
if err != nil {
return err
}
logCLIChange(ctx, log, "user_create", username)
logCLIChange(ctx, log, opUserCreate, username)
return nil
}
@@ -615,12 +676,12 @@ func (a *app) userPasswd(ctx context.Context, b cliUserBackend, log *slog.Logger
if _, err := tx.DeleteUserSessions(ctx, u.ID); err != nil {
return err
}
return insertCLIAudit(ctx, tx, now, "user_password", u, &u, &u)
return insertCLIAudit(ctx, tx, now, opUserPassword, u, &u, &u)
})
if err != nil {
return err
}
logCLIChange(ctx, log, "user_password", username)
logCLIChange(ctx, log, opUserPassword, username)
return nil
}
@@ -639,7 +700,7 @@ func (a *app) userRole(ctx context.Context, b cliUserBackend, log *slog.Logger,
if u.Role == role {
return nil
}
if u.Role == "admin" && len(admins) <= 1 {
if u.Role == roleAdmin && len(admins) <= 1 {
return errLastActiveAdmin
}
if err := tx.SetRole(ctx, u.ID, role, now); err != nil {
@@ -649,13 +710,13 @@ func (a *app) userRole(ctx context.Context, b cliUserBackend, log *slog.Logger,
after.Role = role
after.UpdatedAt = now
changed = true
return insertCLIAudit(ctx, tx, now, "user_role", u, &u, &after)
return insertCLIAudit(ctx, tx, now, opUserRole, u, &u, &after)
})
if err != nil {
return err
}
if changed {
logCLIChange(ctx, log, "user_role", username)
logCLIChange(ctx, log, opUserRole, username)
}
return nil
}
@@ -671,7 +732,7 @@ func (a *app) userDelete(ctx context.Context, b cliUserBackend, log *slog.Logger
if err != nil {
return err
}
if u.Role == "admin" && len(admins) <= 1 {
if u.Role == roleAdmin && len(admins) <= 1 {
return errLastActiveAdmin
}
if err := tx.MarkDeleted(ctx, u.ID, now); err != nil {
@@ -683,11 +744,11 @@ func (a *app) userDelete(ctx context.Context, b cliUserBackend, log *slog.Logger
after := u
after.DeletedAt = sql.NullTime{Time: now, Valid: true}
after.UpdatedAt = now
return insertCLIAudit(ctx, tx, now, "user_delete", u, &u, &after)
return insertCLIAudit(ctx, tx, now, opUserDelete, u, &u, &after)
})
if err != nil {
return err
}
logCLIChange(ctx, log, "user_delete", username)
logCLIChange(ctx, log, opUserDelete, username)
return nil
}