hub v0.66.0 + ISO v1.20.0: customer self-bind (R-27 slice 1)
Let a customer bind their own freshly-installed appliance without the operator: operator "Send self-bind link" mints a 7-day tokenized capability link, emailed (Hungarian, sibling sender) to the customer, who opens a public /bind/<token> page and proves two factors — the console pairing code shown on the box screen + their retrieval passphrase — and the hub stages the bind via the same BindAppliance (provenance customer_selfbind). The box's ~30s appliance poll delivers. Viktor's three rulings verbatim: console pairing code (no appliance list ever rendered), operator-sent tokenized link, 5-attempt lockout -> "call support". Wrong code == wrong passphrase (one generic failure, no oracle, both factors compared unconditionally); expiry falls back to operator-bind unchanged. THE TRAP: one public prefix /bind/, exempt from auth+CSRF at both /login gate sites via a single isPublicBindPath predicate (tight trailing-slash match; ServeMux ..-cleans; handler rejects '/' in token). 9 tests (Scenarios A-F + F1/F2); 4 red-proofs verified red-then-green (lockout, oracle, widened-prefix, single-active). GC verdict: no appliance GC -> the 7-day TTL stands alone. Controller/agent untouched; R-27b deferred. Green: full hub build/vet/test (17 ok) + bash -n + hub confirm gate. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017qDiBqKKQ5vPB5fXBqu7Kp
This commit is contained in:
@@ -10,6 +10,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.dooplex.hu/admin/felhom-hub/internal/configgen"
|
||||
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
|
||||
)
|
||||
|
||||
@@ -28,6 +29,7 @@ type applianceRow struct {
|
||||
CPU string
|
||||
MemGB string
|
||||
SSHFingerprints []string
|
||||
PairingCode string // v0.66.0 (R-27): the code the customer reads off the box console + types on /bind
|
||||
FirstSeen *time.Time
|
||||
LastSeen *time.Time
|
||||
Stale bool
|
||||
@@ -61,9 +63,10 @@ func sshFingerprint(line string) string {
|
||||
// applianceToRow builds the view model (parses hw_summary + computes SSH fingerprints).
|
||||
func applianceToRow(a store.ApplianceRegistration, now time.Time, customerName func(string) string) applianceRow {
|
||||
row := applianceRow{
|
||||
ID: a.ID,
|
||||
UUID: a.UUID,
|
||||
Bound: a.Status == store.ApplianceBound,
|
||||
ID: a.ID,
|
||||
UUID: a.UUID,
|
||||
PairingCode: configgen.FormatPairingCode(a.PairingCode),
|
||||
Bound: a.Status == store.ApplianceBound,
|
||||
}
|
||||
if a.MACSet != "" {
|
||||
row.MACs = strings.Split(a.MACSet, ",")
|
||||
|
||||
@@ -17,7 +17,7 @@ func seedAppliance(t *testing.T, st *store.Store, uuid, macSet string) int64 {
|
||||
// a real ed25519 host key line so the fingerprint helper has something to parse
|
||||
sshKey := "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHVBv+9slP74+1/vNhiI0OJDrXQ2nvb8iwmIxMfUZn36 host"
|
||||
hw := `{"product":"Intel N100 mini","cpu":"Intel(R) N100","mem_kb":16150372}`
|
||||
if _, err := st.RegisterAppliance(uuid, macSet, sshKey, hw, "hash-"+uuid); err != nil {
|
||||
if _, _, err := st.RegisterAppliance(uuid, macSet, sshKey, hw, "hash-"+uuid, "ABCDEF"); err != nil {
|
||||
t.Fatalf("register appliance: %v", err)
|
||||
}
|
||||
list, err := st.ListUnclaimedAppliances()
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.dooplex.hu/admin/felhom-hub/internal/configgen"
|
||||
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
|
||||
)
|
||||
|
||||
// selfbind.go — the CUSTOMER side of self-bind (v0.66.0, R-27 slice 1): the PUBLIC /bind/<token> page.
|
||||
// A logged-out customer opens the emailed capability link and binds their own freshly-installed
|
||||
// appliance by proving TWO factors — the console pairing code (physical possession of the box) and
|
||||
// their retrieval passphrase (customer identity). No hub login exists; the URL token IS the auth.
|
||||
//
|
||||
// THE TRAP (spec §9.2): /bind/ is the ONE new public prefix, exempted from operator auth + CSRF at
|
||||
// the two gate sites the /login exemption occupies. isPublicBindPath is the SINGLE definition of that
|
||||
// prefix — both gate sites and the route dispatch call it, so widening it is one visible change (and
|
||||
// the red-proof targets exactly this function). It is matched TIGHTLY (trailing slash → no sibling
|
||||
// prefix like /bindsecret; the ServeMux cleans .. before we see the path → no traversal reach).
|
||||
//
|
||||
// No-oracle rules on this surface: the page NEVER renders/enumerates any appliance data; a wrong code
|
||||
// and a wrong passphrase produce ONE identical generic failure; both factors are compared
|
||||
// unconditionally before the decision; and only attempt COUNTS are logged (never the secrets, never
|
||||
// the raw token — a hash prefix at most).
|
||||
|
||||
// isPublicBindPath reports whether a path is the public customer self-bind surface. THE single
|
||||
// definition of the /bind/ public prefix (THE TRAP §9.2) — do not inline a second copy anywhere.
|
||||
func isPublicBindPath(path string) bool {
|
||||
return strings.HasPrefix(path, "/bind/")
|
||||
}
|
||||
|
||||
// --- per-IP rate limiter (web-package sibling of api.ipRateLimiter; the type there is unexported) ---
|
||||
|
||||
type bindBucket struct {
|
||||
tokens float64
|
||||
last time.Time
|
||||
}
|
||||
|
||||
type bindRateLimiter struct {
|
||||
mu sync.Mutex
|
||||
perMinute float64
|
||||
buckets map[string]*bindBucket
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func newBindRateLimiter(perMinute int) *bindRateLimiter {
|
||||
if perMinute <= 0 {
|
||||
perMinute = 30
|
||||
}
|
||||
return &bindRateLimiter{perMinute: float64(perMinute), buckets: make(map[string]*bindBucket), now: time.Now}
|
||||
}
|
||||
|
||||
func (rl *bindRateLimiter) allow(ip string) bool {
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
now := rl.now()
|
||||
b, ok := rl.buckets[ip]
|
||||
if !ok {
|
||||
rl.buckets[ip] = &bindBucket{tokens: rl.perMinute - 1, last: now}
|
||||
return true
|
||||
}
|
||||
b.tokens += now.Sub(b.last).Seconds() * (rl.perMinute / 60.0)
|
||||
if b.tokens > rl.perMinute {
|
||||
b.tokens = rl.perMinute
|
||||
}
|
||||
b.last = now
|
||||
if b.tokens < 1 {
|
||||
return false
|
||||
}
|
||||
b.tokens--
|
||||
return true
|
||||
}
|
||||
|
||||
// bindClientIP extracts the client IP behind the ingress (first XFF hop, else RemoteAddr) — buckets
|
||||
// only; the ingress geo-gate is the real access control.
|
||||
func bindClientIP(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
if i := strings.IndexByte(xff, ','); i > 0 {
|
||||
return strings.TrimSpace(xff[:i])
|
||||
}
|
||||
return strings.TrimSpace(xff)
|
||||
}
|
||||
if i := strings.LastIndexByte(r.RemoteAddr, ':'); i > 0 {
|
||||
return r.RemoteAddr[:i]
|
||||
}
|
||||
return r.RemoteAddr
|
||||
}
|
||||
|
||||
// --- the page ---
|
||||
|
||||
type bindPageData struct {
|
||||
State string // "form" | "success" | "expired" | "consumed" | "locked"
|
||||
Token string // echoed into the form action (the capability itself; already in the URL)
|
||||
Failed bool // generic factor-check failure (form state only)
|
||||
}
|
||||
|
||||
var bindTemplate = template.Must(template.New("bind").Parse(bindPageHTML))
|
||||
|
||||
func (s *Server) renderBind(w http.ResponseWriter, status int, data bindPageData) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
if err := bindTemplate.Execute(w, data); err != nil {
|
||||
s.logger.Printf("[ERROR] rendering /bind page: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// handleBind serves the public self-bind page. GET renders the current link state; POST validates
|
||||
// both factors and, on success, stages the bind (same BindAppliance the operator uses; provenance =
|
||||
// customer self-bind). Reached only via isPublicBindPath — auth + CSRF exempt at the gate sites.
|
||||
func (s *Server) handleBind(w http.ResponseWriter, r *http.Request) {
|
||||
if s.bindLimiter != nil && !s.bindLimiter.allow(bindClientIP(r)) {
|
||||
s.renderBind(w, http.StatusTooManyRequests, bindPageData{State: "expired"})
|
||||
return
|
||||
}
|
||||
token := strings.TrimPrefix(r.URL.Path, "/bind/")
|
||||
// A trailing segment only — reject anything with further path structure (defence in depth atop
|
||||
// the ServeMux path-clean; the token is a flat hex string).
|
||||
if token == "" || strings.Contains(token, "/") {
|
||||
s.renderBind(w, http.StatusNotFound, bindPageData{State: "expired"})
|
||||
return
|
||||
}
|
||||
hash := selfBindHash(token)
|
||||
tok, err := s.store.SelfBindTokenByHash(hash)
|
||||
if err != nil {
|
||||
s.logger.Printf("[ERROR] /bind lookup failed: %v", err)
|
||||
http.Error(w, "Internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
|
||||
// Terminal link states — identical for GET and POST, no factor check attempted. An unknown token
|
||||
// (nil) is folded into "expired": no oracle for "was this link ever real".
|
||||
switch {
|
||||
case tok == nil || tok.Expired(now):
|
||||
s.renderBind(w, http.StatusOK, bindPageData{State: "expired"})
|
||||
return
|
||||
case tok.Consumed():
|
||||
s.renderBind(w, http.StatusOK, bindPageData{State: "consumed"})
|
||||
return
|
||||
case tok.Locked:
|
||||
s.renderBind(w, http.StatusOK, bindPageData{State: "locked"})
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
s.renderBind(w, http.StatusOK, bindPageData{State: "form", Token: token})
|
||||
return
|
||||
}
|
||||
|
||||
// --- POST: validate BOTH factors unconditionally, then decide (no oracle) ---
|
||||
normCode := configgen.NormalizePairingCode(r.FormValue("pairing_code"))
|
||||
normPass := configgen.NormalizePassphrase(r.FormValue("passphrase"))
|
||||
|
||||
// Factor 2 (passphrase) — the customer's retrieval passphrase, constant-time compared. Computed
|
||||
// even when the customer/appliance is absent so the two paths are indistinguishable by timing.
|
||||
var storedPass string
|
||||
if cc, cerr := s.store.GetCustomerConfig(tok.CustomerID); cerr == nil && cc != nil {
|
||||
storedPass = configgen.NormalizePassphrase(cc.RetrievalPassword)
|
||||
}
|
||||
passOK := storedPass != "" && subtle.ConstantTimeCompare([]byte(normPass), []byte(storedPass)) == 1
|
||||
|
||||
// Factor 1 (pairing code) — the ONE bindable appliance carrying that console code.
|
||||
appliance, aerr := s.store.ApplianceByPairingCode(normCode)
|
||||
if aerr != nil {
|
||||
s.logger.Printf("[ERROR] /bind appliance lookup failed: %v", aerr)
|
||||
http.Error(w, "Internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
codeOK := appliance != nil
|
||||
|
||||
if !codeOK || !passOK {
|
||||
attempts, locked, rerr := s.store.RecordSelfBindAttempt(hash)
|
||||
if rerr != nil {
|
||||
s.logger.Printf("[ERROR] /bind recording attempt: %v", rerr)
|
||||
}
|
||||
// COUNTS only — never which factor failed, never the secrets, never the raw token.
|
||||
s.logger.Printf("[WARN] self-bind attempt %d/%d failed for token %s… (customer %s)", attempts, store.SelfBindMaxAttempts, hash[:8], tok.CustomerID)
|
||||
if locked {
|
||||
s.renderBind(w, http.StatusOK, bindPageData{State: "locked"})
|
||||
return
|
||||
}
|
||||
s.renderBind(w, http.StatusOK, bindPageData{State: "form", Token: token, Failed: true})
|
||||
return
|
||||
}
|
||||
|
||||
// Both factors passed. Consume one-shot FIRST (atomic gate against a double-bind race).
|
||||
consumed, cerr := s.store.ConsumeSelfBindToken(hash)
|
||||
if cerr != nil {
|
||||
s.logger.Printf("[ERROR] /bind consuming token: %v", cerr)
|
||||
http.Error(w, "Internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !consumed {
|
||||
// Lost the race (a concurrent request consumed it) — it is already being bound.
|
||||
s.renderBind(w, http.StatusOK, bindPageData{State: "consumed"})
|
||||
return
|
||||
}
|
||||
if err := s.store.BindAppliance(appliance.ID, tok.CustomerID, "appliance", ""); err != nil {
|
||||
// Rare: the appliance became unbindable (operator discarded it) between lookup and bind. The
|
||||
// token is spent; surface a neutral generic failure rather than an appliance-state oracle.
|
||||
s.logger.Printf("[WARN] self-bind: BindAppliance %d → %s failed after factor match: %v", appliance.ID, tok.CustomerID, err)
|
||||
s.renderBind(w, http.StatusOK, bindPageData{State: "form", Failed: true})
|
||||
return
|
||||
}
|
||||
if _, err := s.store.SaveEvent(tok.CustomerID, "appliance_bound", "info",
|
||||
"Az ügyfél saját maga kötötte össze az új eszközt (bare-metal telepítés); a hozzáférést a doboz a következő lekérdezéskor megkapja.", "", "customer_selfbind"); err != nil {
|
||||
s.logger.Printf("[WARN] self-bind: save event for %s: %v", tok.CustomerID, err)
|
||||
}
|
||||
s.logger.Printf("[INFO] self-bind SUCCESS: appliance %d bound to customer %s by customer self-service (token %s…)", appliance.ID, tok.CustomerID, hash[:8])
|
||||
s.renderBind(w, http.StatusOK, bindPageData{State: "success"})
|
||||
}
|
||||
|
||||
// bindPageHTML is the self-contained public page. It CANNOT link /style.css (that route is
|
||||
// operator-auth gated), so all styling is inline — mirroring the login page. Design tokens: navy
|
||||
// surface, 2px radius, hairline rules, exception color for the failure banner. Hungarian, adult tone,
|
||||
// no emoji. It renders NO appliance data in any state.
|
||||
const bindPageHTML = `<!DOCTYPE html>
|
||||
<html lang="hu">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>Felhom — Doboz összekötése</title>
|
||||
<style>
|
||||
:root { --navy:#0A2540; --ink:#0A2540; --muted:#5b6b7d; --line:#d8e0e8; --brand:#0083D8; --exc:#c0392b; --bg:#f4f7fa; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin:0; font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif; background:var(--bg); color:var(--ink); line-height:1.5; }
|
||||
.wrap { max-width:460px; margin:3rem auto; padding:0 1rem; }
|
||||
.card { background:#fff; border:1px solid var(--line); border-radius:2px; padding:1.75rem; }
|
||||
h1 { font-size:1.25rem; margin:0 0 .25rem; color:var(--navy); }
|
||||
h1 span { color:var(--brand); }
|
||||
.lead { color:var(--muted); font-size:.92rem; margin:.25rem 0 1.25rem; }
|
||||
label { display:block; font-weight:600; font-size:.9rem; margin:1rem 0 .35rem; }
|
||||
.hint { color:var(--muted); font-size:.8rem; margin:.15rem 0 0; }
|
||||
input[type=text] { width:100%; padding:.6rem .7rem; border:1px solid var(--line); border-radius:2px; font-size:1rem; }
|
||||
input.code { text-transform:uppercase; letter-spacing:.12em; font-family:ui-monospace,SFMono-Regular,Menlo,monospace; }
|
||||
button { margin-top:1.5rem; width:100%; padding:.7rem; background:var(--brand); color:#fff; border:none; border-radius:2px; font-size:1rem; cursor:pointer; }
|
||||
button:hover { background:#006cb0; }
|
||||
.banner { border:1px solid var(--exc); color:var(--exc); background:#fbeae8; border-radius:2px; padding:.6rem .75rem; font-size:.88rem; margin:0 0 1rem; }
|
||||
.note { border-top:1px solid var(--line); margin-top:1.5rem; padding-top:1rem; color:var(--muted); font-size:.82rem; }
|
||||
.foot { text-align:center; color:var(--muted); font-size:.75rem; margin-top:1.25rem; }
|
||||
.ok { color:#1e7e34; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<div class="card">
|
||||
<h1>Felhom <span>doboz</span> összekötése</h1>
|
||||
{{if eq .State "form"}}
|
||||
<p class="lead">Kösd össze a most telepített Felhom dobozodat a fiókoddal. Add meg a doboz képernyőjén látható párosító kódot és a visszaállító jelszavadat.</p>
|
||||
{{if .Failed}}<div class="banner">A megadott adatok nem megfelelőek. Ellenőrizd a párosító kódot és a jelszót, majd próbáld újra.</div>{{end}}
|
||||
<form method="POST" action="/bind/{{.Token}}">
|
||||
<label for="pairing_code">Párosító kód</label>
|
||||
<input class="code" type="text" id="pairing_code" name="pairing_code" autocomplete="off" autocapitalize="characters" spellcheck="false" required autofocus placeholder="ABC-234">
|
||||
<p class="hint">A doboz monitorán jelenik meg, a telepítés után.</p>
|
||||
<label for="passphrase">Visszaállító jelszó</label>
|
||||
<input type="text" id="passphrase" name="passphrase" autocomplete="off" spellcheck="false" required placeholder="öt szó, kötőjellel vagy szóközzel">
|
||||
<p class="hint">Az öt szóból álló kifejezés, amelyet a beállításkor kaptál.</p>
|
||||
<button type="submit">Összekötés</button>
|
||||
</form>
|
||||
<p class="note">Biztonsági okból 5 sikertelen próbálkozás után a hivatkozás zárolódik. Ilyenkor vedd fel a kapcsolatot az ügyfélszolgálattal.</p>
|
||||
{{else if eq .State "success"}}
|
||||
<p class="lead ok">Sikeres összekötés.</p>
|
||||
<p>A doboz kb. egy percen belül folytatja a telepítést. Ezt az oldalt bezárhatod — a beállítás a háttérben befejeződik, és a vezérlőpultod hamarosan elérhető lesz.</p>
|
||||
{{else if eq .State "consumed"}}
|
||||
<p class="lead">Ez a hivatkozás már fel lett használva.</p>
|
||||
<p>A doboz összekötése megtörtént. Ha úgy gondolod, hogy ez tévedés, vedd fel a kapcsolatot az ügyfélszolgálattal.</p>
|
||||
{{else if eq .State "locked"}}
|
||||
<p class="lead">Ez a hivatkozás zárolva van.</p>
|
||||
<p>Túl sok sikertelen próbálkozás történt. Biztonsági okból a hivatkozás zárolódott — kérjük, vedd fel a kapcsolatot az ügyfélszolgálattal a doboz összekötéséhez.</p>
|
||||
{{else}}
|
||||
<p class="lead">Ez a hivatkozás érvénytelen vagy lejárt.</p>
|
||||
<p>A hivatkozás 7 napig érvényes. Ha lejárt, kérj újat az ügyfélszolgálattól, vagy az összekötést az üzemeltető is elvégezheti.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
<p class="foot">Felhom.eu</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>`
|
||||
@@ -0,0 +1,94 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"gitea.dooplex.hu/admin/felhom-hub/internal/configgen"
|
||||
)
|
||||
|
||||
// selfbind_mint.go — the OPERATOR side of customer self-bind (v0.66.0, R-27 slice 1): the "Send
|
||||
// self-bind link" button on the customer page mints a 7-day capability token and emails the customer
|
||||
// a public bind link. The customer side (the public /bind/ page) lives in selfbind.go. No hub
|
||||
// customer-login exists — the emailed link IS the auth model.
|
||||
|
||||
// selfBindTTL is the capability link's lifetime. After it, self-bind falls back to operator-bind
|
||||
// unchanged (the token simply reads as expired; nothing else regresses).
|
||||
const selfBindTTL = 7 * 24 * time.Hour
|
||||
|
||||
// selfBindBaseURL is the hub's public origin, matching the hardcoded origin used elsewhere
|
||||
// (configgen). The link is https://hub.felhom.eu/bind/<token>.
|
||||
const selfBindBaseURL = "https://hub.felhom.eu"
|
||||
|
||||
// SelfBindMailer delivers the self-bind capability link to the registered customer address. The
|
||||
// notify.Dispatcher implements it (a sibling of the claim mailer — NOT routed through claim). The
|
||||
// signature takes plain strings so the implementation needs no import of this package.
|
||||
type SelfBindMailer interface {
|
||||
SendSelfBindEmail(customerID, email, link string) error
|
||||
}
|
||||
|
||||
// SetSelfBindMailer wires the self-bind link sender (v0.66.0). Absent → the button returns 502.
|
||||
func (s *Server) SetSelfBindMailer(m SelfBindMailer) { s.selfBindMailer = m }
|
||||
|
||||
func selfBindHash(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// handleSelfBindLinkSend — POST /customers/{id}/selfbind-link. Mints a single-active capability token
|
||||
// for the customer and emails the public bind link. Honesty rules:
|
||||
// - F1: no registered email → nothing is minted, LOUD flash (a link no one can receive is useless).
|
||||
// - F2: email send fails → the just-minted token is deleted (not left silently live), LOUD flash.
|
||||
//
|
||||
// The plaintext token exists only between minting and the send; it is never logged (only an 8-char
|
||||
// hash prefix) and never persisted (only its sha256).
|
||||
func (s *Server) handleSelfBindLinkSend(w http.ResponseWriter, r *http.Request, customerID string) {
|
||||
if s.selfBindMailer == nil {
|
||||
http.Error(w, "Self-bind mailer is not configured on this hub", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
cfg, err := s.store.GetCustomerConfig(customerID)
|
||||
if err != nil || cfg == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
// F1: refuse to mint a link that cannot be delivered.
|
||||
if cfg.Email == "" {
|
||||
s.logger.Printf("[WARN] self-bind link for %s NOT sent: customer has no registered email", customerID)
|
||||
http.Redirect(w, r, "/customers/"+customerID+"?flash=selfbind-no-email#tab=setup", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
token, err := configgen.RandomHex(32) // 256-bit capability token
|
||||
if err != nil {
|
||||
s.logger.Printf("[ERROR] self-bind link for %s: token generation: %v", customerID, err)
|
||||
http.Error(w, "Internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
hash := selfBindHash(token)
|
||||
if err := s.store.MintSelfBindToken(customerID, hash, selfBindTTL); err != nil {
|
||||
s.logger.Printf("[ERROR] self-bind link for %s: minting token: %v", customerID, err)
|
||||
http.Error(w, "Internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
link := selfBindBaseURL + "/bind/" + token
|
||||
if err := s.selfBindMailer.SendSelfBindEmail(customerID, cfg.Email, link); err != nil {
|
||||
// F2: delivery failed — do not leave a live capability token behind (the plaintext link is
|
||||
// already gone from memory, so nobody could ever use it; delete it and surface the failure).
|
||||
if derr := s.store.DeleteSelfBindTokens(customerID); derr != nil {
|
||||
s.logger.Printf("[ERROR] self-bind link for %s: send failed AND cleanup failed: send=%v cleanup=%v", customerID, err, derr)
|
||||
} else {
|
||||
s.logger.Printf("[ERROR] self-bind link for %s: email send failed, token invalidated (hash %s…): %v", customerID, hash[:8], err)
|
||||
}
|
||||
http.Redirect(w, r, "/customers/"+customerID+"?flash=selfbind-send-failed#tab=setup", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
if err := s.store.MarkSelfBindEmailed(hash); err != nil {
|
||||
s.logger.Printf("[WARN] self-bind link sent to %s but emailed_at not recorded: %v", customerID, err)
|
||||
}
|
||||
s.logger.Printf("[INFO] self-bind link (hash %s…, valid 7 days) emailed to the registered address of %s", hash[:8], customerID)
|
||||
http.Redirect(w, r, "/customers/"+customerID+"?flash=selfbind-sent#tab=setup", http.StatusSeeOther)
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
|
||||
)
|
||||
|
||||
// selfbind_test.go — customer self-bind (v0.66.0, R-27 slice 1), Scenarios A–F.
|
||||
//
|
||||
// Each red-proof below names the ONE line to break to turn a scenario red — the guard that the test
|
||||
// actually pins. If a red-proof does NOT turn its scenario red, the test is hollow.
|
||||
|
||||
const (
|
||||
testPass = "alpha beta gamma delta epsilon" // the customer retrieval passphrase (5 words)
|
||||
testCode = "ABC234" // an appliance console pairing code (raw stored form)
|
||||
testCodeFmt = "abc-234" // as a human might type it (lowercased, separated)
|
||||
)
|
||||
|
||||
// selfBindSetup seeds a customer (with passphrase + email) and one registered appliance carrying the
|
||||
// given console pairing code, and returns the appliance id. Distinct customers must use distinct
|
||||
// codes (a code shared by two registered appliances is ambiguous → binds nothing).
|
||||
func selfBindSetup(t *testing.T, st *store.Store, customerID, code string) int64 {
|
||||
t.Helper()
|
||||
if err := st.SaveCustomerConfig(&store.CustomerConfig{
|
||||
CustomerID: customerID, CustomerName: customerID, APIKey: "k",
|
||||
RetrievalPassword: testPass, Email: customerID + "@example.test",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sshKey := "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHVBv+9slP74+1/vNhiI0OJDrXQ2nvb8iwmIxMfUZn36 host"
|
||||
if _, _, err := st.RegisterAppliance("uuid-"+customerID, "bc:24:11:98:10:0e", sshKey, `{"product":"N100"}`, "aphash-"+customerID, code); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
list, _ := st.ListUnclaimedAppliances()
|
||||
for _, a := range list {
|
||||
if a.UUID == "uuid-"+customerID {
|
||||
return a.ID
|
||||
}
|
||||
}
|
||||
t.Fatal("seeded appliance not found")
|
||||
return 0
|
||||
}
|
||||
|
||||
// mintLink mints a self-bind token for the customer and returns the plaintext token (URL segment).
|
||||
// Each call uses a fresh nonce so distinct calls yield distinct tokens (single-active still applies —
|
||||
// the store deletes the prior row for the customer on each mint).
|
||||
var mintNonce int
|
||||
|
||||
func mintLink(t *testing.T, st *store.Store, customerID string, ttl time.Duration) string {
|
||||
t.Helper()
|
||||
mintNonce++
|
||||
token := "tok-" + customerID + "-" + string(rune('a'+mintNonce%26)) + strconv.Itoa(mintNonce)
|
||||
if err := st.MintSelfBindToken(customerID, selfBindHash(token), ttl); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func bindGET(t *testing.T, s *Server, token string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
rr := httptest.NewRecorder()
|
||||
s.handleBind(rr, httptest.NewRequest("GET", "/bind/"+token, nil))
|
||||
return rr
|
||||
}
|
||||
|
||||
func bindPOST(t *testing.T, s *Server, token, code, pass string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
form := url.Values{"pairing_code": {code}, "passphrase": {pass}}
|
||||
req := httptest.NewRequest("POST", "/bind/"+token, strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
rr := httptest.NewRecorder()
|
||||
s.handleBind(rr, req)
|
||||
return rr
|
||||
}
|
||||
|
||||
// --- Scenario A: happy path (GET renders form; POST with both correct factors stages the bind) ---
|
||||
func TestSelfBind_A_HappyPath(t *testing.T) {
|
||||
s, st := newTestServer(t)
|
||||
id := selfBindSetup(t, st, "acme", testCode)
|
||||
token := mintLink(t, st, "acme", selfBindTTL)
|
||||
|
||||
if body := bindGET(t, s, token).Body.String(); !strings.Contains(body, "Párosító kód") || !strings.Contains(body, "action=\"/bind/"+token+"\"") {
|
||||
t.Fatalf("GET did not render the entry form")
|
||||
}
|
||||
// A human types the code lowercased + separated and the passphrase with odd spacing — normalization
|
||||
// must accept both.
|
||||
rr := bindPOST(t, s, token, testCodeFmt, " Alpha Beta gamma-delta epsilon ")
|
||||
if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), "egy percen belül") {
|
||||
t.Fatalf("POST success page not rendered: code=%d body=%q", rr.Code, rr.Body.String())
|
||||
}
|
||||
// The appliance is bound to the customer (same effect as an operator bind).
|
||||
if a, _ := st.GetAppliance(id); a == nil || a.Status != store.ApplianceBound || a.CustomerID != "acme" {
|
||||
t.Fatalf("appliance not bound: %+v", a)
|
||||
}
|
||||
// Provenance event is customer self-bind, not operator/hub.
|
||||
ev, _ := st.GetLatestEventByType("acme", "appliance_bound")
|
||||
if ev == nil || ev.Source != "customer_selfbind" {
|
||||
t.Fatalf("expected customer_selfbind provenance event, got %+v", ev)
|
||||
}
|
||||
// One-shot: the token is now consumed; a second open shows the consumed state.
|
||||
if body := bindGET(t, s, token).Body.String(); !strings.Contains(body, "már fel lett használva") {
|
||||
t.Fatalf("token not consumed after success")
|
||||
}
|
||||
// Red-proof: drop the ConsumeSelfBindToken call (or make BindAppliance the only effect) → the
|
||||
// token stays live and this consumed-state assertion goes red.
|
||||
}
|
||||
|
||||
// --- Scenario B: NO ORACLE — wrong code and wrong passphrase yield the SAME generic failure ---
|
||||
func TestSelfBind_B_NoOracle(t *testing.T) {
|
||||
s, st := newTestServer(t)
|
||||
// Two customers with DISTINCT pairing codes so the single-active mint does not cross-invalidate,
|
||||
// and each has one fresh (attempt-count 1) token — the only difference between the two failure
|
||||
// pages is then the token in the form action, which we normalize out.
|
||||
selfBindSetup(t, st, "acme", testCode)
|
||||
selfBindSetup(t, st, "acme2", "XYZ789")
|
||||
|
||||
t1 := mintLink(t, st, "acme", selfBindTTL) // wrong-code attempt (right passphrase)
|
||||
t2 := mintLink(t, st, "acme2", selfBindTTL) // wrong-passphrase attempt (right code)
|
||||
wrongCode := strings.ReplaceAll(bindPOST(t, s, t1, "ZZZ999", testPass).Body.String(), t1, "TOKEN")
|
||||
wrongPass := strings.ReplaceAll(bindPOST(t, s, t2, "xyz-789", "wrong words here now").Body.String(), t2, "TOKEN")
|
||||
|
||||
if wrongCode != wrongPass {
|
||||
t.Fatalf("failure pages differ between wrong-code and wrong-passphrase — that is an oracle")
|
||||
}
|
||||
// The generic failure must not leak any appliance data.
|
||||
if !strings.Contains(wrongCode, "nem megfelelőek") {
|
||||
t.Fatalf("failure page missing the generic banner: %q", wrongCode)
|
||||
}
|
||||
if strings.Contains(wrongCode, "uuid-") || strings.Contains(wrongCode, "N100") {
|
||||
t.Fatalf("failure page leaked appliance data")
|
||||
}
|
||||
// Red-proof: give wrong-code and wrong-passphrase distinct messages/states (an oracle) → the
|
||||
// wrongCode == wrongPass assertion goes red.
|
||||
}
|
||||
|
||||
// --- Scenario C1: LOCKOUT after 5 failed attempts; a subsequent CORRECT attempt cannot bind ---
|
||||
func TestSelfBind_C1_Lockout(t *testing.T) {
|
||||
s, st := newTestServer(t)
|
||||
id := selfBindSetup(t, st, "acme", testCode)
|
||||
token := mintLink(t, st, "acme", selfBindTTL)
|
||||
|
||||
for i := 1; i <= store.SelfBindMaxAttempts; i++ {
|
||||
rr := bindPOST(t, s, token, "ZZZ999", "definitely wrong words indeed")
|
||||
if i < store.SelfBindMaxAttempts && !strings.Contains(rr.Body.String(), "nem megfelelőek") {
|
||||
t.Fatalf("attempt %d should re-render the form with a failure, got %q", i, rr.Body.String())
|
||||
}
|
||||
}
|
||||
// The 5th failure locked it: even the CORRECT secrets now bind nothing.
|
||||
rr := bindPOST(t, s, token, testCodeFmt, testPass)
|
||||
if !strings.Contains(rr.Body.String(), "zárolva") {
|
||||
t.Fatalf("token not locked after %d failures: %q", store.SelfBindMaxAttempts, rr.Body.String())
|
||||
}
|
||||
if a, _ := st.GetAppliance(id); a.Status != store.ApplianceRegistered {
|
||||
t.Fatalf("a locked link still bound the appliance: %+v", a)
|
||||
}
|
||||
// Red-proof: remove the `locked = attempts >= SelfBindMaxAttempts` lock (never lock) → the correct
|
||||
// post-lockout POST binds and both the "zárolva" and still-registered assertions go red.
|
||||
}
|
||||
|
||||
// --- Scenario C4: SINGLE-ACTIVE per customer — re-minting kills the prior link ---
|
||||
func TestSelfBind_C4_SingleActive(t *testing.T) {
|
||||
s, st := newTestServer(t)
|
||||
selfBindSetup(t, st, "acme", testCode)
|
||||
|
||||
first := mintLink(t, st, "acme", selfBindTTL)
|
||||
second := mintLink(t, st, "acme", selfBindTTL) // re-mint for the SAME customer
|
||||
|
||||
if body := bindGET(t, s, first).Body.String(); !strings.Contains(body, "érvénytelen vagy lejárt") {
|
||||
t.Fatalf("the first link still resolves after a re-mint (not single-active): %q", body)
|
||||
}
|
||||
if body := bindGET(t, s, second).Body.String(); !strings.Contains(body, "Párosító kód") {
|
||||
t.Fatalf("the freshly-minted link does not render the form: %q", body)
|
||||
}
|
||||
// Red-proof: drop the `DELETE FROM selfbind_tokens WHERE customer_id` in MintSelfBindToken → the
|
||||
// first link still resolves and the érvénytelen assertion goes red.
|
||||
}
|
||||
|
||||
// --- Scenario D: the operator auth gate is intact — self-bind's exemption did NOT open other routes ---
|
||||
func TestSelfBind_D_AuthGateIntact(t *testing.T) {
|
||||
s, st := newAuthServer(t)
|
||||
selfBindSetup(t, st, "acme", testCode)
|
||||
h := s.RequireAuth(http.HandlerFunc(s.ServeHTTP))
|
||||
|
||||
for _, path := range []string{"/", "/hosts", "/customers/acme", "/configuration", "/offsite"} {
|
||||
rr := httptest.NewRecorder()
|
||||
h.ServeHTTP(rr, httptest.NewRequest("GET", path, nil))
|
||||
if rr.Code != http.StatusFound || rr.Header().Get("Location") != "/login" {
|
||||
t.Fatalf("gated route %s not redirected to /login: code=%d loc=%q", path, rr.Code, rr.Header().Get("Location"))
|
||||
}
|
||||
}
|
||||
// Red-proof: this is the companion to Scenario E — widening isPublicBindPath turns THIS red too.
|
||||
}
|
||||
|
||||
// --- Scenario E: THE TRAP — /bind/ is exempt from operator auth, matched TIGHTLY (no leak/traversal) ---
|
||||
func TestSelfBind_E_TheTrap(t *testing.T) {
|
||||
s, st := newAuthServer(t)
|
||||
selfBindSetup(t, st, "acme", testCode)
|
||||
token := mintLink(t, st, "acme", selfBindTTL)
|
||||
h := s.RequireAuth(http.HandlerFunc(s.ServeHTTP))
|
||||
|
||||
// The public bind link renders WITHOUT a login (the exemption works).
|
||||
rr := httptest.NewRecorder()
|
||||
h.ServeHTTP(rr, httptest.NewRequest("GET", "/bind/"+token, nil))
|
||||
if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), "Párosító kód") {
|
||||
t.Fatalf("public /bind/ link was gated or not rendered: code=%d", rr.Code)
|
||||
}
|
||||
|
||||
// A sibling prefix must NOT be exempt: /bindsecret is still gated (tight trailing-slash match).
|
||||
rr = httptest.NewRecorder()
|
||||
h.ServeHTTP(rr, httptest.NewRequest("GET", "/bindsecret", nil))
|
||||
if rr.Code != http.StatusFound {
|
||||
t.Fatalf("/bindsecret leaked through the exemption (prefix not tight): code=%d", rr.Code)
|
||||
}
|
||||
|
||||
// Traversal through the exempt prefix must not reach a gated handler: it stays inside handleBind,
|
||||
// which rejects a token containing '/', never touching /hosts.
|
||||
rr = httptest.NewRecorder()
|
||||
h.ServeHTTP(rr, httptest.NewRequest("GET", "/bind/../hosts", nil))
|
||||
if strings.Contains(rr.Body.String(), "Unclaimed appliances") || strings.Contains(rr.Body.String(), "No hosts enrolled") {
|
||||
t.Fatalf("path traversal through /bind/ reached the hosts page")
|
||||
}
|
||||
// Red-proof: widen isPublicBindPath to strings.HasPrefix(path, "/bind") (drop the slash) → the
|
||||
// /bindsecret gated assertion goes red; broaden it further and Scenario D goes red too.
|
||||
}
|
||||
|
||||
// --- Scenario F: EXPIRY falls back — an expired link binds nothing, even with correct factors ---
|
||||
func TestSelfBind_F_ExpiryFallsBack(t *testing.T) {
|
||||
s, st := newTestServer(t)
|
||||
id := selfBindSetup(t, st, "acme", testCode)
|
||||
token := mintLink(t, st, "acme", -1*time.Hour) // already expired
|
||||
|
||||
if body := bindGET(t, s, token).Body.String(); !strings.Contains(body, "érvénytelen vagy lejárt") {
|
||||
t.Fatalf("expired link did not render the expired state")
|
||||
}
|
||||
// Even the CORRECT secrets on an expired link bind nothing (operator-bind fallback is unchanged).
|
||||
bindPOST(t, s, token, testCodeFmt, testPass)
|
||||
if a, _ := st.GetAppliance(id); a.Status != store.ApplianceRegistered {
|
||||
t.Fatalf("an expired link still bound the appliance: %+v", a)
|
||||
}
|
||||
// Red-proof: drop the `expires_at > datetime('now')` guard in ConsumeSelfBindToken AND the
|
||||
// tok.Expired() gate → the expired POST binds and the still-registered assertion goes red.
|
||||
}
|
||||
|
||||
// --- Scenario (F1/F2): the operator MINT honesty paths ---
|
||||
|
||||
// F1: a customer with no registered email → nothing minted, LOUD flash.
|
||||
func TestSelfBind_MintNoEmail(t *testing.T) {
|
||||
s, st := newTestServer(t)
|
||||
if err := st.SaveCustomerConfig(&store.CustomerConfig{CustomerID: "noemail", APIKey: "k", RetrievalPassword: testPass}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.SetSelfBindMailer(&stubMailer{})
|
||||
rr := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/customers/noemail/selfbind-link", nil)
|
||||
s.handleSelfBindLinkSend(rr, req, "noemail")
|
||||
if rr.Code != http.StatusSeeOther || !strings.Contains(rr.Header().Get("Location"), "selfbind-no-email") {
|
||||
t.Fatalf("no-email mint should redirect with selfbind-no-email: code=%d loc=%q", rr.Code, rr.Header().Get("Location"))
|
||||
}
|
||||
if tok, _ := st.SelfBindTokenByHash(selfBindHash("x")); tok != nil {
|
||||
t.Fatal("a token was minted despite no email")
|
||||
}
|
||||
}
|
||||
|
||||
// F2: the email send fails → the just-minted token is deleted (not left silently live).
|
||||
func TestSelfBind_MintSendFailsCleansUp(t *testing.T) {
|
||||
s, st := newTestServer(t)
|
||||
selfBindSetup(t, st, "acme", testCode)
|
||||
stub := &stubMailer{fail: true}
|
||||
s.SetSelfBindMailer(stub)
|
||||
rr := httptest.NewRecorder()
|
||||
s.handleSelfBindLinkSend(rr, httptest.NewRequest("POST", "/customers/acme/selfbind-link", nil), "acme")
|
||||
if !strings.Contains(rr.Header().Get("Location"), "selfbind-send-failed") {
|
||||
t.Fatalf("send failure should redirect with selfbind-send-failed: %q", rr.Header().Get("Location"))
|
||||
}
|
||||
// The token that was minted for the (failed) send is gone — not left silently live (F2 cleanup).
|
||||
// Recover the token from the link the mailer was handed, and confirm it no longer resolves.
|
||||
tokenFromLink := stub.link[strings.LastIndexByte(stub.link, '/')+1:]
|
||||
if tokenFromLink == "" {
|
||||
t.Fatal("mailer was never handed a link")
|
||||
}
|
||||
if tok, _ := st.SelfBindTokenByHash(selfBindHash(tokenFromLink)); tok != nil {
|
||||
t.Fatal("a failed send left a live token behind")
|
||||
}
|
||||
}
|
||||
|
||||
// stubMailer records the last send and can be told to fail.
|
||||
type stubMailer struct {
|
||||
fail bool
|
||||
link string
|
||||
}
|
||||
|
||||
func (m *stubMailer) SendSelfBindEmail(customerID, email, link string) error {
|
||||
m.link = link
|
||||
if m.fail {
|
||||
return errStubSend
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var errStubSend = &stubErr{}
|
||||
|
||||
type stubErr struct{}
|
||||
|
||||
func (*stubErr) Error() string { return "stub send failure" }
|
||||
|
||||
// newAuthServer is newTestServer with an operator password configured, so RequireAuth is live.
|
||||
func newAuthServer(t *testing.T) (*Server, *store.Store) {
|
||||
t.Helper()
|
||||
s, st := newTestServer(t)
|
||||
h, err := bcrypt.GenerateFromPassword([]byte("operator-pw"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.configPasswordHash = string(h)
|
||||
return s, st
|
||||
}
|
||||
@@ -71,6 +71,8 @@ type Server struct {
|
||||
pbsdrBox func() (monitor.PBSBoxSnapshot, bool) // optional (v0.65.0, R-5); the PBS-DR datastore fill snapshot accessor
|
||||
tenantsync tenancyProvisioner // optional; enables PBS DR tier provisioning (web/pbsdr.go)
|
||||
claimEngine *claim.Engine // optional; enables the customer-claim resend button (v0.50.0)
|
||||
selfBindMailer SelfBindMailer // optional; enables the customer self-bind link button (v0.66.0, R-27)
|
||||
bindLimiter *bindRateLimiter // per-IP throttle for the PUBLIC /bind/ surface (v0.66.0, R-27)
|
||||
// intentHub (v0.58.0, Direction-2 immediate-sync) is Bumped by every operator-intent handler
|
||||
// (config save/delete, claim resend, offsite re-issue/freeze, floor, block/unblock, log pull)
|
||||
// so a box long-polling GET /api/v1/wait wakes in seconds. Shared with the API handler. nil =
|
||||
@@ -129,6 +131,7 @@ func New(store *store.Store, passwordHash, apiKey, version string, staleThreshol
|
||||
templates: tmpl,
|
||||
staleThreshold: staleThreshold,
|
||||
sessions: make(map[string]*hubSession),
|
||||
bindLimiter: newBindRateLimiter(30), // public /bind/ surface: 30 req/min/IP burst (R-27)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,7 +256,10 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// CSRF protection for all state-changing requests (web routes only).
|
||||
// API routes (/api/v1/) are Bearer-token authenticated and exempt.
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead && r.Method != http.MethodOptions {
|
||||
if path != "/login" && s.effectivePasswordHash() != "" {
|
||||
// /bind/ is the public customer self-bind surface (THE TRAP §9.2): no operator session to
|
||||
// ride, so CSRF is exempt here exactly as it is for /login. The URL capability token is the
|
||||
// authorization boundary; a cross-site POST without both secrets only burns attempts.
|
||||
if path != "/login" && !isPublicBindPath(path) && s.effectivePasswordHash() != "" {
|
||||
if !s.validateCSRF(r) {
|
||||
s.logger.Printf("[WARN] CSRF rejected: %s %s from %s", r.Method, path, r.RemoteAddr)
|
||||
http.Error(w, "CSRF token missing or invalid. Please reload the page.", http.StatusForbidden)
|
||||
@@ -377,6 +383,10 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
s.handleHostDetail(w, r, hostID)
|
||||
case path == "/login":
|
||||
s.handleLogin(w, r)
|
||||
case isPublicBindPath(path):
|
||||
// PUBLIC customer self-bind (R-27 slice 1) — GET renders the form/state, POST validates the
|
||||
// two factors. Auth + CSRF exempt above via the SAME isPublicBindPath predicate.
|
||||
s.handleBind(w, r)
|
||||
case strings.HasPrefix(path, "/customers/") && strings.HasSuffix(path, "/block"):
|
||||
customerID := strings.TrimPrefix(path, "/customers/")
|
||||
customerID = strings.TrimSuffix(customerID, "/block")
|
||||
@@ -385,6 +395,15 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
} else {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
}
|
||||
case strings.HasPrefix(path, "/customers/") && strings.HasSuffix(path, "/selfbind-link"):
|
||||
// R-27 slice 1: mint + email a customer self-bind capability link. POST only.
|
||||
customerID := strings.TrimPrefix(path, "/customers/")
|
||||
customerID = strings.TrimSuffix(customerID, "/selfbind-link")
|
||||
if r.Method == http.MethodPost {
|
||||
s.handleSelfBindLinkSend(w, r, customerID)
|
||||
} else {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
}
|
||||
case strings.HasPrefix(path, "/customers/") && strings.HasSuffix(path, "/unblock"):
|
||||
customerID := strings.TrimPrefix(path, "/customers/")
|
||||
customerID = strings.TrimSuffix(customerID, "/unblock")
|
||||
@@ -561,8 +580,12 @@ func (s *Server) RequireAuth(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
// Always allow the login page through (GET and POST)
|
||||
if r.URL.Path == "/login" {
|
||||
// Always allow the login page through (GET and POST), and the PUBLIC customer self-bind
|
||||
// surface (THE TRAP §9.2): /bind/ is exempt from operator auth exactly as /login is — the
|
||||
// emailed URL capability token IS the auth model there. isPublicBindPath is the SINGLE
|
||||
// definition of the prefix (matched tightly: trailing slash, path already .. -cleaned by the
|
||||
// ServeMux) so this exemption cannot reach any operator-gated route.
|
||||
if r.URL.Path == "/login" || isPublicBindPath(r.URL.Path) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -55,6 +55,9 @@
|
||||
{{else if eq .Flash "log_tail_requested"}}Log tail requested — the controller delivers it on its next report cycle (a few minutes). A customer-visible event line was recorded.
|
||||
{{else if eq .Flash "claim-resent"}}Code re-sent to the registered address. A kód a doboz következő jelentésekor (~15 percen belül) aktiválódik.
|
||||
{{else if eq .Flash "claim-resend-failed"}}Claim code resend FAILED — check the hub log (email delivery / send error).
|
||||
{{else if eq .Flash "selfbind-sent"}}Self-bind link sent to the registered address — valid for 7 days. The customer enters the box's console pairing code + their retrieval passphrase; no operator bind needed.
|
||||
{{else if eq .Flash "selfbind-no-email"}}Self-bind link NOT sent — this customer has no registered email address. Set one first, or bind the appliance manually from the Hosts page.
|
||||
{{else if eq .Flash "selfbind-send-failed"}}Self-bind link send FAILED — the link was invalidated (not left live). Check the hub log (email delivery / send error).
|
||||
{{else if eq .Flash "reset_done"}}Customer RESET complete — every operational trace was destroyed (offsite repo, PBS namespace, DR recipe, claim state, retained escrow custody). Identity and basic config survive; the audit event stream records it.
|
||||
{{end}}
|
||||
</div>
|
||||
@@ -454,6 +457,15 @@
|
||||
<button type="submit" class="btn btn-outline btn-sm" data-confirm="Send a fresh code to the registered address? The previous code stops working immediately (the box activates it on its next report, ~15 min).">{{if .Claim.ClaimedAt}}Visszaállító kód küldése{{else}}Kód újraküldése{{end}}</button>
|
||||
</form>
|
||||
{{end}}
|
||||
|
||||
<div class="form-group" style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid var(--border);">
|
||||
<label class="form-label">Customer self-bind (R-27)</label>
|
||||
<span class="form-hint">Let the customer bind their own freshly-installed appliance — no operator bind needed. Sends a 7-day capability link to the registered address ({{.Email}}); the customer opens it and enters the box's <strong>console pairing code</strong> + their <strong>retrieval passphrase</strong>. Wrong entries lock the link after 5 attempts. If the link expires, bind the appliance manually from the Hosts page.</span>
|
||||
<form method="POST" action="/customers/{{.CustomerID}}/selfbind-link" style="margin-top: 0.5rem;">
|
||||
{{.CSRFField}}
|
||||
<button type="submit" class="btn btn-outline btn-sm" data-confirm="Email a self-bind link to the registered address? Any previous self-bind link for this customer stops working immediately.">Send self-bind link</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
<div style="overflow-x: auto;">
|
||||
<table class="data-table">
|
||||
<thead>
|
||||
<tr><th>Appliance</th><th>MACs</th><th>Hardware</th><th>SSH host keys</th><th>Seen</th><th>Bind to customer</th><th></th></tr>
|
||||
<tr><th>Appliance</th><th>Pairing code</th><th>MACs</th><th>Hardware</th><th>SSH host keys</th><th>Seen</th><th>Bind to customer</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{range .Unclaimed}}
|
||||
@@ -48,6 +48,7 @@
|
||||
{{if .Stale}}<br><span class="status-badge status-warn" title="No poll in over 7 days">stale</span>{{end}}
|
||||
{{if .Bound}}<br><span class="status-badge status-ok" title="Bound — awaiting the box's next poll">bound → {{.BoundCustomer}}</span>{{end}}
|
||||
</td>
|
||||
<td style="font-family: var(--font-mono); letter-spacing: 0.05em;">{{if .PairingCode}}<strong>{{.PairingCode}}</strong>{{else}}<span class="text-muted">—</span>{{end}}</td>
|
||||
<td style="font-size: 0.78em; font-family: var(--font-mono)">{{range .MACs}}{{.}}<br>{{end}}</td>
|
||||
<td style="font-size: 0.8em;">{{if .Product}}{{.Product}}<br>{{end}}{{if .CPU}}<span class="text-muted">{{.CPU}}</span><br>{{end}}{{if .MemGB}}<span class="text-muted">{{.MemGB}}</span>{{end}}</td>
|
||||
<td style="font-size: 0.72em; font-family: var(--font-mono)">{{range .SSHFingerprints}}{{.}}<br>{{end}}</td>
|
||||
|
||||
Reference in New Issue
Block a user