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 <[email protected]>
This commit is contained in:
2026-11-26 13:34:03 +00:00
co-authored by Claude Opus 5.5
parent acc6876e33
commit 179463795b
4 changed files with 423 additions and 4 deletions
+183
View File
@@ -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)
}
}