Debian Codegraph @

pkg/oidc/verifier.go

raw
1 package oidc
2
3 import (
4 "bytes"
5 "context"
6 "encoding/base64"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "slices"
11 "strings"
12 "time"
13
14 jose "github.com/go-jose/go-jose/v4"
15 )
16
17 type Claims interface {
18 GetIssuer() string
19 GetSubject() string
20 GetAudience() []string
21 GetExpiration() time.Time
22 GetIssuedAt() time.Time
23 GetNonce() string
24 GetAuthenticationContextClassReference() string
25 GetAuthTime() time.Time
26 GetAuthorizedParty() string
27 ClaimsSignature
28 }
29
30 type ClaimsSignature interface {
31 SetSignatureAlgorithm(algorithm jose.SignatureAlgorithm)
32 }
33
34 type IDClaims interface {
35 Claims
36 GetSignatureAlgorithm() jose.SignatureAlgorithm
37 GetAccessTokenHash() string
38 }
39
40 var (
41 ErrParse = errors.New("parsing of request failed")
42 ErrIssuerInvalid = errors.New("issuer does not match")
43 ErrDiscoveryFailed = errors.New("OpenID Provider Configuration Discovery has failed")
44 ErrSubjectMissing = errors.New("subject missing")
45 ErrSubjectInvalid = errors.New("delegation not allowed, issuer and sub must be identical")
46 ErrAudience = errors.New("audience is not valid")
47 ErrAzpMissing = errors.New("authorized party is not set. If Token is valid for multiple audiences, azp must not be empty")
48 ErrAzpInvalid = errors.New("authorized party is not valid")
49 ErrSignatureMissing = errors.New("id_token does not contain a signature")
50 ErrSignatureMultiple = errors.New("id_token contains multiple signatures")
51 ErrSignatureUnsupportedAlg = errors.New("signature algorithm not supported")
52 ErrSignatureInvalidPayload = errors.New("signature does not match Payload")
53 ErrSignatureInvalid = errors.New("invalid signature")
54 ErrExpired = errors.New("token has expired")
55 ErrIatMissing = errors.New("issuedAt of token is missing")
56 ErrIatInFuture = errors.New("issuedAt of token is in the future")
57 ErrIatToOld = errors.New("issuedAt of token is to old")
58 ErrNonceInvalid = errors.New("nonce does not match")
59 ErrAcrInvalid = errors.New("acr is invalid")
60 ErrAuthTimeNotPresent = errors.New("claim `auth_time` of token is missing")
61 ErrAuthTimeToOld = errors.New("auth time of token is too old")
62 ErrAtHash = errors.New("at_hash does not correspond to access token")
63 )
64
65 // Verifier caries configuration for the various token verification
66 // functions. Use package specific constructor functions to know
67 // which values need to be set.
68 type Verifier struct {
69 Issuer string
70 ISS ISSVerifier
71 MaxAgeIAT time.Duration
72 Offset time.Duration
73 ClientID string
74 SupportedSignAlgs []string
75 MaxAge time.Duration
76 ACR ACRVerifier
77 AZP AZPVerifier
78 KeySet KeySet
79 Nonce func(ctx context.Context) string
80 }
81
82 // ISSVerifier specifies the function to be used by the `DefaultVerifier` for validating the iss claim
83 type ISSVerifier func(string) error
84
85 // DefaultISSVerifier implements `ISSVerifier` returning an error
86 // if the iss claim doesn't match the expected issuer.
87 func DefaultISSVerifier(expectIssuer string) ISSVerifier {
88 return func(inputIssuer string) error {
89 if inputIssuer != expectIssuer {
90 return fmt.Errorf("%w: expected: %s, got: %s", ErrIssuerInvalid, expectIssuer, inputIssuer)
91 }
92 return nil
93 }
94 }
95
96 // ACRVerifier specifies the function to be used by the `DefaultVerifier` for validating the acr claim
97 type ACRVerifier func(string) error
98
99 // DefaultACRVerifier implements `ACRVerifier` returning an error
100 // if none of the provided values matches the acr claim
101 func DefaultACRVerifier(possibleValues []string) ACRVerifier {
102 return func(acr string) error {
103 if !slices.Contains(possibleValues, acr) {
104 return fmt.Errorf("expected one of: %v, got: %q", possibleValues, acr)
105 }
106 return nil
107 }
108 }
109
110 func DecryptToken(tokenString string) (string, error) {
111 return tokenString, nil // TODO: impl
112 }
113
114 func ParseToken(tokenString string, claims any) ([]byte, error) {
115 parts := strings.Split(tokenString, ".")
116 if len(parts) != 3 {
117 return nil, fmt.Errorf("%w: token contains an invalid number of segments", ErrParse)
118 }
119 payload, err := base64.RawURLEncoding.DecodeString(parts[1])
120 if err != nil {
121 return nil, fmt.Errorf("%w: malformed jwt payload: %v", ErrParse, err)
122 }
123 err = json.Unmarshal(payload, claims)
124 return payload, err
125 }
126
127 func CheckSubject(claims Claims) error {
128 if claims.GetSubject() == "" {
129 return ErrSubjectMissing
130 }
131 return nil
132 }
133
134 // Deprecated: Use CheckIssuerWithISSVerifier instead
135 func CheckIssuer(claims Claims, issuer string) error {
136 if claims.GetIssuer() != issuer {
137 return fmt.Errorf("%w: Expected: %s, got: %s", ErrIssuerInvalid, issuer, claims.GetIssuer())
138 }
139 return nil
140 }
141
142 func CheckIssuerWithISSVerifier(claims Claims, issuer string, issVerifier ISSVerifier) error {
143 if issVerifier == nil {
144 return DefaultISSVerifier(issuer)(claims.GetIssuer())
145 }
146 return issVerifier(claims.GetIssuer())
147 }
148
149 func CheckAudience(claims Claims, clientID string) error {
150 if !slices.Contains(claims.GetAudience(), clientID) {
151 return fmt.Errorf("%w: Audience must contain client_id %q", ErrAudience, clientID)
152 }
153
154 // TODO: check aud trusted
155 return nil
156 }
157
158 // AZPVerifier specifies the function to be used by the `DefaultVerifier` for validating the azp claim
159 type AZPVerifier func(string) error
160
161 // DefaultAZPVerifier implements `AZPVerifier` returning an error
162 // if the azp claim is set and doesn't match the clientID.
163 func DefaultAZPVerifier(clientID string) AZPVerifier {
164 return func(azp string) error {
165 if azp != "" && azp != clientID {
166 return fmt.Errorf("%w: azp %q must be equal to client_id %q", ErrAzpInvalid, azp, clientID)
167 }
168 return nil
169 }
170 }
171
172 // CheckAuthorizedParty checks azp (authorized party) claim requirements.
173 //
174 // If the ID Token contains multiple audiences, the Client SHOULD verify that an azp Claim is present.
175 // If an azp Claim is present, the Client MAY verify that its client_id is the Claim Value.
176 // https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
177 func CheckAuthorizedParty(claims Claims, clientID string) error {
178 return CheckAZPVerifier(claims, DefaultAZPVerifier(clientID))
179 }
180
181 // CheckAZPVerifier checks azp (authorized party) claim requirements.
182 //
183 // If the ID Token contains multiple audiences, the Client SHOULD verify that an azp Claim is present.
184 // If an azp Claim is present, the Client MAY verify that its client_id is the Claim Value.
185 // https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
186 func CheckAZPVerifier(claims Claims, azp AZPVerifier) error {
187 if len(claims.GetAudience()) > 1 {
188 if claims.GetAuthorizedParty() == "" {
189 return ErrAzpMissing
190 }
191 }
192
193 if err := azp(claims.GetAuthorizedParty()); err != nil {
194 return fmt.Errorf("%w: %v", ErrAzpInvalid, err)
195 }
196 return nil
197 }
198
199 func CheckSignature(ctx context.Context, token string, payload []byte, claims ClaimsSignature, supportedSigAlgs []string, set KeySet) error {
200 jws, err := jose.ParseSigned(token, toJoseSignatureAlgorithms(supportedSigAlgs))
201 if err != nil {
202 var unexpectedSigAlgErr *jose.ErrUnexpectedSignatureAlgorithm
203 if errors.As(err, &unexpectedSigAlgErr) ||
204 errors.Is(err, jose.ErrUnsupportedAlgorithm) {
205 // TODO(v4): we should wrap errors instead of returning static ones.
206 // This is a workaround so we keep returning the same error for now.
207 return ErrSignatureUnsupportedAlg
208 }
209 return ErrParse
210 }
211 if len(jws.Signatures) == 0 {
212 return ErrSignatureMissing
213 }
214 if len(jws.Signatures) > 1 {
215 return ErrSignatureMultiple
216 }
217 sig := jws.Signatures[0]
218
219 signedPayload, err := set.VerifySignature(ctx, jws)
220 if err != nil {
221 return fmt.Errorf("%w (%w)", ErrSignatureInvalid, err)
222 }
223
224 if !bytes.Equal(signedPayload, payload) {
225 return ErrSignatureInvalidPayload
226 }
227
228 claims.SetSignatureAlgorithm(jose.SignatureAlgorithm(sig.Header.Algorithm))
229
230 return nil
231 }
232
233 // TODO(v4): Use the new jose.SignatureAlgorithm type directly, instead of string.
234 func toJoseSignatureAlgorithms(algorithms []string) []jose.SignatureAlgorithm {
235 out := make([]jose.SignatureAlgorithm, len(algorithms))
236 for i := range algorithms {
237 out[i] = jose.SignatureAlgorithm(algorithms[i])
238 }
239 if len(out) == 0 {
240 out = append(out, jose.RS256, jose.ES256, jose.PS256)
241 }
242 return out
243 }
244
245 func CheckExpiration(claims Claims, offset time.Duration) error {
246 expiration := claims.GetExpiration()
247 if !time.Now().Add(offset).Before(expiration) {
248 return ErrExpired
249 }
250 return nil
251 }
252
253 func CheckIssuedAt(claims Claims, maxAgeIAT, offset time.Duration) error {
254 issuedAt := claims.GetIssuedAt()
255 if issuedAt.IsZero() {
256 return ErrIatMissing
257 }
258 nowWithOffset := time.Now().Add(offset).Round(time.Second)
259 if issuedAt.After(nowWithOffset) {
260 return fmt.Errorf("%w: (iat: %v, now with offset: %v)", ErrIatInFuture, issuedAt, nowWithOffset)
261 }
262 if maxAgeIAT == 0 {
263 return nil
264 }
265 maxAge := time.Now().Add(-maxAgeIAT).Round(time.Second)
266 if issuedAt.Before(maxAge) {
267 return fmt.Errorf("%w: must not be older than %v, but was %v (%v to old)", ErrIatToOld, maxAge, issuedAt, maxAge.Sub(issuedAt))
268 }
269 return nil
270 }
271
272 func CheckNonce(claims Claims, nonce string) error {
273 if claims.GetNonce() != nonce {
274 return fmt.Errorf("%w: expected %q but was %q", ErrNonceInvalid, nonce, claims.GetNonce())
275 }
276 return nil
277 }
278
279 func CheckAuthorizationContextClassReference(claims Claims, acr ACRVerifier) error {
280 if acr != nil {
281 if err := acr(claims.GetAuthenticationContextClassReference()); err != nil {
282 return fmt.Errorf("%w: %v", ErrAcrInvalid, err)
283 }
284 }
285 return nil
286 }
287
288 func CheckAuthTime(claims Claims, maxAge time.Duration) error {
289 if maxAge == 0 {
290 return nil
291 }
292 if claims.GetAuthTime().IsZero() {
293 return ErrAuthTimeNotPresent
294 }
295 authTime := claims.GetAuthTime()
296 maxAuthTime := time.Now().Add(-maxAge).Round(time.Second)
297 if authTime.Before(maxAuthTime) {
298 return fmt.Errorf("%w: must not be older than %v, but was %v (%v to old)", ErrAuthTimeToOld, maxAge, authTime, maxAuthTime.Sub(authTime))
299 }
300 return nil
301 }