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/ 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 = ` Felhom — Doboz összekötése

Felhom doboz összekötése

{{if eq .State "form"}}

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.

{{if .Failed}}{{end}}

A doboz monitorán jelenik meg, a telepítés után.

Az öt szóból álló kifejezés, amelyet a beállításkor kaptál.

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.

{{else if eq .State "success"}}

Sikeres összekötés.

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.

{{else if eq .State "consumed"}}

Ez a hivatkozás már fel lett használva.

A doboz összekötése megtörtént. Ha úgy gondolod, hogy ez tévedés, vedd fel a kapcsolatot az ügyfélszolgálattal.

{{else if eq .State "locked"}}

Ez a hivatkozás zárolva van.

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.

{{else}}

Ez a hivatkozás érvénytelen vagy lejárt.

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.

{{end}}

Felhom.eu

`