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