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]>
228 lines
5.9 KiB
Go
228 lines
5.9 KiB
Go
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
|
|
}
|