Files
adamfandClaude Opus 5.5 e6a93be15c
Test and publish / test (push) Successful in 25s
Test and publish / publish (push) Successful in 3m1s
Gate the dashboard on the site's admin login and add a setup page
Like job-tracker, the tracker forwards the visitor's cookies to the site
backend's /auth/validate-admin instead of asking for an API key. Signed
in, the dashboard shows every device's data. The new /setup page has
instructions for each collector and creates and revokes API keys. The
userscript is served publicly at /tracker.user.js.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 21:22:02 +01:00

64 lines
1.7 KiB
Go

package auth
import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
)
func TestForward(t *testing.T) {
calls := 0
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
w.Header().Add("Set-Cookie", "access_token=new; Path=/")
if r.Header.Get("Cookie") == "access_token=good" {
w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusForbidden)
}))
defer backend.Close()
f := NewForward(backend.URL, slog.New(slog.NewTextHandler(io.Discard, nil)))
ask := func(cookie string) (bool, *httptest.ResponseRecorder) {
r := httptest.NewRequest("GET", "/", nil)
if cookie != "" {
r.Header.Set("Cookie", cookie)
}
w := httptest.NewRecorder()
return f.IsAdmin(w, r), w
}
if ok, _ := ask(""); ok || calls != 0 {
t.Fatalf("no cookie: admin=%v calls=%d, want false without asking", ok, calls)
}
ok, w := ask("access_token=bad")
if ok {
t.Fatal("bad cookie accepted")
}
if w.Header().Get("Set-Cookie") == "" {
t.Fatal("Set-Cookie not relayed on refusal")
}
if ok, _ := ask("access_token=good"); !ok {
t.Fatal("good cookie refused")
}
before := calls
if ok, _ := ask("access_token=good"); !ok || calls != before {
t.Fatalf("second good request: admin=%v, backend asked again=%v", ok, calls != before)
}
if ok, _ := ask("access_token=bad"); ok || calls == before {
t.Fatal("refusals must not be cached")
}
}
func TestForwardBackendDown(t *testing.T) {
f := NewForward("http://127.0.0.1:1/auth/validate-admin", slog.New(slog.NewTextHandler(io.Discard, nil)))
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set("Cookie", "access_token=x")
if f.IsAdmin(httptest.NewRecorder(), r) {
t.Fatal("unreachable backend must refuse")
}
}