An atproto PDS written in Go
1package dpop 2 3import ( 4 "crypto" 5 "crypto/sha256" 6 "encoding/base64" 7 "encoding/json" 8 "errors" 9 "fmt" 10 "log/slog" 11 "net/http" 12 "net/url" 13 "strings" 14 "time" 15 16 "github.com/golang-jwt/jwt/v4" 17 "github.com/haileyok/cocoon/internal/helpers" 18 "github.com/haileyok/cocoon/oauth/constants" 19 "github.com/lestrrat-go/jwx/v2/jwa" 20 "github.com/lestrrat-go/jwx/v2/jwk" 21) 22 23type Manager struct { 24 nonce *Nonce 25 jtiCache *jtiCache 26 logger *slog.Logger 27 hostname string 28} 29 30type ManagerArgs struct { 31 NonceSecret []byte 32 NonceRotationInterval time.Duration 33 OnNonceSecretCreated func([]byte) 34 JTICacheSize int 35 Logger *slog.Logger 36 Hostname string 37} 38 39func NewManager(args ManagerArgs) *Manager { 40 if args.Logger == nil { 41 args.Logger = slog.Default() 42 } 43 44 if args.JTICacheSize == 0 { 45 args.JTICacheSize = 100_000 46 } 47 48 if args.NonceSecret == nil { 49 args.Logger.Warn("nonce secret passed to dpop manager was nil. existing sessions may break. consider saving and restoring your nonce.") 50 } 51 52 return &Manager{ 53 nonce: NewNonce(NonceArgs{ 54 RotationInterval: args.NonceRotationInterval, 55 Secret: args.NonceSecret, 56 OnSecretCreated: args.OnNonceSecretCreated, 57 }), 58 jtiCache: newJTICache(args.JTICacheSize), 59 logger: args.Logger, 60 hostname: args.Hostname, 61 } 62} 63 64func (dm *Manager) CheckProof(reqMethod, reqUrl string, headers http.Header, accessToken *string) (*Proof, error) { 65 if reqMethod == "" { 66 return nil, errors.New("HTTP method is required") 67 } 68 69 if !strings.HasPrefix(reqUrl, "https://") { 70 reqUrl = "https://" + dm.hostname + reqUrl 71 } 72 73 proof := extractProof(headers) 74 75 if proof == "" { 76 return nil, nil 77 } 78 79 parser := jwt.NewParser(jwt.WithoutClaimsValidation()) 80 var token *jwt.Token 81 82 token, _, err := parser.ParseUnverified(proof, jwt.MapClaims{}) 83 if err != nil { 84 return nil, fmt.Errorf("could not parse dpop proof jwt: %w", err) 85 } 86 87 typ, _ := token.Header["typ"].(string) 88 if typ != "dpop+jwt" { 89 return nil, errors.New(`invalid dpop proof jwt: "typ" must be 'dpop+jwt'`) 90 } 91 92 dpopJwk, jwkOk := token.Header["jwk"].(map[string]any) 93 if !jwkOk { 94 return nil, errors.New(`invalid dpop proof jwt: "jwk" is missing in header`) 95 } 96 97 jwkb, err := json.Marshal(dpopJwk) 98 if err != nil { 99 return nil, fmt.Errorf("failed to marshal jwk: %w", err) 100 } 101 102 key, err := jwk.ParseKey(jwkb) 103 if err != nil { 104 return nil, fmt.Errorf("failed to parse jwk: %w", err) 105 } 106 107 var pubKey any 108 if err := key.Raw(&pubKey); err != nil { 109 return nil, fmt.Errorf("failed to get raw public key: %w", err) 110 } 111 112 token, err = jwt.Parse(proof, func(t *jwt.Token) (any, error) { 113 alg := t.Header["alg"].(string) 114 115 switch key.KeyType() { 116 case jwa.EC: 117 if !strings.HasPrefix(alg, "ES") { 118 return nil, fmt.Errorf("algorithm %s doesn't match EC key type", alg) 119 } 120 case jwa.RSA: 121 if !strings.HasPrefix(alg, "RS") && !strings.HasPrefix(alg, "PS") { 122 return nil, fmt.Errorf("algorithm %s doesn't match RSA key type", alg) 123 } 124 case jwa.OKP: 125 if alg != "EdDSA" { 126 return nil, fmt.Errorf("algorithm %s doesn't match OKP key type", alg) 127 } 128 } 129 130 return pubKey, nil 131 }, jwt.WithValidMethods([]string{"ES256", "ES384", "ES512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "EdDSA"})) 132 if err != nil { 133 return nil, fmt.Errorf("could not verify dpop proof jwt: %w", err) 134 } 135 136 if !token.Valid { 137 return nil, errors.New("dpop proof jwt is invalid") 138 } 139 140 claims, ok := token.Claims.(jwt.MapClaims) 141 if !ok { 142 return nil, errors.New("no claims in dpop proof jwt") 143 } 144 145 iat, iatOk := claims["iat"].(float64) 146 if !iatOk { 147 return nil, errors.New(`invalid dpop proof jwt: "iat" is missing`) 148 } 149 150 iatTime := time.Unix(int64(iat), 0) 151 now := time.Now() 152 153 if now.Sub(iatTime) > constants.DpopNonceMaxAge+constants.DpopCheckTolerance { 154 return nil, errors.New("dpop proof too old") 155 } 156 157 if iatTime.Sub(now) > constants.DpopCheckTolerance { 158 return nil, errors.New("dpop proof iat is in the future") 159 } 160 161 jti, _ := claims["jti"].(string) 162 if jti == "" { 163 return nil, errors.New(`invalid dpop proof jwt: "jti" is missing`) 164 } 165 166 if dm.jtiCache.add(jti) { 167 return nil, errors.New("dpop proof replay detected") 168 } 169 170 htm, _ := claims["htm"].(string) 171 if htm == "" { 172 return nil, errors.New(`invalid dpop proof jwt: "htm" is missing`) 173 } 174 175 if htm != reqMethod { 176 return nil, errors.New(`invalid dpop proof jwt: "htm" mismatch`) 177 } 178 179 htu, _ := claims["htu"].(string) 180 if htu == "" { 181 return nil, errors.New(`invalid dpop proof jwt: "htu" is missing`) 182 } 183 184 parsedHtu, err := helpers.OauthParseHtu(htu) 185 if err != nil { 186 return nil, errors.New(`invalid dpop proof jwt: "htu" could not be parsed`) 187 } 188 189 u, _ := url.Parse(reqUrl) 190 if parsedHtu != helpers.OauthNormalizeHtu(u) { 191 return nil, fmt.Errorf(`invalid dpop proof jwt: "htu" mismatch. reqUrl: %s, parsed: %s, normalized: %s`, reqUrl, parsedHtu, helpers.OauthNormalizeHtu(u)) 192 } 193 194 nonce, _ := claims["nonce"].(string) 195 if nonce == "" { 196 // WARN: this _must_ be `use_dpop_nonce` for clients know they should make another request 197 return nil, errors.New("use_dpop_nonce") 198 } 199 200 if nonce != "" && !dm.nonce.Check(nonce) { 201 // WARN: this _must_ be `use_dpop_nonce` so that clients will fetch a new nonce 202 return nil, errors.New("use_dpop_nonce") 203 } 204 205 ath, _ := claims["ath"].(string) 206 207 if accessToken != nil && *accessToken != "" { 208 if ath == "" { 209 return nil, errors.New(`invalid dpop proof jwt: "ath" is required with access token`) 210 } 211 212 hash := sha256.Sum256([]byte(*accessToken)) 213 if ath != base64.RawURLEncoding.EncodeToString(hash[:]) { 214 return nil, errors.New(`invalid dpop proof jwt: "ath" mismatch`) 215 } 216 } else if ath != "" { 217 return nil, errors.New(`invalid dpop proof jwt: "ath" claim not allowed`) 218 } 219 220 thumbBytes, err := key.Thumbprint(crypto.SHA256) 221 if err != nil { 222 return nil, fmt.Errorf("failed to calculate thumbprint: %w", err) 223 } 224 225 thumb := base64.RawURLEncoding.EncodeToString(thumbBytes) 226 227 return &Proof{ 228 JTI: jti, 229 JKT: thumb, 230 HTM: htm, 231 HTU: htu, 232 }, nil 233} 234 235func extractProof(headers http.Header) string { 236 dpopHeaders := headers["Dpop"] 237 switch len(dpopHeaders) { 238 case 0: 239 return "" 240 case 1: 241 return dpopHeaders[0] 242 default: 243 return "" 244 } 245} 246 247func (dm *Manager) NextNonce() string { 248 return dm.nonce.NextNonce() 249}