hub: S2 API — box-facing WG registration + merge-at-read + hub-owned-key guard

POST /hosts/{id}/wg (per-host self-scoped; global = operator/DR path): bind /
re-key-in-place / adopt; generation bump + endpoint push ONLY on real change.
mergeWireguard injects the hub-owned block into served desired-state at READ
time (stored operator blob never touched; fail-safe unmerged on any error;
no-peer = byte-identical pass-through — existing golden test untouched+green).
handleAdminSetDesiredState rejects top-level wireguard (400). Admin DELETE of a
BOUND peer bumps the owning host. NEW golden desired-state-wireguard.golden.json
= the S3 cross-repo contract. Red-proofs a/b/c/d run + reverted.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PSK5g6qYLknKj8u3QAFEr6
This commit is contained in:
2026-07-04 00:44:40 +02:00
parent fcf84a0c5c
commit ba52005e61
4 changed files with 447 additions and 0 deletions
+147
View File
@@ -198,6 +198,135 @@ func (h *Handler) handleAdminAddWGPeer(w http.ResponseWriter, r *http.Request) {
})
}
// handleRegisterHostWG — POST /hosts/{host_id}/wg (S2, doc 06 §3.3 steps 2-4). The box-facing
// registration: per-host key SELF-SCOPED (the handleGetDesiredState gate; the global key may
// register on any host — the operator/DR path). Binds the pubkey to the host (idempotent /
// re-key-in-place / adopt-unbound per the store), and ONLY on a real change bumps the host's
// desired_generation + pushes the peer list to the endpoint.
func (h *Handler) handleRegisterHostWG(w http.ResponseWriter, r *http.Request, pathHostID string) {
authHostID, _, isGlobal, ok := h.checkAuthHost(r)
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
if pathHostID == "" {
http.Error(w, "Missing host_id", http.StatusBadRequest)
return
}
if !isGlobal && authHostID != pathHostID {
http.Error(w, "Forbidden: host_id mismatch", http.StatusForbidden)
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
var req struct {
Pubkey string `json:"pubkey"`
}
if err := json.Unmarshal(body, &req); err != nil {
http.Error(w, "Invalid payload: body must be JSON", http.StatusBadRequest)
return
}
if err := validateWGPubkey(req.Pubkey); err != nil {
http.Error(w, "Invalid payload: "+err.Error(), http.StatusBadRequest)
return
}
host, err := h.store.GetHost(pathHostID)
if err != nil {
h.logger.Printf("[ERROR] wg register: host lookup %s: %v", pathHostID, err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if host == nil {
http.Error(w, "Unknown host_id", http.StatusNotFound)
return
}
ip, changed, err := h.store.RegisterWGPeerForHost(pathHostID, req.Pubkey)
switch {
case err == store.ErrWGEndpointUnset:
http.Error(w, "wg endpoint not configured", http.StatusConflict)
return
case err == store.ErrWGPubkeyBoundElsewhere:
http.Error(w, "pubkey already registered elsewhere", http.StatusConflict)
return
case err == store.ErrWGSubnetExhausted:
http.Error(w, "tunnel subnet exhausted", http.StatusConflict)
return
case err != nil:
h.logger.Printf("[ERROR] wg register %s: %v", pathHostID, err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
gen := host.DesiredGeneration
syncStatus := "unchanged"
if changed {
gen, err = h.store.BumpHostDesired(pathHostID)
if err != nil {
h.logger.Printf("[ERROR] wg register %s: generation bump: %v", pathHostID, err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
syncStatus = h.syncAfterMutation(r.Context())
}
h.logger.Printf("[INFO] wg registered: host=%s pubkey=%s ip=%s/32 changed=%v gen=%d sync=%s",
pathHostID, req.Pubkey, ip, changed, gen, syncStatus)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]interface{}{
"pubkey": req.Pubkey, "assigned_ip": ip + "/32", "existed": !changed,
"generation": gen, "sync": syncStatus,
})
}
// mergeWireguard injects the hub-OWNED wireguard block into a host's served desired-state (S2
// merge-at-read: the stored desired_json stays a pure operator blob; the WG assignment is hub
// state and is merged only on the way out). No peer → the blob passes through untouched (the
// golden pass-through contract). Any merge failure is fail-safe: log + serve UNMERGED — never
// break the agent's control channel over the WG add-on.
//
// Deliberately NOT wire fields (S3 agent constants derived from the design + pbs_tunnel_ip):
// client-side AllowedIPs, PersistentKeepalive=25, MTU 1420.
func (h *Handler) mergeWireguard(hostID, desired string) string {
peer, err := h.store.GetWGPeerForHost(hostID)
if err == sql.ErrNoRows {
return desired // no peer — byte-identical pass-through
}
if err != nil {
h.logger.Printf("[ERROR] wg merge %s: peer lookup: %v (serving unmerged)", hostID, err)
return desired
}
ep, err := h.store.GetWGEndpoint()
if err != nil {
h.logger.Printf("[ERROR] wg merge %s: peer exists but endpoint record unreadable: %v (serving unmerged)", hostID, err)
return desired
}
var doc map[string]interface{}
if err := json.Unmarshal([]byte(desired), &doc); err != nil {
h.logger.Printf("[ERROR] wg merge %s: stored desired_json unparsable: %v (serving unmerged)", hostID, err)
return desired
}
doc["wireguard"] = map[string]interface{}{
"endpoint": map[string]interface{}{
"dns_name": ep.DNSName,
"wg_port": ep.WGPort,
"server_pubkey": ep.ServerPubkey,
"pbs_tunnel_ip": ep.PBSTunnelIP,
},
"pubkey": peer.Pubkey,
"assigned_ip": peer.AssignedIP + "/32",
}
out, err := json.Marshal(doc)
if err != nil {
h.logger.Printf("[ERROR] wg merge %s: re-marshal: %v (serving unmerged)", hostID, err)
return desired
}
return string(out)
}
// handleAdminDeleteWGPeer — DELETE /admin/wg/peers, pubkey in the JSON body (never the URL).
// Unknown pubkey → 404 with NO sync (nothing changed). Known → delete + inline push: the pushed
// full list no longer contains the peer, so revocation lands with the push (Scenario B).
@@ -223,6 +352,17 @@ func (h *Handler) handleAdminDeleteWGPeer(w http.ResponseWriter, r *http.Request
http.Error(w, "Invalid payload: "+err.Error(), http.StatusBadRequest)
return
}
// S2: a BOUND peer's host must learn its block is gone — read the owner before deleting so
// the delete can bump that host's generation (an unbound S1 row bumps nothing).
ownerHostID := ""
if peers, err := h.store.ListWGPeers(); err == nil {
for _, p := range peers {
if p.Pubkey == req.Pubkey {
ownerHostID = p.HostID
break
}
}
}
err = h.store.RemoveWGPeer(req.Pubkey)
if err == sql.ErrNoRows {
http.Error(w, "Unknown pubkey", http.StatusNotFound)
@@ -233,6 +373,13 @@ func (h *Handler) handleAdminDeleteWGPeer(w http.ResponseWriter, r *http.Request
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if ownerHostID != "" {
if gen, err := h.store.BumpHostDesired(ownerHostID); err != nil {
h.logger.Printf("[ERROR] wg delete: generation bump for %s: %v", ownerHostID, err)
} else {
h.logger.Printf("[INFO] wg delete: host %s generation -> %d (peer unbound)", ownerHostID, gen)
}
}
syncStatus := h.syncAfterMutation(r.Context())
h.logger.Printf("[INFO] wg peer removed: %s (sync=%s)", req.Pubkey, syncStatus)
w.Header().Set("Content-Type", "application/json")