Files
eng-pad-server/internal/auth/users.go
Kyle Isom ea9375b6ae Security hardening: fix critical, high, and medium issues from audit
CRITICAL:
- A-001: SQL injection in snapshot — escape single quotes in backup path
- A-002: Timing attack — always verify against dummy hash when user not
  found, preventing username enumeration
- A-003: Notebook ownership — all authenticated endpoints now verify
  user_id before loading notebook data
- A-004: Point data bounds — decodePoints returns error on misaligned
  data, >4MB payloads, and NaN/Inf values

HIGH:
- A-005: Error messages — generic errors in HTTP responses, no err.Error()
- A-006: Share link authz — RevokeShareLink verifies notebook ownership
- A-007: Scan errors — return 500 instead of silently continuing

MEDIUM:
- A-008: Web server TLS — optional TLS support (HTTPS when configured)
- A-009: Input validation — page_size, stroke count, point_data alignment
  checked in SyncNotebook RPC
- A-010: Graceful shutdown — 30s drain on SIGINT/SIGTERM, all servers
  shut down properly

Added AUDIT.md with all 17 findings, status, and rationale for
accepted risks.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 20:16:26 -07:00

61 lines
1.7 KiB
Go

package auth
import (
"database/sql"
"errors"
"fmt"
"time"
)
// dummyHash is a pre-computed Argon2id hash used for constant-time comparison
// when a user is not found. This prevents timing attacks that reveal whether
// a username exists.
var dummyHash = "$argon2id$v=19$m=65536,t=3,p=4$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
// CreateUser creates a new user with a hashed password.
func CreateUser(database *sql.DB, username, password string, params Argon2Params) (int64, error) {
hash, err := HashPassword(password, params)
if err != nil {
return 0, err
}
now := time.Now().UnixMilli()
res, err := database.Exec(
"INSERT INTO users (username, password_hash, created_at, updated_at) VALUES (?, ?, ?, ?)",
username, hash, now, now,
)
if err != nil {
return 0, fmt.Errorf("insert user: %w", err)
}
return res.LastInsertId()
}
// AuthenticateUser verifies username/password and returns the user ID.
func AuthenticateUser(database *sql.DB, username, password string) (int64, error) {
var userID int64
var hash string
err := database.QueryRow(
"SELECT id, password_hash FROM users WHERE username = ?", username,
).Scan(&userID, &hash)
if errors.Is(err, sql.ErrNoRows) {
// User not found: verify against dummy hash to consume constant time,
// preventing timing attacks that reveal username existence.
_, _ = VerifyPassword(password, dummyHash)
return 0, fmt.Errorf("invalid credentials")
}
if err != nil {
return 0, fmt.Errorf("invalid credentials")
}
ok, err := VerifyPassword(password, hash)
if err != nil {
return 0, fmt.Errorf("invalid credentials")
}
if !ok {
return 0, fmt.Errorf("invalid credentials")
}
return userID, nil
}