From 179463795b6d9bbd08ade521a0a64aaac59e5a89 Mon Sep 17 00:00:00 2001 From: Adam French Date: Thu, 26 Nov 2026 13:34:03 +0000 Subject: [PATCH] auth: add AUTH_MODE=access (Cloudflare Access JWT) For running behind Cloudflare Access on stppriv, where the main site's cookie is not sent. Verifies Cf-Access-Jwt-Assertion (or the CF_Authorization cookie) as RS256 against the team's certs, with issuer and audience checks. Default mode is still forward. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + cmd/jobtracker/main.go | 15 ++- internal/auth/access.go | 227 +++++++++++++++++++++++++++++++++++ internal/auth/access_test.go | 183 ++++++++++++++++++++++++++++ 4 files changed, 423 insertions(+), 4 deletions(-) create mode 100644 internal/auth/access.go create mode 100644 internal/auth/access_test.go diff --git a/README.md b/README.md index 345438d..4107080 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,8 @@ There are no accounts here. `internal/auth` forwards the browser's `Cookie` head - **Caching:** a "yes" is cached for 30 seconds per cookie, so logging out takes up to 30 seconds to reach the tracker. - **Lapsed session:** the SPA sends the browser to the site's `/admin/login?redirect=/jobs/...` (`web/src/session.js`). +`AUTH_MODE=access` is for running behind Cloudflare Access (stppriv, `priv./jobs/`), where the site's cookie is not sent. It verifies the `Cf-Access-Jwt-Assertion` header (or the `CF_Authorization` cookie) as an RS256 JWT against `https://$ACCESS_TEAM_DOMAIN/cdn-cgi/access/certs`, with issuer `https://$ACCESS_TEAM_DOMAIN` and audience `$ACCESS_AUD`. Keys are cached for an hour. A lapsed session still sends the SPA to `/admin/login`, which stppriv serves as a "log in again" page. + `AUTH_MODE=dev` admits everyone, for the standalone compose. It is refused unless `DEV_MODE=true`. ## Development diff --git a/cmd/jobtracker/main.go b/cmd/jobtracker/main.go index a4433fd..ff66807 100644 --- a/cmd/jobtracker/main.go +++ b/cmd/jobtracker/main.go @@ -50,13 +50,20 @@ func main() { // AUTH // Settled before anything else, so a bad mode fails fast. - // "forward" (the default) asks the main site; "dev" admits everyone and - // is refused outside DEV_MODE, so a stray setting cannot open the - // tracker in production. + // "forward" (the default) asks the main site; "access" verifies the + // Cloudflare Access JWT (on stppriv, where the main site's cookie is not + // sent); "dev" admits everyone and is refused outside DEV_MODE, so a + // stray setting cannot open the tracker in production. var checker auth.Checker switch mode := getenv("AUTH_MODE", "forward"); mode { case "forward": checker = auth.NewForward(getenv("AUTH_VALIDATE_URL", "http://backend:8080/auth/validate-admin")) + case "access": + a, err := auth.NewAccess(os.Getenv("ACCESS_TEAM_DOMAIN"), os.Getenv("ACCESS_AUD")) + if err != nil { + log.Fatalf("AUTH_MODE=access: %v", err) + } + checker = a case "dev": if !devMode { log.Fatal("AUTH_MODE=dev is only allowed with DEV_MODE=true") @@ -64,7 +71,7 @@ func main() { log.Println("[Auth] AUTH_MODE=dev: every request is treated as the admin") checker = auth.AllowAll{} default: - log.Fatalf("unknown AUTH_MODE %q (want forward or dev)", mode) + log.Fatalf("unknown AUTH_MODE %q (want forward, access or dev)", mode) } databaseURL := os.Getenv("DATABASE_URL") diff --git a/internal/auth/access.go b/internal/auth/access.go new file mode 100644 index 0000000..4cfce28 --- /dev/null +++ b/internal/auth/access.go @@ -0,0 +1,227 @@ +package auth + +import ( + "crypto" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "log" + "math/big" + "net/http" + "strings" + "sync" + "time" +) + +// Access is the "access" mode checker: the tracker sits behind Cloudflare +// Access (on stppriv), which has already logged the user in and adds a signed +// JWT to every request it lets through. A valid token for our application is +// the admin; anything else is refused. Checking it here, not only at the +// edge, means a request that reaches the container some other way (a +// misrouted tunnel, a Bypass policy that is too wide) is still refused. +// +// Only RS256 is accepted, which is what Access signs with. The signing keys +// come from https:///cdn-cgi/access/certs and are cached; a token with +// an unknown key id triggers a refetch, at most once per keyRefetchGap, since +// Access rotates its keys. +type Access struct { + Issuer string // https://.cloudflareaccess.com + Audience string // the Access application's AUD tag + CertsURL string + Client *http.Client + now func() time.Time + + mu sync.Mutex + keys map[string]*rsa.PublicKey + fetchedAt time.Time +} + +const ( + keyCacheTTL = time.Hour + keyRefetchGap = 30 * time.Second + accessHeader = "Cf-Access-Jwt-Assertion" + accessCookie = "CF_Authorization" + clockTolerance = 30 * time.Second +) + +// NewAccess builds the checker for teamDomain (e.g. "me.cloudflareaccess.com", +// with or without https://) and the application's audience tag. +func NewAccess(teamDomain, audience string) (*Access, error) { + team := strings.TrimRight(strings.TrimPrefix(strings.TrimPrefix(teamDomain, "https://"), "http://"), "/") + if team == "" || audience == "" { + return nil, errors.New("ACCESS_TEAM_DOMAIN and ACCESS_AUD must both be set") + } + issuer := "https://" + team + return &Access{ + Issuer: issuer, + Audience: audience, + CertsURL: issuer + "/cdn-cgi/access/certs", + Client: &http.Client{Timeout: 5 * time.Second}, + now: time.Now, + }, nil +} + +func (a *Access) IsAdmin(_ http.ResponseWriter, r *http.Request) bool { + token := r.Header.Get(accessHeader) + if token == "" { + if c, err := r.Cookie(accessCookie); err == nil { + token = c.Value + } + } + if token == "" { + return false + } + if err := a.verify(token); err != nil { + log.Printf("[auth] access token refused: %v", err) + return false + } + return true +} + +type jwtHeader struct { + Alg string `json:"alg"` + Kid string `json:"kid"` +} + +type jwtClaims struct { + Iss string `json:"iss"` + Aud json.RawMessage `json:"aud"` // a string or a list of strings + Exp int64 `json:"exp"` + Nbf int64 `json:"nbf"` +} + +func (a *Access) verify(token string) error { + parts := strings.Split(token, ".") + if len(parts) != 3 { + return errors.New("not a JWT") + } + var hdr jwtHeader + if err := decodeSegment(parts[0], &hdr); err != nil { + return fmt.Errorf("header: %w", err) + } + if hdr.Alg != "RS256" { + return fmt.Errorf("alg %q not allowed", hdr.Alg) + } + key, err := a.key(hdr.Kid) + if err != nil { + return err + } + sig, err := base64.RawURLEncoding.DecodeString(parts[2]) + if err != nil { + return fmt.Errorf("signature encoding: %w", err) + } + digest := sha256.Sum256([]byte(parts[0] + "." + parts[1])) + if err := rsa.VerifyPKCS1v15(key, crypto.SHA256, digest[:], sig); err != nil { + return errors.New("bad signature") + } + + var claims jwtClaims + if err := decodeSegment(parts[1], &claims); err != nil { + return fmt.Errorf("claims: %w", err) + } + if claims.Iss != a.Issuer { + return fmt.Errorf("issuer %q", claims.Iss) + } + if !audienceContains(claims.Aud, a.Audience) { + return errors.New("wrong audience") + } + now := a.now() + if claims.Exp == 0 || now.After(time.Unix(claims.Exp, 0).Add(clockTolerance)) { + return errors.New("expired") + } + if claims.Nbf != 0 && now.Add(clockTolerance).Before(time.Unix(claims.Nbf, 0)) { + return errors.New("not yet valid") + } + return nil +} + +func (a *Access) key(kid string) (*rsa.PublicKey, error) { + a.mu.Lock() + defer a.mu.Unlock() + + stale := a.now().Sub(a.fetchedAt) > keyCacheTTL + k, ok := a.keys[kid] + if ok && !stale { + return k, nil + } + if !stale && a.now().Sub(a.fetchedAt) < keyRefetchGap { + return nil, fmt.Errorf("unknown key id %q", kid) + } + keys, err := a.fetchKeys() + if err != nil { + if ok { // keep serving the cached key if the refresh failed + return k, nil + } + return nil, err + } + a.keys, a.fetchedAt = keys, a.now() + if k, ok = keys[kid]; !ok { + return nil, fmt.Errorf("unknown key id %q", kid) + } + return k, nil +} + +func (a *Access) fetchKeys() (map[string]*rsa.PublicKey, error) { + resp, err := a.Client.Get(a.CertsURL) + if err != nil { + return nil, fmt.Errorf("fetching access certs: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("fetching access certs: status %d", resp.StatusCode) + } + var body struct { + Keys []struct { + Kid string `json:"kid"` + Kty string `json:"kty"` + N string `json:"n"` + E string `json:"e"` + } `json:"keys"` + } + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + return nil, fmt.Errorf("decoding access certs: %w", err) + } + keys := map[string]*rsa.PublicKey{} + for _, k := range body.Keys { + if k.Kty != "RSA" { + continue + } + n, err1 := base64.RawURLEncoding.DecodeString(k.N) + e, err2 := base64.RawURLEncoding.DecodeString(k.E) + if err1 != nil || err2 != nil { + continue + } + keys[k.Kid] = &rsa.PublicKey{N: new(big.Int).SetBytes(n), E: int(new(big.Int).SetBytes(e).Int64())} + } + if len(keys) == 0 { + return nil, errors.New("access certs contained no RSA keys") + } + return keys, nil +} + +func decodeSegment(seg string, v any) error { + b, err := base64.RawURLEncoding.DecodeString(seg) + if err != nil { + return err + } + return json.Unmarshal(b, v) +} + +func audienceContains(raw json.RawMessage, want string) bool { + var one string + if json.Unmarshal(raw, &one) == nil { + return one == want + } + var many []string + if json.Unmarshal(raw, &many) == nil { + for _, a := range many { + if a == want { + return true + } + } + } + return false +} diff --git a/internal/auth/access_test.go b/internal/auth/access_test.go new file mode 100644 index 0000000..3780626 --- /dev/null +++ b/internal/auth/access_test.go @@ -0,0 +1,183 @@ +package auth + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "math/big" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +const testAud = "aud-tag-123" + +type accessFixture struct { + key *rsa.PrivateKey + kid string + server *httptest.Server + fetches atomic.Int32 + checker *Access +} + +func newAccessFixture(t *testing.T) *accessFixture { + t.Helper() + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + f := &accessFixture{key: key, kid: "k1"} + f.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f.fetches.Add(1) + b64 := base64.RawURLEncoding.EncodeToString + json.NewEncoder(w).Encode(map[string]any{"keys": []map[string]string{{ + "kid": f.kid, "kty": "RSA", + "n": b64(key.N.Bytes()), + "e": b64(big.NewInt(int64(key.E)).Bytes()), + }}}) + })) + t.Cleanup(f.server.Close) + + c, err := NewAccess("team.example.com", testAud) + if err != nil { + t.Fatal(err) + } + c.CertsURL = f.server.URL + f.checker = c + return f +} + +func (f *accessFixture) sign(t *testing.T, alg, kid string, claims map[string]any) string { + t.Helper() + enc := func(v any) string { + b, _ := json.Marshal(v) + return base64.RawURLEncoding.EncodeToString(b) + } + signing := enc(map[string]string{"alg": alg, "kid": kid}) + "." + enc(claims) + digest := sha256.Sum256([]byte(signing)) + sig, err := rsa.SignPKCS1v15(rand.Reader, f.key, crypto.SHA256, digest[:]) + if err != nil { + t.Fatal(err) + } + return signing + "." + base64.RawURLEncoding.EncodeToString(sig) +} + +func goodClaims() map[string]any { + return map[string]any{ + "iss": "https://team.example.com", + "aud": []string{testAud}, + "exp": time.Now().Add(time.Hour).Unix(), + "nbf": time.Now().Add(-time.Minute).Unix(), + } +} + +func reqWithHeader(token string) *http.Request { + r := httptest.NewRequest(http.MethodGet, "/jobs/", nil) + if token != "" { + r.Header.Set(accessHeader, token) + } + return r +} + +func TestAccessAcceptsValidToken(t *testing.T) { + f := newAccessFixture(t) + if !f.checker.IsAdmin(httptest.NewRecorder(), reqWithHeader(f.sign(t, "RS256", f.kid, goodClaims()))) { + t.Fatal("valid token refused") + } +} + +func TestAccessAcceptsCookie(t *testing.T) { + f := newAccessFixture(t) + r := reqWithHeader("") + r.AddCookie(&http.Cookie{Name: accessCookie, Value: f.sign(t, "RS256", f.kid, goodClaims())}) + if !f.checker.IsAdmin(httptest.NewRecorder(), r) { + t.Fatal("valid cookie refused") + } +} + +func TestAccessAcceptsStringAudience(t *testing.T) { + f := newAccessFixture(t) + c := goodClaims() + c["aud"] = testAud + if !f.checker.IsAdmin(httptest.NewRecorder(), reqWithHeader(f.sign(t, "RS256", f.kid, c))) { + t.Fatal("string aud refused") + } +} + +func TestAccessRefuses(t *testing.T) { + f := newAccessFixture(t) + other, _ := rsa.GenerateKey(rand.Reader, 2048) + + cases := map[string]func() string{ + "no token": func() string { return "" }, + "garbage": func() string { return "a.b.c" }, + "wrong audience": func() string { + c := goodClaims() + c["aud"] = []string{"someone-else"} + return f.sign(t, "RS256", f.kid, c) + }, + "wrong issuer": func() string { + c := goodClaims() + c["iss"] = "https://evil.example.com" + return f.sign(t, "RS256", f.kid, c) + }, + "expired": func() string { + c := goodClaims() + c["exp"] = time.Now().Add(-time.Hour).Unix() + return f.sign(t, "RS256", f.kid, c) + }, + "not yet valid": func() string { + c := goodClaims() + c["nbf"] = time.Now().Add(time.Hour).Unix() + return f.sign(t, "RS256", f.kid, c) + }, + "alg none": func() string { return f.sign(t, "none", f.kid, goodClaims()) }, + "unknown kid": func() string { return f.sign(t, "RS256", "k2", goodClaims()) }, + "wrong key": func() string { + saved := f.key + f.key = other + defer func() { f.key = saved }() + return f.sign(t, "RS256", f.kid, goodClaims()) + }, + } + for name, mk := range cases { + t.Run(name, func(t *testing.T) { + if f.checker.IsAdmin(httptest.NewRecorder(), reqWithHeader(mk())) { + t.Fatal("accepted") + } + }) + } +} + +func TestAccessCachesKeys(t *testing.T) { + f := newAccessFixture(t) + tok := f.sign(t, "RS256", f.kid, goodClaims()) + for i := 0; i < 5; i++ { + f.checker.IsAdmin(httptest.NewRecorder(), reqWithHeader(tok)) + } + // Unknown kids right after a fetch must not hammer the certs endpoint. + for i := 0; i < 5; i++ { + f.checker.IsAdmin(httptest.NewRecorder(), reqWithHeader(f.sign(t, "RS256", "nope", goodClaims()))) + } + if n := f.fetches.Load(); n != 1 { + t.Fatalf("certs fetched %d times, want 1", n) + } +} + +func TestNewAccessNeedsConfig(t *testing.T) { + if _, err := NewAccess("", testAud); err == nil { + t.Fatal("empty team accepted") + } + if _, err := NewAccess("team.example.com", ""); err == nil { + t.Fatal("empty aud accepted") + } + c, _ := NewAccess("https://team.example.com/", testAud) + if c.Issuer != "https://team.example.com" { + t.Fatalf("issuer %q", c.Issuer) + } +}