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:
@@ -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://<team>/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://<team>.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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user