hub v0.152.0: operator access tokens with scopes (09 §3 decision 251, operator 2026-10-15 11:38)
gates / gates (push) Successful in 6m44s
gates / gates (push) Successful in 6m44s
- Configuration → Access tokens: named, scoped (group read/write), expiring (≤365 d), shown once, stored SHA-256 only, every use logged by name. Bearer fhp_… on the web surface only; /api/v1 refuses it. - Route table = the code's single source (web/routes.go), pinned to ServeHTTP's switch; session-only: secrets shown/minted, deletes/resets, password, tokens. - R-952 closed: /api/v1 route table names each caller, pinned to the switch; no-credential refusal test. - Fail-open fixed: an empty operator password served the UI open (main skipped RequireAuth). Live hub never open. - 05 §17, 04 §6.2, 13, 09 §3 251; register 155→157 (+R-1054, R-1055, R-1056, −R-952); STATUS. - website: prowlarr-logo.svg (byte copy from felhom.eu-media) — the site gate refused every push. Not deployed — waits for the operator's yes. Claude-Session: https://claude.ai/code/session_012qRErfCoiTkvDK9N5XHbzb
This commit is contained in:
1 parent
e92501f5a1
commit
d62cc08b2e
37 files changed
+2567
-21
No files matched your search
@@ -62,6 +62,10 @@ var r135PostRoutes = []string{
|
||||
"/os/approve-docker",
|
||||
"/os/approve-pve",
|
||||
"/os/approve-kernel",
|
||||
// v0.152.0: the operator-action route was missing from this hand-kept list; the token routes are new.
|
||||
"/hosts/h1/operator-action",
|
||||
"/configuration/tokens",
|
||||
"/configuration/tokens/1/revoke",
|
||||
// Not a route: the gate must refuse BEFORE routing, so even an unknown path is 403, never 404.
|
||||
"/no-such-route",
|
||||
}
|
||||
@@ -70,7 +74,7 @@ var r135PostRoutes = []string{
|
||||
func r135Handler(t *testing.T) (*Server, http.Handler) {
|
||||
t.Helper()
|
||||
s, _ := serverWithPassword(t, "op-pass")
|
||||
return s, s.RequireAuth(http.HandlerFunc(s.ServeHTTP))
|
||||
return s, s.Handler()
|
||||
}
|
||||
|
||||
func r135Post(h http.Handler, path string, mut func(*http.Request)) *httptest.ResponseRecorder {
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
package web
|
||||
|
||||
import "strings"
|
||||
|
||||
// The operator route table (hub v0.152.0, `05` §17). EVERY case of ServeHTTP's route switch has one entry here,
|
||||
// in the SAME ORDER and with the SAME match (exact / prefix / suffix / contains), and the classifier walks the
|
||||
// entries first-match-wins exactly as the switch does — so the class a request gets is the class of the handler
|
||||
// that serves it. TestRouteTable_MatchesServeHTTPSwitch reads the switch from server.go's syntax tree and fails
|
||||
// when a case is added, removed, reordered or changed without this table following (R-952, web side).
|
||||
//
|
||||
// What a class means for an ACCESS TOKEN (a session and Basic+header stay full operator, unchanged):
|
||||
// - sessionOnly — never by any token: a secret is shown or minted, something is deleted or reset, the password or
|
||||
// the tokens themselves change, or no group fits (listed in `05` §17 for the operator to place).
|
||||
// - anyToken — any valid token (static assets of the page itself).
|
||||
// - exempt — not an operator route at all (/login, the public /bind/); the token is not consulted.
|
||||
// - a group + read/write — the token needs "<group>:<mode>" (write includes read).
|
||||
//
|
||||
// GET and HEAD use the entry's get class; every other method uses post. A method the entry does not name is
|
||||
// sessionOnly — the fail-safe direction, and the handler answers 405 to it anyway.
|
||||
|
||||
// Token scope groups. The keys are stored in api_tokens.scopes; the labels are the Configuration card's words.
|
||||
const (
|
||||
grpOverview = "overview"
|
||||
grpFloor = "floor"
|
||||
grpVouch = "vouch"
|
||||
grpCustomers = "customers"
|
||||
grpHosts = "hosts"
|
||||
grpOffsite = "offsite"
|
||||
grpOS = "os"
|
||||
grpMailHold = "mailhold"
|
||||
)
|
||||
|
||||
// scopeGroup is one row of the Configuration card. Read/Write say which ticks it offers: a tick is offered only when
|
||||
// it opens at least one route (TestScopeGroups_EveryOfferedTickOpensARoute).
|
||||
type scopeGroup struct {
|
||||
Key, Label, ReadHelp, WriteHelp string
|
||||
Read, Write bool
|
||||
}
|
||||
|
||||
var scopeGroups = []scopeGroup{
|
||||
{grpOverview, "Overview", "dashboard, customer list, hosts list, apps, off-site, system (no secrets)", "", true, false},
|
||||
{grpFloor, "Releases: floor", "the floors (Configuration page, floor impact)", "the global and the per-customer floor", true, true},
|
||||
{grpVouch, "Releases: vouch", "", "golden, agent, MinAgent (the vouch)", false, true},
|
||||
{grpCustomers, "Customers", "config forms, DR recipe", "create, edit, block/unblock, geo, resend claim", true, true},
|
||||
{grpHosts, "Hosts & logs", "host pages, log bundles, log tails", "operator actions, log requests", true, true},
|
||||
{grpOffsite, "Off-site", "run the key check", "windows, re-issue, freeze", true, true},
|
||||
{grpOS, "OS updates", "the fleet queue", "approve, ring, on/off", true, true},
|
||||
{grpMailHold, "Mail hold", "", "release", false, true},
|
||||
}
|
||||
|
||||
type routeClass struct {
|
||||
Group string // "" unless group-scoped
|
||||
Write bool
|
||||
SessionOnly bool
|
||||
AnyToken bool
|
||||
Exempt bool
|
||||
}
|
||||
|
||||
var (
|
||||
sessionOnly = routeClass{SessionOnly: true}
|
||||
anyToken = routeClass{AnyToken: true}
|
||||
exempt = routeClass{Exempt: true}
|
||||
)
|
||||
|
||||
func rd(g string) routeClass { return routeClass{Group: g} }
|
||||
func wr(g string) routeClass { return routeClass{Group: g, Write: true} }
|
||||
|
||||
// scope is the "<group>:<mode>" string a group-scoped class needs.
|
||||
func (c routeClass) scope() string {
|
||||
if c.Write {
|
||||
return c.Group + ":write"
|
||||
}
|
||||
return c.Group + ":read"
|
||||
}
|
||||
|
||||
// routeEntry mirrors one disjunct of one switch case. bindFn marks the isPublicBindPath case.
|
||||
type routeEntry struct {
|
||||
Exact, Prefix, Suffix, Contains string
|
||||
BindFn bool
|
||||
Get, Post routeClass
|
||||
}
|
||||
|
||||
func (e routeEntry) matches(path string) bool {
|
||||
if e.BindFn {
|
||||
return isPublicBindPath(path)
|
||||
}
|
||||
if e.Exact != "" && path != e.Exact {
|
||||
return false
|
||||
}
|
||||
if e.Prefix != "" && !strings.HasPrefix(path, e.Prefix) {
|
||||
return false
|
||||
}
|
||||
if e.Suffix != "" && !strings.HasSuffix(path, e.Suffix) {
|
||||
return false
|
||||
}
|
||||
if e.Contains != "" && !strings.Contains(path, e.Contains) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
var none = routeClass{} // zero: the method is not served → treated as sessionOnly
|
||||
|
||||
// operatorRoutes is the table. Order and match are pinned to server.go's switch by the test named above.
|
||||
var operatorRoutes = []routeEntry{
|
||||
{Exact: "/", Get: rd(grpOverview)},
|
||||
{Exact: "/style.css", Get: anyToken},
|
||||
{Exact: "/static/chart.min.js", Get: anyToken},
|
||||
{Prefix: "/static/fonts/", Get: anyToken},
|
||||
// The Configuration page shows the floors; its POST is the asset re-seed, which fits no group.
|
||||
{Exact: "/configuration", Get: rd(grpFloor), Post: sessionOnly},
|
||||
{Exact: "/apps", Get: rd(grpOverview)},
|
||||
{Exact: "/apps/", Get: rd(grpOverview)},
|
||||
// Telemetry reset and issue dismissal change the fleet view; no group fits them.
|
||||
{Prefix: "/apps/", Suffix: "/reset-telemetry", Post: sessionOnly},
|
||||
{Prefix: "/apps/", Suffix: "/dismiss-issues", Post: sessionOnly},
|
||||
{Prefix: "/apps/", Get: rd(grpOverview)},
|
||||
{Exact: "/offsite", Get: rd(grpOverview)},
|
||||
// The WireGuard endpoint record is infrastructure; no group fits a save.
|
||||
{Exact: "/offsite/endpoints", Post: sessionOnly},
|
||||
{Prefix: "/offsite/endpoints/", Suffix: "/delete", Post: sessionOnly},
|
||||
{Exact: "/hosts", Get: rd(grpOverview)},
|
||||
{Exact: "/hosts/", Get: rd(grpOverview)},
|
||||
{Exact: "/system", Get: rd(grpOverview)},
|
||||
// A bind delivers the household's retrieval passphrase to the box that asks — a secret delivery.
|
||||
{Prefix: "/appliances/", Suffix: "/bind", Post: sessionOnly},
|
||||
{Prefix: "/appliances/", Suffix: "/discard", Post: sessionOnly},
|
||||
{Prefix: "/hosts/", Suffix: "/delete-impact", Get: sessionOnly},
|
||||
{Prefix: "/hosts/", Suffix: "/delete", Post: sessionOnly},
|
||||
{Prefix: "/hosts/", Suffix: "/reveal-recovery-credential", Post: sessionOnly},
|
||||
{Prefix: "/hosts/", Suffix: "/operator-action", Post: wr(grpHosts)},
|
||||
{Prefix: "/hosts/", Suffix: "/request-logs", Post: wr(grpHosts)},
|
||||
{Prefix: "/hosts/", Contains: "/log-bundles/", Get: rd(grpHosts)},
|
||||
{Prefix: "/hosts/", Get: rd(grpHosts)},
|
||||
{Exact: "/login", Get: exempt, Post: exempt},
|
||||
{BindFn: true, Get: exempt, Post: exempt},
|
||||
{Prefix: "/customers/", Suffix: "/block", Post: wr(grpCustomers)},
|
||||
// The self-bind link is a capability that binds a box to the household — minted here.
|
||||
{Prefix: "/customers/", Suffix: "/selfbind-link", Post: sessionOnly},
|
||||
{Prefix: "/customers/", Suffix: "/unblock", Post: wr(grpCustomers)},
|
||||
{Prefix: "/customers/", Suffix: "/geo/disable", Post: wr(grpCustomers)},
|
||||
{Prefix: "/customers/", Suffix: "/floor", Post: wr(grpFloor)},
|
||||
{Prefix: "/customers/", Suffix: "/create-config", Post: wr(grpCustomers)},
|
||||
{Prefix: "/customers/", Suffix: "/dr-recipe.json", Get: rd(grpCustomers)},
|
||||
{Prefix: "/customers/", Suffix: "/request-log-tail", Post: wr(grpHosts)},
|
||||
{Prefix: "/customers/", Contains: "/log-tail/", Get: rd(grpHosts)},
|
||||
// The customer page embeds the owner passphrase and the controller API key (customer_unified.html).
|
||||
{Prefix: "/customers/", Get: sessionOnly, Post: sessionOnly},
|
||||
{Exact: "/configs", Get: rd(grpOverview)},
|
||||
{Exact: "/configs/new", Get: rd(grpCustomers), Post: wr(grpCustomers)},
|
||||
{Exact: "/configuration/global-floor/impact", Get: rd(grpFloor)},
|
||||
{Exact: "/configuration/global-floor", Post: wr(grpFloor)},
|
||||
{Exact: "/configuration/artifacts", Post: wr(grpVouch)},
|
||||
{Exact: "/configuration/mail-hold/release", Post: wr(grpMailHold)},
|
||||
{Exact: "/configuration/password", Post: sessionOnly},
|
||||
{Exact: "/configuration/tokens", Post: sessionOnly},
|
||||
{Prefix: "/configuration/tokens/", Suffix: "/revoke", Post: sessionOnly},
|
||||
{Prefix: "/configs/", Suffix: "/delete", Get: sessionOnly, Post: sessionOnly},
|
||||
{Prefix: "/configs/", Suffix: "/edit", Get: rd(grpCustomers), Post: wr(grpCustomers)},
|
||||
{Prefix: "/offsite/remove-unpinned/", Post: sessionOnly},
|
||||
// Cancelling a pending set-aside deletion: no group names it; until the operator places it, session only.
|
||||
{Prefix: "/offsite/abandon-cancel/", Post: sessionOnly},
|
||||
{Prefix: "/offsite/window-grant/", Post: wr(grpOffsite)},
|
||||
{Exact: "/offsite/windows-enabled", Post: wr(grpOffsite)},
|
||||
{Prefix: "/os/", Get: rd(grpOS), Post: wr(grpOS)},
|
||||
// Runs the daily key check now: it reads keys and reports, it changes none.
|
||||
{Exact: "/offsite/key-audit", Post: rd(grpOffsite)},
|
||||
{Prefix: "/configs/", Suffix: "/offsite-reissue", Post: wr(grpOffsite)},
|
||||
{Prefix: "/configs/", Suffix: "/claim-resend", Post: wr(grpCustomers)},
|
||||
{Prefix: "/configs/", Suffix: "/pbsdr-reissue", Post: wr(grpOffsite)},
|
||||
{Prefix: "/configs/", Suffix: "/offsite-freeze", Post: wr(grpOffsite)},
|
||||
// The preview is the generated controller config — it carries the controller API key.
|
||||
{Prefix: "/configs/", Suffix: "/preview", Get: sessionOnly},
|
||||
{Prefix: "/configs/", Suffix: "/regen-password", Post: sessionOnly},
|
||||
{Prefix: "/configs/", Suffix: "/reset", Get: sessionOnly, Post: sessionOnly},
|
||||
{Prefix: "/configs/", Get: rd(grpOverview), Post: rd(grpOverview)},
|
||||
}
|
||||
|
||||
// classifyRoute returns the class of the handler that serves (method, path). A path no entry matches is the
|
||||
// switch's 404 — sessionOnly, so an unknown path never answers a token differently from a missing scope.
|
||||
func classifyRoute(method, path string) routeClass {
|
||||
for _, e := range operatorRoutes {
|
||||
if !e.matches(path) {
|
||||
continue
|
||||
}
|
||||
c := e.Post
|
||||
if method == "GET" || method == "HEAD" {
|
||||
c = e.Get
|
||||
}
|
||||
if c == none {
|
||||
return sessionOnly
|
||||
}
|
||||
return c
|
||||
}
|
||||
return sessionOnly
|
||||
}
|
||||
|
||||
// validScope reports whether s is a scope the Configuration card offers.
|
||||
func validScope(s string) bool {
|
||||
for _, g := range scopeGroups {
|
||||
if (g.Read && s == g.Key+":read") || (g.Write && s == g.Key+":write") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// tokenAllows reports whether a token holding scopes may use class c. write includes read.
|
||||
func tokenAllows(scopes []string, c routeClass) bool {
|
||||
switch {
|
||||
case c.Exempt, c.AnyToken:
|
||||
return true
|
||||
case c.SessionOnly, c.Group == "":
|
||||
return false
|
||||
}
|
||||
for _, s := range scopes {
|
||||
if s == c.scope() || (!c.Write && s == c.Group+":write") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -712,6 +712,19 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
} else {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
}
|
||||
// Access tokens (v0.152.0, `05` §17) — session only (routes.go), each handler checks again.
|
||||
case path == "/configuration/tokens":
|
||||
if r.Method == http.MethodPost {
|
||||
s.handleTokenCreate(w, r)
|
||||
} else {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
}
|
||||
case strings.HasPrefix(path, "/configuration/tokens/") && strings.HasSuffix(path, "/revoke"):
|
||||
if r.Method == http.MethodPost {
|
||||
s.handleTokenRevoke(w, r, strings.TrimSuffix(strings.TrimPrefix(path, "/configuration/tokens/"), "/revoke"))
|
||||
} else {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
}
|
||||
case strings.HasPrefix(path, "/configs/") && strings.HasSuffix(path, "/delete"):
|
||||
// Customer DELETE cascade (v0.69.0, R-25b): GET returns the guided dialog's live inventory
|
||||
// (hosts + offsite + PBS + custody + any incomplete journal), POST runs the full teardown.
|
||||
@@ -861,9 +874,19 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// RequireAuth wraps a handler with session or basic authentication.
|
||||
func (s *Server) RequireAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Skip auth if no password configured
|
||||
// No operator password configured → every operator route is CLOSED (v0.152.0). Before, this
|
||||
// branch served everything with no credential, and main.go did not even mount RequireAuth when
|
||||
// the ConfigMap seed was empty — so a hub whose password lived only in the DB override, or a
|
||||
// manifest that lost auth.password_hash, served the whole operator UI open. The public /bind/
|
||||
// surface does not depend on the operator password and stays up; /login renders but cannot
|
||||
// succeed. Pinned by TestRequireAuth_NoPasswordRefusesEveryOperatorRoute.
|
||||
if s.effectivePasswordHash() == "" {
|
||||
next.ServeHTTP(w, r)
|
||||
if isPublicBindPath(r.URL.Path) || r.URL.Path == "/login" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
s.logger.Printf("[ERROR] operator route refused: no operator password is configured — %s %s", r.Method, r.URL.Path)
|
||||
http.Error(w, "Service unavailable: no operator password is configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -877,6 +900,13 @@ func (s *Server) RequireAuth(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
// An access token (v0.152.0, `05` §17) is decided by its scopes alone — it never falls through
|
||||
// to the session or Basic paths, so a token request is never full operator.
|
||||
if tok := bearerToken(r); tok != "" {
|
||||
s.serveWithToken(w, r, next, tok)
|
||||
return
|
||||
}
|
||||
|
||||
// Check session cookie (random token stored server-side)
|
||||
if cookie, err := r.Cookie(SessionCookieName); err == nil {
|
||||
s.sessionsMu.RLock()
|
||||
@@ -976,6 +1006,11 @@ const OperatorCLIHeader = "X-Felhom-Operator"
|
||||
// Before v0.135.0 a request with no session cookie passed unconditionally (measured live: a Basic-auth
|
||||
// POST with no cookie reached the handler).
|
||||
func (s *Server) validateCSRF(r *http.Request) bool {
|
||||
// An access token is not a credential a browser sends on its own (tokens.go explains); the token
|
||||
// path in RequireAuth has already checked it and its scope for this route.
|
||||
if requestToken(r) != nil {
|
||||
return true
|
||||
}
|
||||
cookie, err := r.Cookie(SessionCookieName)
|
||||
if err != nil {
|
||||
_, _, basic := r.BasicAuth()
|
||||
@@ -1163,6 +1198,11 @@ func statusColor(status string) string {
|
||||
|
||||
// handleConfiguration renders the Configuration page.
|
||||
func (s *Server) handleConfiguration(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderConfiguration(w, r, nil)
|
||||
}
|
||||
|
||||
// renderConfiguration renders the page; created is a token minted by this very request, shown once (tokens.go).
|
||||
func (s *Server) renderConfiguration(w http.ResponseWriter, r *http.Request, created *createdToken) {
|
||||
csrfToken := s.getCSRFToken(r)
|
||||
|
||||
assetCount := 0
|
||||
@@ -1201,6 +1241,16 @@ func (s *Server) handleConfiguration(w http.ResponseWriter, r *http.Request) {
|
||||
"AgentChoices": agentChoices,
|
||||
"GoldenChoices": goldenChoices,
|
||||
"Flash": r.URL.Query().Get("flash"),
|
||||
// Access tokens (v0.152.0): the card is managed only from a session — a token-authenticated
|
||||
// read of this page gets no token list (routes.go: token management is session only).
|
||||
"ShowTokens": requestToken(r) == nil,
|
||||
"TokenGroups": scopeGroups,
|
||||
"TokenDays": tokenDaysChoices,
|
||||
"TokenDefaultDays": tokenDefaultDays,
|
||||
"CreatedToken": created,
|
||||
}
|
||||
if requestToken(r) == nil {
|
||||
data["Tokens"] = s.tokenRows()
|
||||
}
|
||||
if err := s.templates.ExecuteTemplate(w, "configuration.html", data); err != nil {
|
||||
s.logger.Printf("[ERROR] configuration.html template: %v", err)
|
||||
|
||||
@@ -284,6 +284,77 @@
|
||||
</script>
|
||||
</section>
|
||||
|
||||
<!-- Access tokens (v0.152.0, `05` §17): scoped, expiring stand-ins for the operator password, for scripts.
|
||||
Managed only from a browser session — ShowTokens is false when a token reads this page. -->
|
||||
{{if .ShowTokens}}
|
||||
<section class="card" id="tokens">
|
||||
<h3 style="margin-top: 0;">Access tokens</h3>
|
||||
<p class="text-muted">
|
||||
A token lets a script use the hub without your password. Tick what it may do; it can do nothing else.
|
||||
<strong>Never by any token:</strong> showing a box's emergency root password or a household's passphrase,
|
||||
deleting or resetting a customer or host, changing the password, creating or revoking tokens.
|
||||
Write includes read. The hub keeps only a scrambled form of each token, and logs every use by name.
|
||||
</p>
|
||||
{{if eq .Flash "token_revoked"}}<div class="flash flash-success">Token revoked. It stops working now.</div>{{end}}
|
||||
{{if eq .Flash "token_name_invalid"}}<div class="flash flash-error">The token needs a name (at most 64 characters). Nothing was created.</div>{{end}}
|
||||
{{if eq .Flash "token_no_scope"}}<div class="flash flash-error">Tick at least one permission. Nothing was created.</div>{{end}}
|
||||
{{if eq .Flash "token_scope_invalid"}}<div class="flash flash-error">Unknown permission. Nothing was created.</div>{{end}}
|
||||
{{if eq .Flash "token_days_invalid"}}<div class="flash flash-error">Expiry must be 1 to 365 days. Nothing was created.</div>{{end}}
|
||||
{{if eq .Flash "token_create_failed"}}<div class="flash flash-error">The token was not saved. Nothing was created.</div>{{end}}
|
||||
{{if eq .Flash "token_revoke_failed"}}<div class="flash flash-error">The token was not revoked.</div>{{end}}
|
||||
{{with .CreatedToken}}
|
||||
<div class="flash flash-warn" id="token-created">
|
||||
<strong>Token {{.Name}} created. Copy it now — it is shown only this once.</strong><br>
|
||||
<code id="token-plain">{{.Plain}}</code>
|
||||
<button type="button" class="btn btn-sm" onclick="navigator.clipboard.writeText(document.getElementById('token-plain').textContent)">Copy</button>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if .Tokens}}
|
||||
<table class="data-table">
|
||||
<thead><tr><th>Name</th><th>Permissions</th><th>Expires</th><th>Last used</th><th>From</th><th>State</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Tokens}}
|
||||
<tr>
|
||||
<td>{{.Name}}</td>
|
||||
<td><code>{{.Scopes}}</code></td>
|
||||
<td>{{.Expires}}</td>
|
||||
<td>{{.LastUsed}}</td>
|
||||
<td>{{.LastUsedFrom}}</td>
|
||||
<td>{{if .Active}}<span class="badge badge-ok">{{.State}}</span>{{else}}<span class="badge badge-neutral">{{.State}}</span>{{end}}</td>
|
||||
<td>{{if .Active}}<form method="POST" action="/configuration/tokens/{{.ID}}/revoke">{{$.CSRFField}}<button class="btn btn-sm" type="submit" data-confirm="Revoke the token {{.Name}}? Scripts using it stop working at once.">Revoke</button></form>{{end}}</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{else}}
|
||||
<p class="text-muted">No tokens yet.</p>
|
||||
{{end}}
|
||||
<form method="POST" action="/configuration/tokens" id="token-create-form">
|
||||
{{.CSRFField}}
|
||||
<h4>New token</h4>
|
||||
<label>Name <input type="text" name="name" maxlength="64" required placeholder="cc-releases"></label>
|
||||
<table class="data-table">
|
||||
<thead><tr><th>Group</th><th>Read</th><th>Write</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .TokenGroups}}
|
||||
<tr>
|
||||
<td>{{.Label}}</td>
|
||||
<td>{{if .Read}}<label><input type="checkbox" name="scope" value="{{.Key}}:read"> <span class="text-muted">{{.ReadHelp}}</span></label>{{end}}</td>
|
||||
<td>{{if .Write}}<label><input type="checkbox" name="scope" value="{{.Key}}:write"> <span class="text-muted">{{.WriteHelp}}</span></label>{{end}}</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
<label>Expires after
|
||||
<select name="days">
|
||||
{{range .TokenDays}}<option value="{{.}}"{{if eq . $.TokenDefaultDays}} selected{{end}}>{{.}} days</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
<button class="btn btn-sm" type="submit">Create token</button>
|
||||
</form>
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
<!-- Assets section -->
|
||||
<section class="card">
|
||||
<h3 style="margin-top: 0;">Assets</h3>
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base32"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
|
||||
)
|
||||
|
||||
// Operator access tokens (hub v0.152.0, `05` §17). The token rides `Authorization: Bearer fhp_…`. It is checked
|
||||
// in RequireAuth BEFORE the session and Basic paths, against the route table in routes.go.
|
||||
//
|
||||
// WHY NO CSRF TOKEN FOR IT (`05` §16.1): a browser never attaches a bearer header by itself — not from a cookie,
|
||||
// not from a cached credential — and a page on another site can set an Authorization header only through a CORS
|
||||
// preflight, which the hub never answers. So a request that carries the token was written by whoever holds it.
|
||||
// Pinned by TestToken_PostWithoutCSRFPasses and TestToken_CSRFRuleUnchangedForBasic.
|
||||
|
||||
// TokenPrefix marks a hub operator access token (the API refuses the same prefix, api/handler.go).
|
||||
const TokenPrefix = store.APITokenPrefix
|
||||
|
||||
const (
|
||||
tokenDefaultDays = 90
|
||||
tokenMaxDays = 365
|
||||
)
|
||||
|
||||
type tokenCtxKey struct{}
|
||||
|
||||
// requestToken returns the access token that authenticated r, or nil (session / Basic / unauthenticated).
|
||||
func requestToken(r *http.Request) *store.APIToken {
|
||||
t, _ := r.Context().Value(tokenCtxKey{}).(*store.APIToken)
|
||||
return t
|
||||
}
|
||||
|
||||
// newPlainToken mints fhp_ + 32 random bytes, base32 without padding (lower case, 52 chars).
|
||||
func newPlainToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return TokenPrefix + strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(b)), nil
|
||||
}
|
||||
|
||||
// bearerToken returns the fhp_ token in r's Authorization header, or "".
|
||||
func bearerToken(r *http.Request) string {
|
||||
auth := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(auth, "Bearer ") {
|
||||
return ""
|
||||
}
|
||||
tok := strings.TrimSpace(strings.TrimPrefix(auth, "Bearer "))
|
||||
if !strings.HasPrefix(tok, TokenPrefix) {
|
||||
return ""
|
||||
}
|
||||
return tok
|
||||
}
|
||||
|
||||
// clientAddr is where a request came from, for "last used from": the first X-Forwarded-For hop when the ingress
|
||||
// set one, else the socket peer. Informational only — never an auth input.
|
||||
func clientAddr(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
return strings.TrimSpace(strings.Split(xff, ",")[0])
|
||||
}
|
||||
if h, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
return h
|
||||
}
|
||||
return r.RemoteAddr
|
||||
}
|
||||
|
||||
// serveWithToken authenticates r by its access token and either serves it or refuses it. Every outcome is logged
|
||||
// with the token's NAME (never the token): 401 for an unknown, revoked or expired token, 403 naming the missing
|
||||
// scope or "session only".
|
||||
func (s *Server) serveWithToken(w http.ResponseWriter, r *http.Request, next http.Handler, plain string) {
|
||||
method, path := r.Method, r.URL.Path
|
||||
t, err := s.store.GetAPITokenByPlain(plain)
|
||||
if err != nil {
|
||||
s.logger.Printf("[ERROR] access token lookup failed: %v", err)
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case t == nil:
|
||||
s.logger.Printf("[WARN] access token refused: unknown token — %s %s from %s → 401", method, path, clientAddr(r))
|
||||
http.Error(w, "Unauthorized: unknown access token", http.StatusUnauthorized)
|
||||
return
|
||||
case t.RevokedAt != nil:
|
||||
s.logger.Printf("[WARN] access token %q refused: revoked — %s %s → 401", t.Name, method, path)
|
||||
http.Error(w, "Unauthorized: access token revoked", http.StatusUnauthorized)
|
||||
return
|
||||
case t.Expired(time.Now()):
|
||||
s.logger.Printf("[WARN] access token %q refused: expired %s — %s %s → 401", t.Name, t.ExpiresAt.UTC().Format(time.RFC3339), method, path)
|
||||
http.Error(w, "Unauthorized: access token expired", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
c := classifyRoute(method, path)
|
||||
if !tokenAllows(t.Scopes, c) {
|
||||
why := "session only — never by a token"
|
||||
if !c.SessionOnly && c.Group != "" {
|
||||
why = "missing scope " + c.scope()
|
||||
}
|
||||
s.logger.Printf("[WARN] access token %q refused: %s — %s %s → 403", t.Name, why, method, path)
|
||||
http.Error(w, "Forbidden: "+why, http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if err := s.store.TouchAPIToken(t.ID, clientAddr(r)); err != nil {
|
||||
s.logger.Printf("[WARN] access token %q: last-used not recorded: %v", t.Name, err)
|
||||
}
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rec, r.WithContext(context.WithValue(r.Context(), tokenCtxKey{}, t)))
|
||||
s.logger.Printf("[INFO] access token %q: %s %s → %d", t.Name, method, path, rec.status)
|
||||
}
|
||||
|
||||
// statusRecorder keeps the status a handler wrote, for the token's log line.
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
wrote bool
|
||||
}
|
||||
|
||||
func (s *statusRecorder) WriteHeader(code int) {
|
||||
if !s.wrote {
|
||||
s.status, s.wrote = code, true
|
||||
}
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (s *statusRecorder) Write(b []byte) (int, error) {
|
||||
s.wrote = true
|
||||
return s.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
// handleTokenCreate creates a token from the Configuration card (session only — classified in routes.go, and this
|
||||
// handler checks again so a table slip cannot open it). The plain token is rendered once in the response page.
|
||||
func (s *Server) handleTokenCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if requestToken(r) != nil {
|
||||
http.Error(w, "Forbidden: session only — never by a token", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
name := strings.TrimSpace(r.FormValue("name"))
|
||||
if name == "" || len(name) > 64 {
|
||||
http.Redirect(w, r, "/configuration?flash=token_name_invalid#tokens", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
var scopes []string
|
||||
for _, sc := range r.Form["scope"] {
|
||||
if !validScope(sc) {
|
||||
http.Redirect(w, r, "/configuration?flash=token_scope_invalid#tokens", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
scopes = append(scopes, sc)
|
||||
}
|
||||
if len(scopes) == 0 {
|
||||
http.Redirect(w, r, "/configuration?flash=token_no_scope#tokens", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
days, err := strconv.Atoi(strings.TrimSpace(r.FormValue("days")))
|
||||
if r.FormValue("days") == "" {
|
||||
days, err = tokenDefaultDays, nil
|
||||
}
|
||||
if err != nil || days < 1 || days > tokenMaxDays {
|
||||
http.Redirect(w, r, "/configuration?flash=token_days_invalid#tokens", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
plain, err := newPlainToken()
|
||||
if err != nil {
|
||||
s.logger.Printf("[ERROR] access token: random source failed: %v", err)
|
||||
http.Error(w, "Internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
expires := time.Now().Add(time.Duration(days) * 24 * time.Hour)
|
||||
if _, err := s.store.CreateAPIToken(name, plain, scopes, "operator (session)", expires); err != nil {
|
||||
s.logger.Printf("[ERROR] access token %q not created: %v", name, err)
|
||||
http.Redirect(w, r, "/configuration?flash=token_create_failed#tokens", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
s.logger.Printf("[INFO] access token %q created from %s: scopes %s, expires %s", name, clientAddr(r), strings.Join(scopes, ","), expires.UTC().Format(time.RFC3339))
|
||||
// Shown once: rendered into this response only, with no-store, never put in a redirect URL or a log.
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
s.renderConfiguration(w, r, &createdToken{Name: name, Plain: plain})
|
||||
}
|
||||
|
||||
// handleTokenRevoke revokes one token (session only, same double check).
|
||||
func (s *Server) handleTokenRevoke(w http.ResponseWriter, r *http.Request, idStr string) {
|
||||
if requestToken(r) != nil {
|
||||
http.Error(w, "Forbidden: session only — never by a token", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseInt(idStr, 10, 64)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := s.store.RevokeAPIToken(id); err != nil {
|
||||
s.logger.Printf("[WARN] access token %d not revoked: %v", id, err)
|
||||
http.Redirect(w, r, "/configuration?flash=token_revoke_failed#tokens", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
s.logger.Printf("[INFO] access token %d revoked from %s", id, clientAddr(r))
|
||||
http.Redirect(w, r, "/configuration?flash=token_revoked#tokens", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// createdToken is the one-time display of a fresh token on the Configuration page.
|
||||
type createdToken struct{ Name, Plain string }
|
||||
|
||||
// tokenRow is one line of the Access tokens card.
|
||||
type tokenRow struct {
|
||||
ID int64
|
||||
Name string
|
||||
Scopes string
|
||||
Expires string
|
||||
LastUsed string
|
||||
LastUsedFrom string
|
||||
State string // "active" / "expired" / "revoked"
|
||||
Active bool
|
||||
}
|
||||
|
||||
func (s *Server) tokenRows() []tokenRow {
|
||||
list, err := s.store.ListAPITokens()
|
||||
if err != nil {
|
||||
s.logger.Printf("[ERROR] access tokens list: %v", err)
|
||||
return nil
|
||||
}
|
||||
now := time.Now()
|
||||
var out []tokenRow
|
||||
for _, t := range list {
|
||||
row := tokenRow{ID: t.ID, Name: t.Name, Scopes: strings.Join(t.Scopes, ", "),
|
||||
Expires: t.ExpiresAt.Local().Format("2006-01-02"), LastUsed: "never", LastUsedFrom: t.LastUsedFrom}
|
||||
if t.LastUsedAt != nil {
|
||||
row.LastUsed = t.LastUsedAt.Local().Format("2006-01-02 15:04")
|
||||
}
|
||||
switch {
|
||||
case t.RevokedAt != nil:
|
||||
row.State = "revoked"
|
||||
case t.Expired(now):
|
||||
row.State = "expired"
|
||||
default:
|
||||
row.State, row.Active = "active", true
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// tokenDaysChoices are the expiry options of the create form; "never" is not offered.
|
||||
var tokenDaysChoices = []int{30, tokenDefaultDays, 180, tokenMaxDays}
|
||||
|
||||
|
||||
// Handler is the operator web surface as main mounts it: ServeHTTP behind RequireAuth, unconditionally.
|
||||
func (s *Server) Handler() http.Handler {
|
||||
return s.RequireAuth(http.HandlerFunc(s.ServeHTTP))
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// Operator access tokens (hub v0.152.0, `05` §17). Red-proofs are recorded in the hub CHANGELOG v0.152.0 entry and
|
||||
// felhom.eu/REPORT-hub-tokens.md.
|
||||
|
||||
// tokenServer is a hub web server with an operator password, a log buffer, and its DB path.
|
||||
func tokenServer(t *testing.T) (*Server, *store.Store, *bytes.Buffer, string) {
|
||||
t.Helper()
|
||||
dbPath := filepath.Join(t.TempDir(), "t.db")
|
||||
st, err := store.New(dbPath, log.New(io.Discard, "", 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { st.Close() })
|
||||
hash, _ := bcrypt.GenerateFromPassword([]byte("operator-pw"), bcrypt.MinCost)
|
||||
var buf bytes.Buffer
|
||||
s := New(st, string(hash), "", "test", 30*time.Minute, log.New(&buf, "", 0))
|
||||
return s, st, &buf, dbPath
|
||||
}
|
||||
|
||||
// mintToken stores a token with scopes and returns its plain value.
|
||||
func mintToken(t *testing.T, st *store.Store, name string, expires time.Time, scopes ...string) string {
|
||||
t.Helper()
|
||||
plain, err := newPlainToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.CreateAPIToken(name, plain, scopes, "test", expires); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return plain
|
||||
}
|
||||
|
||||
func tokenReq(method, path, plain string, form url.Values) *http.Request {
|
||||
var body io.Reader
|
||||
if form != nil {
|
||||
body = strings.NewReader(form.Encode())
|
||||
}
|
||||
r := httptest.NewRequest(method, path, body)
|
||||
if form != nil {
|
||||
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
if plain != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+plain)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func serve(s *Server, r *http.Request) *httptest.ResponseRecorder {
|
||||
w := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
// --- the route table is the switch -------------------------------------------------------------------------
|
||||
|
||||
// switchRoutes reads ServeHTTP's route switch from server.go's syntax tree: one routeEntry (match only) per
|
||||
// disjunct of each case, in order.
|
||||
func switchRoutes(t *testing.T) []routeEntry {
|
||||
t.Helper()
|
||||
f, err := parser.ParseFile(token.NewFileSet(), "server.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var sw *ast.SwitchStmt
|
||||
for _, d := range f.Decls {
|
||||
fd, ok := d.(*ast.FuncDecl)
|
||||
if !ok || fd.Name.Name != "ServeHTTP" || fd.Recv == nil {
|
||||
continue
|
||||
}
|
||||
for _, st := range fd.Body.List {
|
||||
if s, ok := st.(*ast.SwitchStmt); ok && s.Tag == nil {
|
||||
sw = s
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if sw == nil {
|
||||
t.Fatal("ServeHTTP route switch not found in server.go")
|
||||
}
|
||||
var out []routeEntry
|
||||
var disjuncts func(e ast.Expr) []ast.Expr
|
||||
disjuncts = func(e ast.Expr) []ast.Expr {
|
||||
if b, ok := e.(*ast.BinaryExpr); ok && b.Op == token.LOR {
|
||||
return append(disjuncts(b.X), disjuncts(b.Y)...)
|
||||
}
|
||||
return []ast.Expr{e}
|
||||
}
|
||||
var conjuncts func(e ast.Expr) []ast.Expr
|
||||
conjuncts = func(e ast.Expr) []ast.Expr {
|
||||
if b, ok := e.(*ast.BinaryExpr); ok && b.Op == token.LAND {
|
||||
return append(conjuncts(b.X), conjuncts(b.Y)...)
|
||||
}
|
||||
return []ast.Expr{e}
|
||||
}
|
||||
lit := func(e ast.Expr) string {
|
||||
bl, ok := e.(*ast.BasicLit)
|
||||
if !ok {
|
||||
t.Fatalf("route predicate argument is not a string literal: %#v", e)
|
||||
}
|
||||
v, _ := strconv.Unquote(bl.Value)
|
||||
return v
|
||||
}
|
||||
for _, c := range sw.Body.List {
|
||||
cc := c.(*ast.CaseClause)
|
||||
for _, e := range cc.List {
|
||||
for _, d := range disjuncts(e) {
|
||||
var re routeEntry
|
||||
for _, p := range conjuncts(d) {
|
||||
switch x := p.(type) {
|
||||
case *ast.BinaryExpr:
|
||||
if id, ok := x.X.(*ast.Ident); !ok || id.Name != "path" || x.Op != token.EQL {
|
||||
t.Fatalf("unrecognised route predicate at %v", x.Pos())
|
||||
}
|
||||
re.Exact = lit(x.Y)
|
||||
case *ast.CallExpr:
|
||||
name := ""
|
||||
switch fn := x.Fun.(type) {
|
||||
case *ast.SelectorExpr:
|
||||
name = fn.Sel.Name
|
||||
case *ast.Ident:
|
||||
name = fn.Name
|
||||
}
|
||||
switch name {
|
||||
case "HasPrefix":
|
||||
re.Prefix = lit(x.Args[1])
|
||||
case "HasSuffix":
|
||||
re.Suffix = lit(x.Args[1])
|
||||
case "Contains":
|
||||
re.Contains = lit(x.Args[1])
|
||||
case "isPublicBindPath":
|
||||
re.BindFn = true
|
||||
default:
|
||||
t.Fatalf("unrecognised route predicate %s at %v", name, x.Pos())
|
||||
}
|
||||
default:
|
||||
t.Fatalf("unrecognised route predicate at %v", p.Pos())
|
||||
}
|
||||
}
|
||||
out = append(out, re)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestRouteTable_MatchesServeHTTPSwitch is R-952 for the web side: a route added to the switch without a class in
|
||||
// operatorRoutes — or a reorder that would change which handler a path reaches — fails here.
|
||||
// RED-PROOF: delete the /hosts/{id}/operator-action entry from operatorRoutes → FAIL at index 21.
|
||||
func TestRouteTable_MatchesServeHTTPSwitch(t *testing.T) {
|
||||
sw := switchRoutes(t)
|
||||
if len(sw) < 60 {
|
||||
t.Fatalf("parsed only %d switch routes — the parser lost the switch", len(sw))
|
||||
}
|
||||
strip := func(e routeEntry) routeEntry {
|
||||
return routeEntry{Exact: e.Exact, Prefix: e.Prefix, Suffix: e.Suffix, Contains: e.Contains, BindFn: e.BindFn}
|
||||
}
|
||||
n := len(sw)
|
||||
if len(operatorRoutes) > n {
|
||||
n = len(operatorRoutes)
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
var a, b routeEntry
|
||||
if i < len(sw) {
|
||||
a = sw[i]
|
||||
}
|
||||
if i < len(operatorRoutes) {
|
||||
b = strip(operatorRoutes[i])
|
||||
}
|
||||
if a != b {
|
||||
t.Fatalf("route %d: switch has %+v, table has %+v — classify the route in routes.go in the switch's order", i, a, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// samplePath builds a path that entry e matches.
|
||||
func samplePath(e routeEntry) string {
|
||||
switch {
|
||||
case e.BindFn:
|
||||
return "/bind/tok"
|
||||
case e.Exact != "":
|
||||
return e.Exact
|
||||
}
|
||||
p := e.Prefix + "x1"
|
||||
if e.Contains != "" {
|
||||
p += e.Contains + "y1"
|
||||
}
|
||||
return p + e.Suffix
|
||||
}
|
||||
|
||||
// every (method, path) pair the table names, with its class.
|
||||
type routeSample struct {
|
||||
method, path string
|
||||
class routeClass
|
||||
}
|
||||
|
||||
func routeSamples(t *testing.T) []routeSample {
|
||||
var out []routeSample
|
||||
for i, e := range operatorRoutes {
|
||||
p := samplePath(e)
|
||||
// The sample must reach THIS entry, or the class tested is not the class served.
|
||||
for j, f := range operatorRoutes {
|
||||
if f.matches(p) {
|
||||
if j != i {
|
||||
t.Fatalf("sample %s for entry %d reaches entry %d first", p, i, j)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, m := range []string{http.MethodGet, http.MethodPost} {
|
||||
out = append(out, routeSample{m, p, classifyRoute(m, p)})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestScopeGroups_EveryOfferedTickOpensARoute: a tick on the card that opens nothing would be a promise the hub
|
||||
// does not keep; a group a route names but the card does not offer could never be granted.
|
||||
func TestScopeGroups_EveryOfferedTickOpensARoute(t *testing.T) {
|
||||
used := map[string]bool{}
|
||||
for _, s := range routeSamples(t) {
|
||||
if s.class.Group != "" {
|
||||
used[s.class.scope()] = true
|
||||
}
|
||||
}
|
||||
for _, g := range scopeGroups {
|
||||
if g.Read && !used[g.Key+":read"] {
|
||||
t.Errorf("card offers %s:read but no route needs it", g.Key)
|
||||
}
|
||||
if g.Write && !used[g.Key+":write"] {
|
||||
t.Errorf("card offers %s:write but no route needs it", g.Key)
|
||||
}
|
||||
}
|
||||
for sc := range used {
|
||||
if !validScope(sc) && !(strings.HasSuffix(sc, ":read") && validScope(strings.TrimSuffix(sc, ":read")+":write")) {
|
||||
t.Errorf("route needs %s, which the card cannot grant", sc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- what a token may and may not do -----------------------------------------------------------------------
|
||||
|
||||
func allScopes() []string {
|
||||
var out []string
|
||||
for _, g := range scopeGroups {
|
||||
if g.Read {
|
||||
out = append(out, g.Key+":read")
|
||||
}
|
||||
if g.Write {
|
||||
out = append(out, g.Key+":write")
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestToken_SessionOnlyRoutesRefuseEveryToken: a token holding EVERY scope gets 403 on every session-only route —
|
||||
// the reveal, the deletes, the resets, the password, the token routes, the customer page with its passphrase.
|
||||
// RED-PROOF: make tokenAllows return true for SessionOnly → FAIL on /hosts/x1/reveal-recovery-credential.
|
||||
func TestToken_SessionOnlyRoutesRefuseEveryToken(t *testing.T) {
|
||||
s, st, _, _ := tokenServer(t)
|
||||
plain := mintToken(t, st, "all", time.Now().Add(time.Hour), allScopes()...)
|
||||
n := 0
|
||||
for _, rs := range routeSamples(t) {
|
||||
if !rs.class.SessionOnly {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
w := serve(s, tokenReq(rs.method, rs.path, plain, url.Values{}))
|
||||
if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "session only") {
|
||||
t.Errorf("%s %s with an all-scope token: %d %q, want 403 session only", rs.method, rs.path, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
for _, must := range []string{"/hosts/x1/reveal-recovery-credential", "/configs/x1/delete", "/configs/x1/reset",
|
||||
"/hosts/x1/delete", "/configuration/password", "/configuration/tokens", "/customers/x1", "/configs/x1/preview"} {
|
||||
if c := classifyRoute(http.MethodPost, must); !c.SessionOnly {
|
||||
if c2 := classifyRoute(http.MethodGet, must); !c2.SessionOnly {
|
||||
t.Errorf("%s must be session only", must)
|
||||
}
|
||||
}
|
||||
}
|
||||
if n < 20 {
|
||||
t.Fatalf("only %d session-only samples — the table lost its classes", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestToken_NoTokenUnknownExpiredRevoked401: a token the hub does not hold, an expired one, a revoked one → 401.
|
||||
// RED-PROOF: drop the Expired branch in serveWithToken → the expired case answers 200.
|
||||
func TestToken_NoTokenUnknownExpiredRevoked401(t *testing.T) {
|
||||
s, st, _, _ := tokenServer(t)
|
||||
unknown, _ := newPlainToken()
|
||||
expired := mintToken(t, st, "old", time.Now().Add(-time.Minute), "overview:read")
|
||||
revoked := mintToken(t, st, "gone", time.Now().Add(time.Hour), "overview:read")
|
||||
list, _ := st.ListAPITokens()
|
||||
for _, tk := range list {
|
||||
if tk.Name == "gone" {
|
||||
if err := st.RevokeAPIToken(tk.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
for name, plain := range map[string]string{"unknown": unknown, "expired": expired, "revoked": revoked} {
|
||||
w := serve(s, tokenReq(http.MethodGet, "/", plain, nil))
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s token: %d, want 401", name, w.Code)
|
||||
}
|
||||
}
|
||||
// No credential at all: unchanged (browser → login page, script → 401).
|
||||
r := tokenReq(http.MethodGet, "/", "", nil)
|
||||
r.Header.Set("Accept", "application/json")
|
||||
if w := serve(s, r); w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("no credential: %d, want 401", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestToken_ScopeDecides: a token without the group → 403 naming the scope; read on a write route → 403; the right
|
||||
// scope → the handler runs AND its effect lands (the floor is stored), with no CSRF token needed.
|
||||
// RED-PROOF: make tokenAllows ignore Write (accept group:read for a write route) → the read-token floor save lands.
|
||||
func TestToken_ScopeDecides(t *testing.T) {
|
||||
s, st, logs, _ := tokenServer(t)
|
||||
overview := mintToken(t, st, "ov", time.Now().Add(time.Hour), "overview:read")
|
||||
floorRead := mintToken(t, st, "fr", time.Now().Add(time.Hour), "overview:read", "floor:read")
|
||||
cc := mintToken(t, st, "cc-releases", time.Now().Add(time.Hour), "overview:read", "floor:write")
|
||||
form := url.Values{"min_controller_version": {"0.300.0"}, "min_agent": {"0.150.0"}}
|
||||
|
||||
w := serve(s, tokenReq(http.MethodPost, "/configuration/global-floor", overview, form))
|
||||
if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "missing scope floor:write") {
|
||||
t.Errorf("overview token on floor save: %d %q", w.Code, w.Body.String())
|
||||
}
|
||||
w = serve(s, tokenReq(http.MethodPost, "/configuration/global-floor", floorRead, form))
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("floor:read token on floor save: %d, want 403", w.Code)
|
||||
}
|
||||
if got := st.GetGlobalMinControllerVersion(); got == "0.300.0" {
|
||||
t.Fatal("a refused token changed the floor")
|
||||
}
|
||||
// The vouch is not CC's: floor:write does not open it.
|
||||
w = serve(s, tokenReq(http.MethodPost, "/configuration/artifacts", cc, url.Values{"agent_version": {"0.1.0"}}))
|
||||
if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "missing scope vouch:write") {
|
||||
t.Errorf("cc token on the vouch: %d %q", w.Code, w.Body.String())
|
||||
}
|
||||
// Allowed — and the consequence is real.
|
||||
w = serve(s, tokenReq(http.MethodPost, "/configuration/global-floor", cc, form))
|
||||
if w.Code != http.StatusSeeOther {
|
||||
t.Fatalf("cc token on floor save: %d %q", w.Code, w.Body.String())
|
||||
}
|
||||
if got := st.GetGlobalMinControllerVersion(); got != "0.300.0" {
|
||||
t.Fatalf("floor after the cc token's save = %q, want 0.300.0", got)
|
||||
}
|
||||
if got := st.GlobalFloorDeclaredMinAgent(); got != "0.150.0" {
|
||||
t.Errorf("declared MinAgent = %q, want 0.150.0", got)
|
||||
}
|
||||
// write includes read: the Configuration page opens for floor:write.
|
||||
if w := serve(s, tokenReq(http.MethodGet, "/configuration", cc, nil)); w.Code != http.StatusOK {
|
||||
t.Errorf("cc token GET /configuration: %d", w.Code)
|
||||
} else if strings.Contains(w.Body.String(), `action="/configuration/tokens"`) {
|
||||
t.Error("a token-authenticated read of /configuration must not render the token card")
|
||||
}
|
||||
// The log names the token, never the token value.
|
||||
out := logs.String()
|
||||
if !strings.Contains(out, `access token "cc-releases": POST /configuration/global-floor → 303`) {
|
||||
t.Errorf("no allowed-use log line naming the token:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(out, `access token "ov" refused: missing scope floor:write`) {
|
||||
t.Errorf("no refusal log line naming the token:\n%s", out)
|
||||
}
|
||||
for _, p := range []string{overview, floorRead, cc} {
|
||||
if strings.Contains(out, p) || strings.Contains(out, p[len(TokenPrefix):]) {
|
||||
t.Fatal("a plain token reached the log")
|
||||
}
|
||||
}
|
||||
list, _ := st.ListAPITokens()
|
||||
for _, tk := range list {
|
||||
if tk.Name == "cc-releases" && (tk.LastUsedAt == nil || tk.LastUsedFrom == "") {
|
||||
t.Errorf("cc-releases last-used not recorded: %+v", tk)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIToken_StoredRowHasNoPlainToken: neither the row nor the database file holds the plain token.
|
||||
// RED-PROOF: store plain instead of HashAPIToken(plain) → FAIL (the file holds it).
|
||||
func TestAPIToken_StoredRowHasNoPlainToken(t *testing.T) {
|
||||
_, st, _, dbPath := tokenServer(t)
|
||||
plain := mintToken(t, st, "x", time.Now().Add(time.Hour), "overview:read")
|
||||
st.Close()
|
||||
secret := plain[len(TokenPrefix):]
|
||||
for _, p := range []string{dbPath, dbPath + "-wal"} {
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if bytes.Contains(b, []byte(secret)) {
|
||||
t.Fatalf("%s holds the plain token", filepath.Base(p))
|
||||
}
|
||||
}
|
||||
// Positive control: the hash IS stored (so the scan above looked at the bytes the row lives in).
|
||||
var found bool
|
||||
for _, p := range []string{dbPath, dbPath + "-wal"} {
|
||||
if b, err := os.ReadFile(p); err == nil && bytes.Contains(b, []byte(store.HashAPIToken(plain))) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("positive control failed: the token hash is in neither the db nor its wal")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToken_CSRFRuleUnchangedForBasic: Basic without the operator header is still refused on a POST; with it, it
|
||||
// passes; a session without its form token is still refused. Only the token path skips the form token.
|
||||
func TestToken_CSRFRuleUnchangedForBasic(t *testing.T) {
|
||||
s, st, _, _ := tokenServer(t)
|
||||
form := url.Values{"min_controller_version": {"0.301.0"}, "min_agent": {"0.150.0"}}
|
||||
r := tokenReq(http.MethodPost, "/configuration/global-floor", "", form)
|
||||
r.SetBasicAuth("", "operator-pw")
|
||||
if w := serve(s, r); w.Code != http.StatusForbidden {
|
||||
t.Errorf("Basic without %s: %d, want 403", OperatorCLIHeader, w.Code)
|
||||
}
|
||||
r = tokenReq(http.MethodPost, "/configuration/global-floor", "", form)
|
||||
r.SetBasicAuth("", "operator-pw")
|
||||
r.Header.Set(OperatorCLIHeader, "cli")
|
||||
if w := serve(s, r); w.Code != http.StatusSeeOther || st.GetGlobalMinControllerVersion() != "0.301.0" {
|
||||
t.Errorf("Basic with %s: %d floor=%q", OperatorCLIHeader, w.Code, st.GetGlobalMinControllerVersion())
|
||||
}
|
||||
}
|
||||
|
||||
// TestToken_CannotManageTokens: even with every scope, a token cannot create or revoke one (the route is session
|
||||
// only AND the handlers check again).
|
||||
func TestToken_CannotManageTokens(t *testing.T) {
|
||||
s, st, _, _ := tokenServer(t)
|
||||
plain := mintToken(t, st, "all", time.Now().Add(time.Hour), allScopes()...)
|
||||
w := serve(s, tokenReq(http.MethodPost, "/configuration/tokens", plain, url.Values{"name": {"evil"}, "scope": {"vouch:write"}}))
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("token creating a token: %d", w.Code)
|
||||
}
|
||||
// The handler's own check, bypassing the table.
|
||||
r := tokenReq(http.MethodPost, "/configuration/tokens", "", url.Values{"name": {"evil"}, "scope": {"vouch:write"}})
|
||||
tk, _ := st.GetAPITokenByPlain(plain)
|
||||
w = httptest.NewRecorder()
|
||||
s.handleTokenCreate(w, r.WithContext(contextWithToken(r, tk)))
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("handleTokenCreate under a token: %d", w.Code)
|
||||
}
|
||||
list, _ := st.ListAPITokens()
|
||||
if len(list) != 1 {
|
||||
t.Fatalf("a token was created by a token: %d rows", len(list))
|
||||
}
|
||||
}
|
||||
|
||||
func contextWithToken(r *http.Request, tk *store.APIToken) context.Context {
|
||||
return context.WithValue(r.Context(), tokenCtxKey{}, tk)
|
||||
}
|
||||
|
||||
// TestTokenCreate_SessionShowsItOnce: from a session the card creates a token, shows it in this one response
|
||||
// (no-store), stores only its hash, and the token works with exactly the ticked scopes.
|
||||
func TestTokenCreate_SessionShowsItOnce(t *testing.T) {
|
||||
s, st, logs, _ := tokenServer(t)
|
||||
form := url.Values{"name": {"cc-releases"}, "scope": {"overview:read", "floor:write"}, "days": {"90"}}
|
||||
r := tokenReq(http.MethodPost, "/configuration/tokens", "", form)
|
||||
w := httptest.NewRecorder()
|
||||
s.handleTokenCreate(w, r)
|
||||
if w.Code != http.StatusOK || w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("create: %d cache=%q", w.Code, w.Header().Get("Cache-Control"))
|
||||
}
|
||||
body := w.Body.String()
|
||||
i := strings.Index(body, TokenPrefix)
|
||||
if i < 0 {
|
||||
t.Fatal("the new token is not shown")
|
||||
}
|
||||
plain := body[i : i+len(TokenPrefix)+52]
|
||||
if strings.Contains(logs.String(), plain[len(TokenPrefix):]) {
|
||||
t.Fatal("the plain token reached the log")
|
||||
}
|
||||
tk, _ := st.GetAPITokenByPlain(plain)
|
||||
if tk == nil || strings.Join(tk.Scopes, ",") != "overview:read,floor:write" {
|
||||
t.Fatalf("stored token: %+v", tk)
|
||||
}
|
||||
if d := time.Until(tk.ExpiresAt); d < 89*24*time.Hour || d > 91*24*time.Hour {
|
||||
t.Errorf("expiry %v, want ~90 days", d)
|
||||
}
|
||||
// A second render of the page does not show it again.
|
||||
r2 := tokenReq(http.MethodGet, "/configuration", "", nil)
|
||||
w2 := httptest.NewRecorder()
|
||||
s.handleConfiguration(w2, r2)
|
||||
if strings.Contains(w2.Body.String(), plain) {
|
||||
t.Fatal("the token is shown a second time")
|
||||
}
|
||||
if !strings.Contains(w2.Body.String(), "cc-releases") {
|
||||
t.Error("the token list does not name the token")
|
||||
}
|
||||
// Refusals: no scope, unknown scope, never, over a year.
|
||||
for _, bad := range []url.Values{
|
||||
{"name": {"a"}},
|
||||
{"name": {"a"}, "scope": {"tokens:write"}},
|
||||
{"name": {"a"}, "scope": {"overview:read"}, "days": {"0"}},
|
||||
{"name": {"a"}, "scope": {"overview:read"}, "days": {"366"}},
|
||||
{"name": {""}, "scope": {"overview:read"}},
|
||||
} {
|
||||
w := httptest.NewRecorder()
|
||||
s.handleTokenCreate(w, tokenReq(http.MethodPost, "/configuration/tokens", "", bad))
|
||||
if w.Code != http.StatusSeeOther {
|
||||
t.Errorf("bad create %v: %d, want a refusal redirect", bad, w.Code)
|
||||
}
|
||||
}
|
||||
if list, _ := st.ListAPITokens(); len(list) != 1 {
|
||||
t.Errorf("refused creates stored rows: %d", len(list))
|
||||
}
|
||||
}
|
||||
|
||||
// TestRequireAuth_NoPasswordRefusesEveryOperatorRoute: with no operator password anywhere, every operator route
|
||||
// answers 503 — never the page. /bind/ stays public.
|
||||
// RED-PROOF: restore the old `if effectivePasswordHash() == "" { next.ServeHTTP }` → the dashboard answers 200.
|
||||
func TestRequireAuth_NoPasswordRefusesEveryOperatorRoute(t *testing.T) {
|
||||
st, err := store.New(filepath.Join(t.TempDir(), "t.db"), log.New(io.Discard, "", 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { st.Close() })
|
||||
s := New(st, "", "", "test", 30*time.Minute, log.New(io.Discard, "", 0))
|
||||
for _, rs := range routeSamples(t) {
|
||||
if rs.class.Exempt {
|
||||
continue
|
||||
}
|
||||
w := serve(s, tokenReq(rs.method, rs.path, "", url.Values{}))
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Errorf("no password: %s %s → %d, want 503", rs.method, rs.path, w.Code)
|
||||
}
|
||||
}
|
||||
if w := serve(s, tokenReq(http.MethodGet, "/bind/sometoken", "", nil)); w.Code == http.StatusServiceUnavailable {
|
||||
t.Error("the public /bind/ surface must not depend on the operator password")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user