hub: S2 store — host-bound WG peers (register/re-key/adopt), one-per-host index, BumpHostDesired
allocateWGPeerTx extracted from addWGPeerOnce (behavior-neutral; S1 tests unmodified+green). RegisterWGPeerForHost: idempotent / re-key-in-place-keep-ip / adopt-unbound / ErrWGPubkeyBoundElsewhere. Partial unique index enforces one bound peer per host. BumpHostDesired touches ONLY the generation. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PSK5g6qYLknKj8u3QAFEr6
This commit is contained in:
+151
-34
@@ -20,6 +20,10 @@ var ErrWGEndpointUnset = errors.New("wg endpoint not configured")
|
||||
// ErrWGSubnetExhausted is returned when the tunnel subnet has no free host address left.
|
||||
var ErrWGSubnetExhausted = errors.New("tunnel subnet exhausted")
|
||||
|
||||
// ErrWGPubkeyBoundElsewhere is returned by RegisterWGPeerForHost when the pubkey is already
|
||||
// registered for a different owner — a key is never silently stolen (S2 Scenario C-c2).
|
||||
var ErrWGPubkeyBoundElsewhere = errors.New("wg pubkey already registered elsewhere")
|
||||
|
||||
// WGEndpoint is the public endpoint's coordinates (doc 06 §3.2 "endpoint record"). One row
|
||||
// expected ("ep0") for now; the schema allows more for a later multi-endpoint world.
|
||||
type WGEndpoint struct {
|
||||
@@ -103,49 +107,162 @@ func (s *Store) addWGPeerOnce(pubkey, hostID, note string) (string, bool, error)
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
var subnet, pbsIP string
|
||||
err = tx.QueryRow(`SELECT tunnel_subnet, pbs_tunnel_ip FROM wg_endpoints ORDER BY endpoint_id LIMIT 1`).
|
||||
Scan(&subnet, &pbsIP)
|
||||
if err == sql.ErrNoRows {
|
||||
return "", false, ErrWGEndpointUnset
|
||||
}
|
||||
ip, err := allocateWGPeerTx(tx, pubkey, hostID, note)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
taken := map[string]bool{}
|
||||
rows, err := tx.Query(`SELECT assigned_ip FROM wg_peers`)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var ip string
|
||||
if err := rows.Scan(&ip); err != nil {
|
||||
rows.Close()
|
||||
return "", false, err
|
||||
}
|
||||
taken[ip] = true
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
ip, err := lowestFreeHost(subnet, pbsIP, taken)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(`INSERT INTO wg_peers (pubkey, assigned_ip, host_id, note) VALUES (?, ?, ?, ?)`,
|
||||
pubkey, ip, hostID, note); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return ip, false, nil
|
||||
}
|
||||
|
||||
// allocateWGPeerTx is the tx-scoped allocation core (S2 extraction — behavior-identical to the
|
||||
// S1 inline code): load the endpoint, read the taken set, pick the lowest free host address,
|
||||
// INSERT. Callers own the transaction and the pubkey-existence checks.
|
||||
func allocateWGPeerTx(tx *sql.Tx, pubkey, hostID, note string) (string, error) {
|
||||
var subnet, pbsIP string
|
||||
err := tx.QueryRow(`SELECT tunnel_subnet, pbs_tunnel_ip FROM wg_endpoints ORDER BY endpoint_id LIMIT 1`).
|
||||
Scan(&subnet, &pbsIP)
|
||||
if err == sql.ErrNoRows {
|
||||
return "", ErrWGEndpointUnset
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
taken := map[string]bool{}
|
||||
rows, err := tx.Query(`SELECT assigned_ip FROM wg_peers`)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for rows.Next() {
|
||||
var ip string
|
||||
if err := rows.Scan(&ip); err != nil {
|
||||
rows.Close()
|
||||
return "", err
|
||||
}
|
||||
taken[ip] = true
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
ip, err := lowestFreeHost(subnet, pbsIP, taken)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(`INSERT INTO wg_peers (pubkey, assigned_ip, host_id, note) VALUES (?, ?, ?, ?)`,
|
||||
pubkey, ip, hostID, note); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return ip, nil
|
||||
}
|
||||
|
||||
// RegisterWGPeerForHost binds a pubkey to a host (S2 — the box-facing registration core).
|
||||
// One transaction; outcomes:
|
||||
// - host already has this pubkey → (ip, changed=false): idempotent, NO generation/sync side effects
|
||||
// - host has a DIFFERENT pubkey → re-key IN PLACE: pubkey replaced, /32 KEPT (stable tunnel
|
||||
// addressing across rotation/DR); conflict with any existing row for the new pubkey → typed error
|
||||
// - no row for host: pubkey exists bound elsewhere → ErrWGPubkeyBoundElsewhere; exists unbound
|
||||
// (an S1 admin/test row) → ADOPT it (bind, keep its ip); absent → allocate the lowest free /32
|
||||
//
|
||||
// The idx_wg_peers_host partial unique index backstops the one-bound-peer-per-host invariant.
|
||||
func (s *Store) RegisterWGPeerForHost(hostID, pubkey string) (ip string, changed bool, err error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
ip, changed, err = s.registerWGPeerForHostOnce(hostID, pubkey)
|
||||
if err != nil && attempt == 0 && strings.Contains(err.Error(), "UNIQUE constraint failed: wg_peers.assigned_ip") {
|
||||
continue // allocation race — retry once against the fresh taken set
|
||||
}
|
||||
return ip, changed, err
|
||||
}
|
||||
return ip, changed, err
|
||||
}
|
||||
|
||||
func (s *Store) registerWGPeerForHostOnce(hostID, pubkey string) (string, bool, error) {
|
||||
if hostID == "" {
|
||||
return "", false, fmt.Errorf("wg: RegisterWGPeerForHost needs a host_id")
|
||||
}
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Existing binding for this host?
|
||||
var curPK, curIP string
|
||||
err = tx.QueryRow(`SELECT pubkey, assigned_ip FROM wg_peers WHERE host_id = ?`, hostID).Scan(&curPK, &curIP)
|
||||
if err == nil {
|
||||
if curPK == pubkey {
|
||||
return curIP, false, nil // idempotent re-register
|
||||
}
|
||||
// Re-key in place. The new pubkey must not exist anywhere (bound OR unbound) — a key is
|
||||
// never stolen, and adopting here would change the host's ip (stable-IP rule forbids it).
|
||||
var n int
|
||||
if err := tx.QueryRow(`SELECT COUNT(*) FROM wg_peers WHERE pubkey = ?`, pubkey).Scan(&n); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if n > 0 {
|
||||
return "", false, ErrWGPubkeyBoundElsewhere
|
||||
}
|
||||
if _, err := tx.Exec(`UPDATE wg_peers SET pubkey = ?, updated_at = datetime('now') WHERE host_id = ?`,
|
||||
pubkey, hostID); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return curIP, true, nil
|
||||
}
|
||||
if err != sql.ErrNoRows {
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
// No binding for this host — does the pubkey already exist?
|
||||
var pkHost, pkIP string
|
||||
err = tx.QueryRow(`SELECT host_id, assigned_ip FROM wg_peers WHERE pubkey = ?`, pubkey).Scan(&pkHost, &pkIP)
|
||||
if err == nil {
|
||||
if pkHost != "" {
|
||||
return "", false, ErrWGPubkeyBoundElsewhere
|
||||
}
|
||||
// Unbound S1 row → adopt: bind it to the host, keep its ip.
|
||||
if _, err := tx.Exec(`UPDATE wg_peers SET host_id = ?, updated_at = datetime('now') WHERE pubkey = ?`,
|
||||
hostID, pubkey); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return pkIP, true, nil
|
||||
}
|
||||
if err != sql.ErrNoRows {
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
// Fresh registration → allocate.
|
||||
ip, err := allocateWGPeerTx(tx, pubkey, hostID, "")
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return ip, true, nil
|
||||
}
|
||||
|
||||
// GetWGPeerForHost returns the host's bound peer, or sql.ErrNoRows when none.
|
||||
func (s *Store) GetWGPeerForHost(hostID string) (*WGPeer, error) {
|
||||
var p WGPeer
|
||||
err := s.db.QueryRow(`SELECT pubkey, assigned_ip, host_id, note FROM wg_peers WHERE host_id = ?`, hostID).
|
||||
Scan(&p.Pubkey, &p.AssignedIP, &p.HostID, &p.Note)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
// lowestFreeHost walks the subnet's host addresses from lowest and returns the first not in
|
||||
// `taken`, skipping the network address, the endpoint's own address, and (v4) the broadcast.
|
||||
func lowestFreeHost(subnet, endpointIP string, taken map[string]bool) (string, error) {
|
||||
|
||||
Reference in New Issue
Block a user