498 lines
17 KiB
Go
498 lines
17 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/ecdsa"
|
|
"crypto/elliptic"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/x509"
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const maxJSONBodyBytes = 8 * 1024
|
|
|
|
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
|
var uuidPattern = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`)
|
|
|
|
type contextKey string
|
|
|
|
const authenticatedUserIDKey contextKey = "authenticated-user-id"
|
|
const authenticatedTokenHashKey contextKey = "authenticated-token-hash"
|
|
|
|
type credentialsRequest struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
type deviceRegistrationRequest struct {
|
|
ChallengeID string `json:"challenge_id"`
|
|
IdentityKey string `json:"identity_public_key"`
|
|
ChallengeProof string `json:"challenge_signature"`
|
|
}
|
|
|
|
func (s *apiServer) register(w http.ResponseWriter, r *http.Request) {
|
|
var request credentialsRequest
|
|
if !decodeJSON(w, r, &request) {
|
|
return
|
|
}
|
|
if !usernamePattern.MatchString(request.Username) || len(request.Password) < 12 || len(request.Password) > 1024 {
|
|
writeError(w, http.StatusBadRequest, "username or password does not meet requirements")
|
|
return
|
|
}
|
|
|
|
passwordHash, err := s.passwords.hash(request.Password)
|
|
if errors.Is(err, errPasswordCapacity) {
|
|
writeError(w, http.StatusServiceUnavailable, "authentication is busy; retry shortly")
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create account")
|
|
return
|
|
}
|
|
|
|
userID, err := newUUID()
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create account")
|
|
return
|
|
}
|
|
token, tokenHash, err := newSessionToken()
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create account")
|
|
return
|
|
}
|
|
expiresAt := time.Now().UTC().Add(sessionLifetime)
|
|
tx, err := s.db.BeginTx(r.Context(), nil)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create account")
|
|
return
|
|
}
|
|
defer tx.Rollback()
|
|
err = tx.QueryRowContext(r.Context(),
|
|
`INSERT INTO users(id, username, password_hash) VALUES ($1, $2, $3)
|
|
ON CONFLICT (username) DO NOTHING RETURNING id::text`,
|
|
userID, request.Username, passwordHash,
|
|
).Scan(&userID)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
writeError(w, http.StatusConflict, "username is unavailable")
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create account")
|
|
return
|
|
}
|
|
if _, err := tx.ExecContext(r.Context(),
|
|
`INSERT INTO sessions(token_hash, user_id, expires_at) VALUES ($1, $2, $3)`,
|
|
tokenHash[:], userID, expiresAt,
|
|
); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create account")
|
|
return
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create account")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, authResponse{UserID: userID, AccessToken: token, TokenType: "Bearer", ExpiresAt: expiresAt})
|
|
}
|
|
|
|
func (s *apiServer) login(w http.ResponseWriter, r *http.Request) {
|
|
var request credentialsRequest
|
|
if !decodeJSON(w, r, &request) {
|
|
return
|
|
}
|
|
if len(request.Username) > 32 || len(request.Password) == 0 || len(request.Password) > 1024 {
|
|
writeError(w, http.StatusUnauthorized, "invalid username or password")
|
|
return
|
|
}
|
|
|
|
var userID, encodedHash string
|
|
err := s.db.QueryRowContext(r.Context(),
|
|
`SELECT id::text, password_hash FROM users WHERE username = $1`, request.Username,
|
|
).Scan(&userID, &encodedHash)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
encodedHash = s.passwords.dummyHash
|
|
} else if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not authenticate")
|
|
return
|
|
}
|
|
valid, err := s.passwords.verify(request.Password, encodedHash)
|
|
if errors.Is(err, errPasswordCapacity) {
|
|
writeError(w, http.StatusServiceUnavailable, "authentication is busy; retry shortly")
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not authenticate")
|
|
return
|
|
}
|
|
if !valid || userID == "" {
|
|
writeError(w, http.StatusUnauthorized, "invalid username or password")
|
|
return
|
|
}
|
|
|
|
token, tokenHash, err := newSessionToken()
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not authenticate")
|
|
return
|
|
}
|
|
expiresAt := time.Now().UTC().Add(sessionLifetime)
|
|
if _, err := s.db.ExecContext(r.Context(),
|
|
`INSERT INTO sessions(token_hash, user_id, expires_at) VALUES ($1, $2, $3)`,
|
|
tokenHash[:], userID, expiresAt,
|
|
); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not authenticate")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, authResponse{UserID: userID, AccessToken: token, TokenType: "Bearer", ExpiresAt: expiresAt})
|
|
}
|
|
|
|
func (s *apiServer) logout(w http.ResponseWriter, r *http.Request) {
|
|
tokenHash, _ := r.Context().Value(authenticatedTokenHashKey).([32]byte)
|
|
if _, err := s.db.ExecContext(r.Context(), `DELETE FROM sessions WHERE token_hash = $1`, tokenHash[:]); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not end session")
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (s *apiServer) requireAuth(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
header := r.Header.Get("Authorization")
|
|
if !strings.HasPrefix(header, "Bearer ") {
|
|
writeError(w, http.StatusUnauthorized, "authentication required")
|
|
return
|
|
}
|
|
token := strings.TrimPrefix(header, "Bearer ")
|
|
decoded, err := base64.RawURLEncoding.DecodeString(token)
|
|
if err != nil || len(decoded) != 32 {
|
|
writeError(w, http.StatusUnauthorized, "authentication required")
|
|
return
|
|
}
|
|
tokenHash := sha256.Sum256(decoded)
|
|
var userID string
|
|
err = s.db.QueryRowContext(r.Context(),
|
|
`SELECT user_id::text FROM sessions WHERE token_hash = $1 AND expires_at > now()`,
|
|
tokenHash[:],
|
|
).Scan(&userID)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
writeError(w, http.StatusUnauthorized, "authentication required")
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, "authentication service unavailable")
|
|
return
|
|
}
|
|
ctx := context.WithValue(r.Context(), authenticatedUserIDKey, userID)
|
|
ctx = context.WithValue(ctx, authenticatedTokenHashKey, tokenHash)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
func (s *apiServer) createDeviceChallenge(w http.ResponseWriter, r *http.Request) {
|
|
userID := r.Context().Value(authenticatedUserIDKey).(string)
|
|
tx, err := s.db.BeginTx(r.Context(), nil)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create device challenge")
|
|
return
|
|
}
|
|
defer tx.Rollback()
|
|
if err := tx.QueryRowContext(r.Context(), `SELECT id FROM users WHERE id = $1 FOR UPDATE`, userID).Scan(new(string)); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create device challenge")
|
|
return
|
|
}
|
|
if _, err := tx.ExecContext(r.Context(),
|
|
`DELETE FROM device_registration_challenges WHERE expires_at <= now() OR consumed_at IS NOT NULL`,
|
|
); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create device challenge")
|
|
return
|
|
}
|
|
var pending int
|
|
if err := tx.QueryRowContext(r.Context(),
|
|
`SELECT count(*) FROM device_registration_challenges WHERE user_id = $1 AND consumed_at IS NULL AND expires_at > now()`, userID,
|
|
).Scan(&pending); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create device challenge")
|
|
return
|
|
}
|
|
if pending >= 5 {
|
|
writeError(w, http.StatusTooManyRequests, "too many pending device challenges")
|
|
return
|
|
}
|
|
challengeID, err := newUUID()
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create device challenge")
|
|
return
|
|
}
|
|
nonce := make([]byte, 32)
|
|
if _, err := rand.Read(nonce); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create device challenge")
|
|
return
|
|
}
|
|
expiresAt := time.Now().UTC().Add(deviceChallengeLifetime)
|
|
if _, err := tx.ExecContext(r.Context(),
|
|
`INSERT INTO device_registration_challenges(id, user_id, nonce, expires_at) VALUES ($1, $2, $3, $4)`,
|
|
challengeID, userID, nonce, expiresAt,
|
|
); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create device challenge")
|
|
return
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not create device challenge")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, map[string]any{
|
|
"challenge_id": challengeID,
|
|
"challenge": base64.StdEncoding.EncodeToString(nonce),
|
|
"expires_at": expiresAt,
|
|
})
|
|
}
|
|
|
|
func (s *apiServer) registerDevice(w http.ResponseWriter, r *http.Request) {
|
|
var request deviceRegistrationRequest
|
|
if !decodeJSON(w, r, &request) {
|
|
return
|
|
}
|
|
if !uuidPattern.MatchString(request.ChallengeID) {
|
|
writeError(w, http.StatusBadRequest, "invalid device registration proof")
|
|
return
|
|
}
|
|
publicKeyDER, err := base64.StdEncoding.Strict().DecodeString(request.IdentityKey)
|
|
if err != nil || len(publicKeyDER) == 0 || len(publicKeyDER) > 512 {
|
|
writeError(w, http.StatusBadRequest, "invalid device registration proof")
|
|
return
|
|
}
|
|
parsedKey, err := x509.ParsePKIXPublicKey(publicKeyDER)
|
|
publicKey, ok := parsedKey.(*ecdsa.PublicKey)
|
|
if err != nil || !ok || publicKey.Curve == nil || publicKey.Curve.Params().Name != elliptic.P256().Params().Name ||
|
|
publicKey.X == nil || publicKey.Y == nil || !publicKey.Curve.IsOnCurve(publicKey.X, publicKey.Y) {
|
|
writeError(w, http.StatusBadRequest, "unsupported device identity key")
|
|
return
|
|
}
|
|
signature, err := base64.StdEncoding.Strict().DecodeString(request.ChallengeProof)
|
|
if err != nil || len(signature) < 8 || len(signature) > 80 {
|
|
writeError(w, http.StatusBadRequest, "invalid device registration proof")
|
|
return
|
|
}
|
|
|
|
userID := r.Context().Value(authenticatedUserIDKey).(string)
|
|
tx, err := s.db.BeginTx(r.Context(), nil)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not register device")
|
|
return
|
|
}
|
|
defer tx.Rollback()
|
|
if err := tx.QueryRowContext(r.Context(), `SELECT id FROM users WHERE id = $1 FOR UPDATE`, userID).Scan(new(string)); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not register device")
|
|
return
|
|
}
|
|
var nonce []byte
|
|
var expiresAt time.Time
|
|
err = tx.QueryRowContext(r.Context(),
|
|
`SELECT nonce, expires_at FROM device_registration_challenges
|
|
WHERE id = $1 AND user_id = $2 AND consumed_at IS NULL FOR UPDATE`,
|
|
request.ChallengeID, userID,
|
|
).Scan(&nonce, &expiresAt)
|
|
if errors.Is(err, sql.ErrNoRows) || (err == nil && !time.Now().Before(expiresAt)) {
|
|
writeError(w, http.StatusBadRequest, "invalid or expired device registration challenge")
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not register device")
|
|
return
|
|
}
|
|
proofMessage := append([]byte("ee2e-device-registration-v1\x00"+request.ChallengeID+"\x00"), nonce...)
|
|
digest := sha256.Sum256(proofMessage)
|
|
if !ecdsa.VerifyASN1(publicKey, digest[:], signature) {
|
|
writeError(w, http.StatusBadRequest, "invalid device registration proof")
|
|
return
|
|
}
|
|
var activeDevices int
|
|
if err := tx.QueryRowContext(r.Context(),
|
|
`SELECT count(*) FROM devices WHERE user_id = $1 AND status = 'active'`, userID,
|
|
).Scan(&activeDevices); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not register device")
|
|
return
|
|
}
|
|
if activeDevices >= maxActiveDevices {
|
|
writeError(w, http.StatusConflict, "device limit reached")
|
|
return
|
|
}
|
|
deviceID, err := newUUID()
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not register device")
|
|
return
|
|
}
|
|
if _, err := tx.ExecContext(r.Context(),
|
|
`UPDATE device_registration_challenges SET consumed_at = now() WHERE id = $1`, request.ChallengeID,
|
|
); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not register device")
|
|
return
|
|
}
|
|
if _, err := tx.ExecContext(r.Context(),
|
|
`INSERT INTO devices(id, user_id, identity_public_key, status) VALUES ($1, $2, $3, 'active')`,
|
|
deviceID, userID, publicKeyDER,
|
|
); err != nil {
|
|
writeError(w, http.StatusConflict, "device key is already registered or invalid")
|
|
return
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not register device")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, map[string]string{
|
|
"device_id": deviceID,
|
|
"identity_key_type": "ecdsa-p256-sha256-v1",
|
|
"fingerprint": fingerprint(publicKeyDER),
|
|
})
|
|
}
|
|
|
|
func (s *apiServer) listDevices(w http.ResponseWriter, r *http.Request) {
|
|
username := r.PathValue("username")
|
|
if !usernamePattern.MatchString(username) {
|
|
writeError(w, http.StatusBadRequest, "invalid username")
|
|
return
|
|
}
|
|
rows, err := s.db.QueryContext(r.Context(),
|
|
`SELECT d.id::text, d.identity_public_key, d.created_at
|
|
FROM devices d JOIN users u ON u.id = d.user_id
|
|
WHERE u.username = $1 AND d.status = 'active' ORDER BY d.created_at, d.id`, username,
|
|
)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not read device directory")
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
devices := make([]directoryDevice, 0)
|
|
for rows.Next() {
|
|
var device directoryDevice
|
|
var publicKey []byte
|
|
if err := rows.Scan(&device.DeviceID, &publicKey, &device.CreatedAt); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not read device directory")
|
|
return
|
|
}
|
|
device.IdentityKeyType = "ecdsa-p256-sha256-v1"
|
|
device.IdentityPublicKey = base64.StdEncoding.EncodeToString(publicKey)
|
|
device.Fingerprint = fingerprint(publicKey)
|
|
devices = append(devices, device)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not read device directory")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"username": username, "devices": devices})
|
|
}
|
|
|
|
func (s *apiServer) revokeDevice(w http.ResponseWriter, r *http.Request) {
|
|
deviceID := r.PathValue("deviceID")
|
|
if !uuidPattern.MatchString(deviceID) {
|
|
writeError(w, http.StatusBadRequest, "invalid device id")
|
|
return
|
|
}
|
|
userID := r.Context().Value(authenticatedUserIDKey).(string)
|
|
result, err := s.db.ExecContext(r.Context(),
|
|
`UPDATE devices SET status = 'revoked' WHERE id = $1 AND user_id = $2 AND status = 'active'`, deviceID, userID,
|
|
)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not revoke device")
|
|
return
|
|
}
|
|
count, err := result.RowsAffected()
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "could not revoke device")
|
|
return
|
|
}
|
|
if count == 0 {
|
|
writeError(w, http.StatusNotFound, "device not found")
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
type authResponse struct {
|
|
UserID string `json:"user_id"`
|
|
AccessToken string `json:"access_token"`
|
|
TokenType string `json:"token_type"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
}
|
|
|
|
type directoryDevice struct {
|
|
DeviceID string `json:"device_id"`
|
|
IdentityKeyType string `json:"identity_key_type"`
|
|
IdentityPublicKey string `json:"identity_public_key"`
|
|
Fingerprint string `json:"fingerprint"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
func decodeJSON(w http.ResponseWriter, r *http.Request, destination any) bool {
|
|
r.Body = http.MaxBytesReader(w, r.Body, maxJSONBodyBytes)
|
|
decoder := json.NewDecoder(r.Body)
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(destination); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid JSON request")
|
|
return false
|
|
}
|
|
var extra any
|
|
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
|
writeError(w, http.StatusBadRequest, "invalid JSON request")
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(value)
|
|
}
|
|
|
|
func writeError(w http.ResponseWriter, status int, message string) {
|
|
writeJSON(w, status, map[string]string{"error": message})
|
|
}
|
|
|
|
func newUUID() (string, error) {
|
|
bytes := make([]byte, 16)
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
return "", err
|
|
}
|
|
bytes[6] = (bytes[6] & 0x0f) | 0x40
|
|
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
|
encoded := hex.EncodeToString(bytes)
|
|
return fmt.Sprintf("%s-%s-%s-%s-%s", encoded[:8], encoded[8:12], encoded[12:16], encoded[16:20], encoded[20:]), nil
|
|
}
|
|
|
|
func newSessionToken() (string, [32]byte, error) {
|
|
var tokenHash [32]byte
|
|
bytes := make([]byte, 32)
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
return "", tokenHash, err
|
|
}
|
|
tokenHash = sha256.Sum256(bytes)
|
|
return base64.RawURLEncoding.EncodeToString(bytes), tokenHash, nil
|
|
}
|
|
|
|
func fingerprint(publicKey []byte) string {
|
|
digest := sha256.Sum256(publicKey)
|
|
encoded := strings.ToUpper(hex.EncodeToString(digest[:]))
|
|
parts := make([]string, 0, len(encoded)/2)
|
|
for i := 0; i < len(encoded); i += 2 {
|
|
parts = append(parts, encoded[i:i+2])
|
|
}
|
|
return strings.Join(parts, ":")
|
|
}
|
|
|
|
const (
|
|
sessionLifetime = 30 * 24 * time.Hour
|
|
deviceChallengeLifetime = 5 * time.Minute
|
|
maxActiveDevices = 10
|
|
)
|