Debian Codegraph @

pkg/oidc/token.go

raw
1 package oidc
2
3 import (
4 "encoding/json"
5 "os"
6 "time"
7
8 jose "github.com/go-jose/go-jose/v4"
9 "golang.org/x/oauth2"
10
11 "github.com/muhlemmer/gu"
12
13 "github.com/zitadel/oidc/v3/pkg/crypto"
14 )
15
16 const (
17 // BearerToken defines the token_type `Bearer`, which is returned in a successful token response
18 BearerToken = "Bearer"
19
20 PrefixBearer = BearerToken + " "
21 )
22
23 type Tokens[C IDClaims] struct {
24 *oauth2.Token
25 IDTokenClaims C
26 IDToken string
27 }
28
29 // TokenClaims contains the base Claims used all tokens.
30 // It implements OpenID Connect Core 1.0, section 2.
31 // https://openid.net/specs/openid-connect-core-1_0.html#IDToken
32 // And RFC 9068: JSON Web Token (JWT) Profile for OAuth 2.0 Access Tokens,
33 // section 2.2. https://datatracker.ietf.org/doc/html/rfc9068#name-data-structure
34 //
35 // TokenClaims implements the Claims interface,
36 // and can be used to extend larger claim types by embedding.
37 type TokenClaims struct {
38 Issuer string `json:"iss,omitempty"`
39 Subject string `json:"sub,omitempty"`
40 Audience Audience `json:"aud,omitempty"`
41 Expiration Time `json:"exp,omitempty"`
42 IssuedAt Time `json:"iat,omitempty"`
43 AuthTime Time `json:"auth_time,omitempty"`
44 NotBefore Time `json:"nbf,omitempty"`
45 Nonce string `json:"nonce,omitempty"`
46 AuthenticationContextClassReference string `json:"acr,omitempty"`
47 AuthenticationMethodsReferences AuthenticationMethodsReferences `json:"amr,omitempty"`
48 AuthorizedParty string `json:"azp,omitempty"`
49 ClientID string `json:"client_id,omitempty"`
50 JWTID string `json:"jti,omitempty"`
51 Actor *ActorClaims `json:"act,omitempty"`
52
53 // Additional information set by this framework
54 SignatureAlg jose.SignatureAlgorithm `json:"-"`
55 }
56
57 func (c *TokenClaims) GetIssuer() string {
58 return c.Issuer
59 }
60
61 func (c *TokenClaims) GetSubject() string {
62 return c.Subject
63 }
64
65 func (c *TokenClaims) GetAudience() []string {
66 return c.Audience
67 }
68
69 func (c *TokenClaims) GetExpiration() time.Time {
70 return c.Expiration.AsTime()
71 }
72
73 func (c *TokenClaims) GetIssuedAt() time.Time {
74 return c.IssuedAt.AsTime()
75 }
76
77 func (c *TokenClaims) GetNonce() string {
78 return c.Nonce
79 }
80
81 func (c *TokenClaims) GetAuthTime() time.Time {
82 return c.AuthTime.AsTime()
83 }
84
85 func (c *TokenClaims) GetAuthorizedParty() string {
86 return c.AuthorizedParty
87 }
88
89 func (c *TokenClaims) GetSignatureAlgorithm() jose.SignatureAlgorithm {
90 return c.SignatureAlg
91 }
92
93 func (c *TokenClaims) GetAuthenticationContextClassReference() string {
94 return c.AuthenticationContextClassReference
95 }
96
97 func (c *TokenClaims) SetSignatureAlgorithm(algorithm jose.SignatureAlgorithm) {
98 c.SignatureAlg = algorithm
99 }
100
101 type AccessTokenClaims struct {
102 TokenClaims
103 Scopes SpaceDelimitedArray `json:"scope,omitempty"`
104 Claims map[string]any `json:"-"`
105 }
106
107 func NewAccessTokenClaims(issuer, subject string, audience []string, expiration time.Time, jwtid, clientID string, skew time.Duration) *AccessTokenClaims {
108 now := time.Now().UTC().Add(-skew)
109 if len(audience) == 0 {
110 audience = append(audience, clientID)
111 }
112 return &AccessTokenClaims{
113 TokenClaims: TokenClaims{
114 Issuer: issuer,
115 Subject: subject,
116 Audience: audience,
117 Expiration: FromTime(expiration),
118 IssuedAt: FromTime(now),
119 NotBefore: FromTime(now),
120 ClientID: clientID,
121 JWTID: jwtid,
122 },
123 }
124 }
125
126 type atcAlias AccessTokenClaims
127
128 func (a *AccessTokenClaims) MarshalJSON() ([]byte, error) {
129 return mergeAndMarshalClaims((*atcAlias)(a), a.Claims)
130 }
131
132 func (a *AccessTokenClaims) UnmarshalJSON(data []byte) error {
133 return unmarshalJSONMulti(data, (*atcAlias)(a), &a.Claims)
134 }
135
136 // IDTokenClaims extends TokenClaims by further implementing
137 // OpenID Connect Core 1.0, sections 3.1.3.6 (Code flow),
138 // 3.2.2.10 (implicit), 3.3.2.11 (Hybrid) and 5.1 (UserInfo).
139 // https://openid.net/specs/openid-connect-core-1_0.html#toc
140 type IDTokenClaims struct {
141 TokenClaims
142 NotBefore Time `json:"nbf,omitempty"`
143 AccessTokenHash string `json:"at_hash,omitempty"`
144 CodeHash string `json:"c_hash,omitempty"`
145 SessionID string `json:"sid,omitempty"`
146 UserInfoProfile
147 UserInfoEmail
148 UserInfoPhone
149 Address *UserInfoAddress `json:"address,omitempty"`
150 Claims map[string]any `json:"-"`
151 }
152
153 // GetAccessTokenHash implements the IDTokenClaims interface
154 func (t *IDTokenClaims) GetAccessTokenHash() string {
155 return t.AccessTokenHash
156 }
157
158 func (t *IDTokenClaims) SetUserInfo(i *UserInfo) {
159 t.Subject = i.Subject
160 t.UserInfoProfile = i.UserInfoProfile
161 t.UserInfoEmail = i.UserInfoEmail
162 t.UserInfoPhone = i.UserInfoPhone
163 t.Address = i.Address
164 if t.Claims == nil {
165 t.Claims = make(map[string]any, len(t.Claims))
166 }
167 gu.MapMerge(i.Claims, t.Claims)
168 }
169
170 func (t *IDTokenClaims) GetUserInfo() *UserInfo {
171 return &UserInfo{
172 Subject: t.Subject,
173 UserInfoProfile: t.UserInfoProfile,
174 UserInfoEmail: t.UserInfoEmail,
175 UserInfoPhone: t.UserInfoPhone,
176 Address: t.Address,
177 Claims: gu.MapCopy(t.Claims),
178 }
179 }
180
181 func NewIDTokenClaims(issuer, subject string, audience []string, expiration, authTime time.Time, nonce string, acr string, amr []string, clientID string, skew time.Duration) *IDTokenClaims {
182 audience = AppendClientIDToAudience(clientID, audience)
183 return &IDTokenClaims{
184 TokenClaims: TokenClaims{
185 Issuer: issuer,
186 Subject: subject,
187 Audience: audience,
188 Expiration: FromTime(expiration),
189 IssuedAt: FromTime(time.Now().Add(-skew)),
190 AuthTime: FromTime(authTime.Add(-skew)),
191 Nonce: nonce,
192 AuthenticationContextClassReference: acr,
193 AuthenticationMethodsReferences: amr,
194 AuthorizedParty: clientID,
195 ClientID: clientID,
196 },
197 }
198 }
199
200 type itcAlias IDTokenClaims
201
202 func (i *IDTokenClaims) MarshalJSON() ([]byte, error) {
203 return mergeAndMarshalClaims((*itcAlias)(i), i.Claims)
204 }
205
206 func (i *IDTokenClaims) UnmarshalJSON(data []byte) error {
207 return unmarshalJSONMulti(data, (*itcAlias)(i), &i.Claims)
208 }
209
210 // ActorClaims provides the `act` claims used for impersonation or delegation Token Exchange.
211 //
212 // An actor can be nested in case an obtained token is used as actor token to obtain impersonation or delegation.
213 // This allows creating a chain of actors.
214 // See [RFC 8693, section 4.1](https://www.rfc-editor.org/rfc/rfc8693#name-act-actor-claim).
215 type ActorClaims struct {
216 Actor *ActorClaims `json:"act,omitempty"`
217 Issuer string `json:"iss,omitempty"`
218 Subject string `json:"sub,omitempty"`
219 Claims map[string]any `json:"-"`
220 }
221
222 type acAlias ActorClaims
223
224 func (c *ActorClaims) MarshalJSON() ([]byte, error) {
225 return mergeAndMarshalClaims((*acAlias)(c), c.Claims)
226 }
227
228 func (c *ActorClaims) UnmarshalJSON(data []byte) error {
229 return unmarshalJSONMulti(data, (*acAlias)(c), &c.Claims)
230 }
231
232 type AccessTokenResponse struct {
233 AccessToken string `json:"access_token,omitempty" schema:"access_token,omitempty"`
234 TokenType string `json:"token_type,omitempty" schema:"token_type,omitempty"`
235 RefreshToken string `json:"refresh_token,omitempty" schema:"refresh_token,omitempty"`
236 ExpiresIn uint64 `json:"expires_in,omitempty" schema:"expires_in,omitempty"`
237 IDToken string `json:"id_token,omitempty" schema:"id_token,omitempty"`
238 State string `json:"state,omitempty" schema:"state,omitempty"`
239 Scope SpaceDelimitedArray `json:"scope,omitempty" schema:"scope,omitempty"`
240 }
241
242 type JWTProfileAssertionClaims struct {
243 PrivateKeyID string `json:"-"`
244 PrivateKey []byte `json:"-"`
245 Issuer string `json:"iss"`
246 Subject string `json:"sub"`
247 Audience Audience `json:"aud"`
248 Expiration Time `json:"exp"`
249 IssuedAt Time `json:"iat"`
250
251 Claims map[string]any `json:"-"`
252 }
253
254 type jpaAlias JWTProfileAssertionClaims
255
256 func (j *JWTProfileAssertionClaims) MarshalJSON() ([]byte, error) {
257 return mergeAndMarshalClaims((*jpaAlias)(j), j.Claims)
258 }
259
260 func (j *JWTProfileAssertionClaims) UnmarshalJSON(data []byte) error {
261 return unmarshalJSONMulti(data, (*jpaAlias)(j), &j.Claims)
262 }
263
264 func NewJWTProfileAssertionFromKeyJSON(filename string, audience []string, opts ...AssertionOption) (*JWTProfileAssertionClaims, error) {
265 data, err := os.ReadFile(filename)
266 if err != nil {
267 return nil, err
268 }
269 return NewJWTProfileAssertionFromFileData(data, audience, opts...)
270 }
271
272 func NewJWTProfileAssertionStringFromFileData(data []byte, audience []string, opts ...AssertionOption) (string, error) {
273 keyData := new(struct {
274 KeyID string `json:"keyId"`
275 Key string `json:"key"`
276 UserID string `json:"userId"`
277 })
278 err := json.Unmarshal(data, keyData)
279 if err != nil {
280 return "", err
281 }
282 return GenerateJWTProfileToken(NewJWTProfileAssertion(keyData.UserID, keyData.KeyID, audience, []byte(keyData.Key), opts...))
283 }
284
285 func JWTProfileDelegatedSubject(sub string) func(*JWTProfileAssertionClaims) {
286 return func(j *JWTProfileAssertionClaims) {
287 j.Subject = sub
288 }
289 }
290
291 func JWTProfileCustomClaim(key string, value any) func(*JWTProfileAssertionClaims) {
292 return func(j *JWTProfileAssertionClaims) {
293 j.Claims[key] = value
294 }
295 }
296
297 func NewJWTProfileAssertionFromFileData(data []byte, audience []string, opts ...AssertionOption) (*JWTProfileAssertionClaims, error) {
298 keyData := new(struct {
299 KeyID string `json:"keyId"`
300 Key string `json:"key"`
301 UserID string `json:"userId"`
302 })
303 err := json.Unmarshal(data, keyData)
304 if err != nil {
305 return nil, err
306 }
307 return NewJWTProfileAssertion(keyData.UserID, keyData.KeyID, audience, []byte(keyData.Key), opts...), nil
308 }
309
310 type AssertionOption func(*JWTProfileAssertionClaims)
311
312 func NewJWTProfileAssertion(userID, keyID string, audience []string, key []byte, opts ...AssertionOption) *JWTProfileAssertionClaims {
313 j := &JWTProfileAssertionClaims{
314 PrivateKey: key,
315 PrivateKeyID: keyID,
316 Issuer: userID,
317 Subject: userID,
318 IssuedAt: FromTime(time.Now().UTC()),
319 Expiration: FromTime(time.Now().Add(1 * time.Hour).UTC()),
320 Audience: audience,
321 Claims: make(map[string]any),
322 }
323
324 for _, opt := range opts {
325 opt(j)
326 }
327
328 return j
329 }
330
331 func ClaimHash(claim string, sigAlgorithm jose.SignatureAlgorithm) (string, error) {
332 hash, err := crypto.GetHashAlgorithm(sigAlgorithm)
333 if err != nil {
334 return "", err
335 }
336
337 return crypto.HashString(hash, claim, true), nil
338 }
339
340 func AppendClientIDToAudience(clientID string, audience []string) []string {
341 for _, aud := range audience {
342 if aud == clientID {
343 return audience
344 }
345 }
346 return append(audience, clientID)
347 }
348
349 func GenerateJWTProfileToken(assertion *JWTProfileAssertionClaims) (string, error) {
350 privateKey, algorithm, err := crypto.BytesToPrivateKey(assertion.PrivateKey)
351 if err != nil {
352 return "", err
353 }
354 key := jose.SigningKey{
355 Algorithm: algorithm,
356 Key: &jose.JSONWebKey{Key: privateKey, KeyID: assertion.PrivateKeyID},
357 }
358 signer, err := jose.NewSigner(key, &jose.SignerOptions{})
359 if err != nil {
360 return "", err
361 }
362
363 marshalledAssertion, err := json.Marshal(assertion)
364 if err != nil {
365 return "", err
366 }
367 signedAssertion, err := signer.Sign(marshalledAssertion)
368 if err != nil {
369 return "", err
370 }
371 return signedAssertion.CompactSerialize()
372 }
373
374 type TokenExchangeResponse struct {
375 AccessToken string `json:"access_token"` // Can be access token or ID token
376 IssuedTokenType TokenType `json:"issued_token_type"`
377 TokenType string `json:"token_type"`
378 ExpiresIn uint64 `json:"expires_in,omitempty"`
379 Scopes SpaceDelimitedArray `json:"scope,omitempty"`
380 RefreshToken string `json:"refresh_token,omitempty"`
381
382 // IDToken field allows returning an additional ID token
383 // if the requested_token_type was Access Token and scope contained openid.
384 IDToken string `json:"id_token,omitempty"`
385 }
386
387 type LogoutTokenClaims struct {
388 Issuer string `json:"iss,omitempty"`
389 Subject string `json:"sub,omitempty"`
390 Audience Audience `json:"aud,omitempty"`
391 IssuedAt Time `json:"iat,omitempty"`
392 Expiration Time `json:"exp,omitempty"`
393 JWTID string `json:"jti,omitempty"`
394 Events map[string]any `json:"events,omitempty"`
395 SessionID string `json:"sid,omitempty"`
396 Claims map[string]any `json:"-"`
397 }
398
399 type ltcAlias LogoutTokenClaims
400
401 func (i *LogoutTokenClaims) MarshalJSON() ([]byte, error) {
402 return mergeAndMarshalClaims((*ltcAlias)(i), i.Claims)
403 }
404
405 func (i *LogoutTokenClaims) UnmarshalJSON(data []byte) error {
406 return unmarshalJSONMulti(data, (*ltcAlias)(i), &i.Claims)
407 }
408
409 func NewLogoutTokenClaims(issuer, subject string, audience Audience, expiration time.Time, jwtID, sessionID string, skew time.Duration) *LogoutTokenClaims {
410 return &LogoutTokenClaims{
411 Issuer: issuer,
412 Subject: subject,
413 Audience: audience,
414 IssuedAt: FromTime(time.Now().Add(-skew)),
415 Expiration: FromTime(expiration),
416 JWTID: jwtID,
417 Events: map[string]any{
418 "http://schemas.openid.net/event/backchannel-logout": struct{}{},
419 },
420 SessionID: sessionID,
421 }
422 }