ARTEX/db/proxy_pool.go
Grady May a383e5bcb2 feat(db): store proxy pool entries behind a masked API
Part 1 of 4 of the proxy pool design in #545: storage and a CRUD API.
Nothing activates an entry yet, so the global proxy is unchanged.

- Migration 0028 adds proxy_pool: a unique keyed address hash, at most
  one active entry (partial unique index), a CHECK that the active entry
  is enabled, and nullable egress_ip, last_check_at and last_check_ok for
  the health check.
- Addresses are normalized, sealed at rest (AAD proxy_pool.address) and
  covered by the startup key check and key rotation. Uniqueness uses an
  HMAC under a sub-key kept on secretBox; RotateSecretKey locks the table
  and rehashes in its transaction, and pool writes seal under that lock.
- GET/POST /api/proxy-pool and PATCH/DELETE /api/proxy-pool/{id} never
  return an address; a masked address on update keeps the stored one.
2026-12-02 22:05:05 -05:00

370 lines
12 KiB
Go

package db
import (
"context"
"crypto/hmac"
"crypto/sha256"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"net"
"net/url"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/jackc/pgx/v5/pgconn"
)
// Proxy pool (#545): stored candidates for the global egress proxy. This layer
// stores entries and keeps their addresses sealed; it never activates one.
// The address is in clear on ProxyPoolEntry, so a handler must never return
// the struct as is.
const (
MaxProxyPoolEntries = 100
MaxProxyPoolLabelRunes = 100
)
var (
ErrProxyPoolInvalid = errors.New("invalid proxy pool entry")
ErrProxyPoolDuplicate = errors.New("a proxy pool entry with this address already exists")
ErrProxyPoolLimit = fmt.Errorf("the limit of %d proxy pool entries is reached", MaxProxyPoolEntries)
// ErrProxyPoolActive refuses to disable or delete the active entry.
ErrProxyPoolActive = errors.New("the active proxy pool entry cannot be disabled or deleted")
)
var colProxyPoolAddress = secretColumn{"proxy_pool", "address", false, ""}
// ProxyPoolEntry is one row of proxy_pool. Address is the normalized address
// in clear, credentials included.
type ProxyPoolEntry struct {
ID int64
Label string
Address string
Enabled bool
Active bool
EgressIP *string // nil: never checked
LastCheckAt *time.Time // nil: never checked
LastCheckOK *bool // nil: never checked
CreatedAt time.Time
UpdatedAt time.Time
}
const proxyPoolCols = `id, label, address, enabled, active, egress_ip, last_check_at, last_check_ok, created_at, updated_at`
func scanProxyPoolEntry(row interface{ Scan(...any) error }) (ProxyPoolEntry, error) {
var e ProxyPoolEntry
var egress sql.NullString
var checkedAt sql.NullTime
var ok sql.NullBool
err := row.Scan(&e.ID, &e.Label, &e.Address, &e.Enabled, &e.Active, &egress, &checkedAt, &ok, &e.CreatedAt, &e.UpdatedAt)
if err != nil {
return e, err
}
if egress.Valid {
e.EgressIP = &egress.String
}
if checkedAt.Valid {
e.LastCheckAt = &checkedAt.Time
}
if ok.Valid {
e.LastCheckOK = &ok.Bool
}
e.Address, err = openSecret(colProxyPoolAddress, e.Address)
return e, err
}
// proxyPoolDefaultPorts are the ports net/http assumes for a proxy URL without
// one, made explicit so "http://h" and "http://h:80" are the same entry.
var proxyPoolDefaultPorts = map[string]string{"http": "80", "https": "443", "socks5": "1080"}
// NormalizeProxyAddress checks a proxy address and returns its canonical form:
// scheme://[user[:pass]@]host:port, with the scheme and host in lower case and
// the default port made explicit. It accepts http, https and socks5, the
// schemes of the global proxy, and refuses a path, query or fragment.
func NormalizeProxyAddress(raw string) (string, error) {
raw = strings.TrimSpace(raw)
u, err := url.Parse(raw)
if err != nil {
return "", fmt.Errorf("%w: the address does not parse as a URL", ErrProxyPoolInvalid)
}
scheme := strings.ToLower(u.Scheme)
defPort, ok := proxyPoolDefaultPorts[scheme]
if !ok {
return "", fmt.Errorf("%w: use an http://, https:// or socks5:// address", ErrProxyPoolInvalid)
}
if u.Opaque != "" || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
return "", fmt.Errorf("%w: a proxy address has no path, query or fragment", ErrProxyPoolInvalid)
}
host := strings.ToLower(u.Hostname())
if host == "" {
return "", fmt.Errorf("%w: the address has no host", ErrProxyPoolInvalid)
}
port := u.Port()
if port == "" {
if strings.HasSuffix(u.Host, ":") {
return "", fmt.Errorf("%w: the port is empty", ErrProxyPoolInvalid)
}
port = defPort
}
n, err := strconv.Atoi(port)
if err != nil || n < 1 || n > 65535 {
return "", fmt.Errorf("%w: the port must be between 1 and 65535", ErrProxyPoolInvalid)
}
port = strconv.Itoa(n) // "080" and "80" are the same port
out := url.URL{Scheme: scheme, User: u.User, Host: net.JoinHostPort(host, port)}
return out.String(), nil
}
func normalizeProxyPoolLabel(label string) (string, error) {
label = strings.TrimSpace(label)
switch {
case label == "":
return "", fmt.Errorf("%w: a label is required", ErrProxyPoolInvalid)
case utf8.RuneCountInString(label) > MaxProxyPoolLabelRunes:
return "", fmt.Errorf("%w: the label exceeds %d characters", ErrProxyPoolInvalid, MaxProxyPoolLabelRunes)
}
return label, nil
}
// proxyPoolKeyMu orders pool writes against a key rotation in this process
// (proxyPoolTx, RotateSecretKey).
var proxyPoolKeyMu sync.RWMutex
// proxyPoolHashDomain separates the address-hash key from the secret key it
// is derived from.
const proxyPoolHashDomain = "artex-proxy-pool-address"
// proxyAddressHash is the uniqueness key of a normalized address: an HMAC
// under the box's sub-key, so the table never holds an unkeyed digest of a
// credential.
func (b *secretBox) proxyAddressHash(normalized string) string {
m := hmac.New(sha256.New, b.proxyPoolHashKey)
m.Write([]byte(normalized))
return hex.EncodeToString(m.Sum(nil))
}
// rehashProxyPool recomputes every address hash under box. RotateSecretKey
// runs it inside its transaction, which holds the table lock from before the
// addresses are sealed again until commit, so no pool write interleaves and
// the placeholder below never commits.
func rehashProxyPool(ctx context.Context, tx *sql.Tx, box *secretBox) error {
rows, err := tx.QueryContext(ctx, `SELECT id, address FROM proxy_pool`)
if err != nil {
return fmt.Errorf("rehash proxy_pool: %w", err)
}
type rehash struct {
id int64
hash string
}
var todo []rehash
for rows.Next() {
var id int64
var addr string
if err = rows.Scan(&id, &addr); err != nil {
break
}
if isSealed(colProxyPoolAddress, addr) {
if addr, err = box.open(colProxyPoolAddress, addr); err != nil {
break
}
}
todo = append(todo, rehash{id, box.proxyAddressHash(addr)})
}
rows.Close()
if err == nil {
err = rows.Err()
}
if err != nil {
return fmt.Errorf("rehash proxy_pool: %w", err)
}
// Move every hash out of the way first: a new hash may equal another
// row's old one, which the unique constraint would refuse mid-update.
if _, err := tx.ExecContext(ctx, `UPDATE proxy_pool SET address_hash='rehash:'||id`); err != nil {
return fmt.Errorf("rehash proxy_pool: %w", err)
}
for _, r := range todo {
if _, err := tx.ExecContext(ctx, `UPDATE proxy_pool SET address_hash=$2 WHERE id=$1`, r.id, r.hash); err != nil {
return fmt.Errorf("rehash proxy_pool id=%d: %w", r.id, err)
}
}
return nil
}
// proxyPoolWriteErr maps a constraint violation to the error the caller
// reports.
func proxyPoolWriteErr(err error) error {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
switch {
case pgErr.Code == "23505" && pgErr.ConstraintName == "proxy_pool_address_hash_key":
return ErrProxyPoolDuplicate
case pgErr.Code == "23514" && pgErr.ConstraintName == "proxy_pool_active_enabled":
return ErrProxyPoolActive
}
}
return err
}
// sealProxyAddress returns the sealed form and hash of a normalized address.
// Writers call it under the table lock, which RotateSecretKey also takes, so a
// write never interleaves a rotation's reseal and rehash. A server process
// still holds the old key after an out-of-process rotation until it restarts
// (docs/OPS.md), as for every sealed column.
func sealProxyAddress(normalized string) (sealed, hash string, err error) {
b := activeSecretBox.Load() // one box for both, so they share a key
if b == nil {
return "", "", errNoSecretKey
}
sealed, err = b.seal(colProxyPoolAddress, normalized)
return sealed, b.proxyAddressHash(normalized), err
}
// ListProxyPool returns every entry, oldest first.
func (d *DB) ListProxyPool() ([]ProxyPoolEntry, error) {
rows, err := d.Query(`SELECT ` + proxyPoolCols + ` FROM proxy_pool ORDER BY id`)
if err != nil {
return nil, err
}
defer rows.Close()
out := []ProxyPoolEntry{}
for rows.Next() {
e, err := scanProxyPoolEntry(rows)
if err != nil {
return nil, err
}
out = append(out, e)
}
return out, rows.Err()
}
// GetProxyPoolEntry returns one entry, sql.ErrNoRows when it does not exist.
func (d *DB) GetProxyPoolEntry(id int64) (ProxyPoolEntry, error) {
return scanProxyPoolEntry(d.QueryRow(`SELECT `+proxyPoolCols+` FROM proxy_pool WHERE id=$1`, id))
}
// proxyPoolTx runs fn with the table locked against concurrent writers, so the
// limit count and the row fn reads cannot change before it commits.
//
// It also holds proxyPoolKeyMu shared through commit. RotateSecretKey holds it
// exclusively from before its transaction until the new box is published, so
// a write in this process never runs between the rotation's commit (which
// releases the table lock) and the key swap.
func (d *DB) proxyPoolTx(fn func(tx *sql.Tx) error) error {
proxyPoolKeyMu.RLock()
defer proxyPoolKeyMu.RUnlock()
tx, err := d.Begin()
if err != nil {
return err
}
defer tx.Rollback() //nolint:errcheck // no-op after Commit
if _, err := tx.Exec(`LOCK TABLE proxy_pool IN SHARE ROW EXCLUSIVE MODE`); err != nil {
return err
}
if err := fn(tx); err != nil {
return proxyPoolWriteErr(err)
}
return proxyPoolWriteErr(tx.Commit())
}
// CreateProxyPoolEntry stores a new, inactive entry. The address is
// normalized (NormalizeProxyAddress) and sealed.
func (d *DB) CreateProxyPoolEntry(label, address string, enabled bool) (out ProxyPoolEntry, err error) {
if label, err = normalizeProxyPoolLabel(label); err != nil {
return out, err
}
normalized, err := NormalizeProxyAddress(address)
if err != nil {
return out, err
}
err = d.proxyPoolTx(func(tx *sql.Tx) error {
sealed, hash, err := sealProxyAddress(normalized)
if err != nil {
return err
}
var n int
if err := tx.QueryRow(`SELECT count(*) FROM proxy_pool`).Scan(&n); err != nil {
return err
}
if n >= MaxProxyPoolEntries {
return ErrProxyPoolLimit
}
out, err = scanProxyPoolEntry(tx.QueryRow(`
INSERT INTO proxy_pool(label, address, address_hash, enabled)
VALUES ($1, $2, $3, $4)
RETURNING `+proxyPoolCols, label, sealed, hash, enabled))
return err
})
return out, err
}
// ProxyPoolEdit is a partial update: a nil field keeps the stored value.
type ProxyPoolEdit struct {
Label *string
Address *string
Enabled *bool
}
// UpdateProxyPoolEntry applies edit to entry id. sql.ErrNoRows when it does
// not exist, ErrProxyPoolActive when it would disable the active entry.
func (d *DB) UpdateProxyPoolEntry(id int64, edit ProxyPoolEdit) (out ProxyPoolEntry, err error) {
var label, normalized *string
if edit.Label != nil {
l, err := normalizeProxyPoolLabel(*edit.Label)
if err != nil {
return out, err
}
label = &l
}
if edit.Address != nil {
n, err := NormalizeProxyAddress(*edit.Address)
if err != nil {
return out, err
}
normalized = &n
}
err = d.proxyPoolTx(func(tx *sql.Tx) error {
var sealed, hash *string
if normalized != nil {
s, h, err := sealProxyAddress(*normalized)
if err != nil {
return err
}
sealed, hash = &s, &h
}
var active bool
if err := tx.QueryRow(`SELECT active FROM proxy_pool WHERE id=$1`, id).Scan(&active); err != nil {
return err
}
if active && edit.Enabled != nil && !*edit.Enabled {
return ErrProxyPoolActive
}
out, err = scanProxyPoolEntry(tx.QueryRow(`
UPDATE proxy_pool
SET label=COALESCE($2, label), address=COALESCE($3, address),
address_hash=COALESCE($4, address_hash), enabled=COALESCE($5, enabled)
WHERE id=$1
RETURNING `+proxyPoolCols, id, label, sealed, hash, edit.Enabled))
return err
})
return out, err
}
// DeleteProxyPoolEntry removes an entry. sql.ErrNoRows when it does not
// exist, ErrProxyPoolActive when it is the active entry.
func (d *DB) DeleteProxyPoolEntry(id int64) error {
return d.proxyPoolTx(func(tx *sql.Tx) error {
var active bool
if err := tx.QueryRow(`SELECT active FROM proxy_pool WHERE id=$1`, id).Scan(&active); err != nil {
return err
}
if active {
return ErrProxyPoolActive
}
return oneRow(tx.Exec(`DELETE FROM proxy_pool WHERE id=$1`, id))
})
}