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]>
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
// Package auth decides whether a request comes from the site's admin.
|
||||
//
|
||||
// Like the job tracker, the activity tracker has no users or passwords of its
|
||||
// own. It runs behind the main site's nginx at /tracker/ and borrows that
|
||||
// site's session: the browser already carries the site's HTTP-only auth
|
||||
// cookies (Path=/) on every request, so the tracker forwards the Cookie header
|
||||
// to the site backend's GET /auth/validate-admin and treats a 2xx as "admin".
|
||||
// Logging in and out happen on the main site; the tracker only ever asks.
|
||||
//
|
||||
// - validate-admin falls back to the refresh token when the access token has
|
||||
// expired, and answers with fresh cookies. Those Set-Cookie headers are
|
||||
// relayed onto this response, or the browser would keep presenting the
|
||||
// expired token.
|
||||
// - A "yes" is cached for cacheTTL per cookie, so a page that fires several
|
||||
// requests costs one round trip. A refusal is re-asked, so logging in
|
||||
// takes effect at once; logging out takes up to cacheTTL to reach here.
|
||||
//
|
||||
// Collectors don't use this: they authenticate with per-device bearer keys.
|
||||
//
|
||||
// Mode "dev" admits everyone. It exists for the local docker-compose, which
|
||||
// has no site backend to ask, and config refuses it unless DEV_MODE=true.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// cacheTTL is how long a "yes" from the site backend is trusted.
|
||||
const cacheTTL = 30 * time.Second
|
||||
|
||||
// Checker answers whether the request is the admin's. It may write headers
|
||||
// (the relayed Set-Cookie) onto w, which is why it gets the writer.
|
||||
type Checker interface {
|
||||
IsAdmin(w http.ResponseWriter, r *http.Request) bool
|
||||
}
|
||||
|
||||
// AllowAll is the "dev" mode checker.
|
||||
type AllowAll struct{}
|
||||
|
||||
func (AllowAll) IsAdmin(http.ResponseWriter, *http.Request) bool { return true }
|
||||
|
||||
// Forward asks the site backend at URL, forwarding the request's cookies.
|
||||
type Forward struct {
|
||||
URL string
|
||||
Client *http.Client
|
||||
Log *slog.Logger
|
||||
|
||||
mu sync.Mutex
|
||||
cache map[string]time.Time // sha256(Cookie header) -> when it was confirmed
|
||||
}
|
||||
|
||||
// NewForward builds a Forward checker for validateURL, normally
|
||||
// http://backend:8080/auth/validate-admin on the Docker network.
|
||||
func NewForward(validateURL string, log *slog.Logger) *Forward {
|
||||
return &Forward{
|
||||
URL: validateURL,
|
||||
// Short: a backend that doesn't answer in a few seconds should be a
|
||||
// refusal, not a hang.
|
||||
Client: &http.Client{Timeout: 5 * time.Second},
|
||||
Log: log,
|
||||
cache: map[string]time.Time{},
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Forward) IsAdmin(w http.ResponseWriter, r *http.Request) bool {
|
||||
cookie := r.Header.Get("Cookie")
|
||||
if cookie == "" {
|
||||
return false
|
||||
}
|
||||
sum := sha256.Sum256([]byte(cookie))
|
||||
key := hex.EncodeToString(sum[:])
|
||||
|
||||
f.mu.Lock()
|
||||
confirmed, ok := f.cache[key]
|
||||
f.mu.Unlock()
|
||||
if ok && time.Since(confirmed) < cacheTTL {
|
||||
return true
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, f.URL, nil)
|
||||
if err != nil {
|
||||
f.Log.Error("building validate request", "err", err)
|
||||
return false
|
||||
}
|
||||
req.Header.Set("Cookie", cookie)
|
||||
resp, err := f.Client.Do(req)
|
||||
if err != nil {
|
||||
f.Log.Error("site backend unreachable", "err", err)
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Relayed whatever the verdict: a refresh that rotated the cookies is
|
||||
// worth keeping even on a 403.
|
||||
for _, c := range resp.Header.Values("Set-Cookie") {
|
||||
w.Header().Add("Set-Cookie", c)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
return false
|
||||
}
|
||||
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for k, t := range f.cache {
|
||||
if time.Since(t) >= cacheTTL {
|
||||
delete(f.cache, k)
|
||||
}
|
||||
}
|
||||
f.cache[key] = time.Now()
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user