Debian Codegraph @

pkg/op/storage.go

raw
1 package op
2
3 import (
4 "context"
5 "errors"
6 "time"
7
8 jose "github.com/go-jose/go-jose/v4"
9 "golang.org/x/text/language"
10
11 "github.com/zitadel/oidc/v3/pkg/oidc"
12 )
13
14 type AuthStorage interface {
15 CreateAuthRequest(context.Context, *oidc.AuthRequest, string) (AuthRequest, error)
16 AuthRequestByID(context.Context, string) (AuthRequest, error)
17 AuthRequestByCode(context.Context, string) (AuthRequest, error)
18 SaveAuthCode(context.Context, string, string) error
19 DeleteAuthRequest(context.Context, string) error
20
21 // The TokenRequest parameter of CreateAccessToken can be any of:
22 //
23 // * TokenRequest as returned by ClientCredentialsStorage.ClientCredentialsTokenRequest,
24 //
25 // * AuthRequest as returned by AuthRequestByID or AuthRequestByCode (above)
26 //
27 // * *oidc.JWTTokenRequest from a JWT that is the assertion value of a JWT Profile
28 // Grant: https://datatracker.ietf.org/doc/html/rfc7523#section-2.1
29 //
30 // * TokenExchangeRequest as returned by ValidateTokenExchangeRequest
31 CreateAccessToken(context.Context, TokenRequest) (accessTokenID string, expiration time.Time, err error)
32
33 // The TokenRequest parameter of CreateAccessAndRefreshTokens can be any of:
34 //
35 // * TokenRequest as returned by ClientCredentialsStorage.ClientCredentialsTokenRequest
36 //
37 // * RefreshTokenRequest as returned by AuthStorage.TokenRequestByRefreshToken
38 //
39 // * AuthRequest as by returned by the AuthRequestByID or AuthRequestByCode (above).
40 // Used for the authorization code flow which requested offline_access scope and
41 // registered the refresh_token grant type in advance
42 //
43 // * TokenExchangeRequest as returned by ValidateTokenExchangeRequest
44 //
45 // CreateAccessAndRefreshToken creates both access and refresh tokens.
46 // The returned refresh token is the actual token value that will be passed
47 // directly to the client. The storage implementation is responsible for
48 // creating the complete refresh token (JWT or opaque format). For refresh tokens,
49 // in either format, the token itself serves as both the identifier and the credential.
50 CreateAccessAndRefreshTokens(ctx context.Context, request TokenRequest, currentRefreshToken string) (accessTokenID string, newRefreshToken string, expiration time.Time, err error)
51 TokenRequestByRefreshToken(ctx context.Context, refreshToken string) (RefreshTokenRequest, error)
52
53 TerminateSession(ctx context.Context, userID string, clientID string) error
54
55 // RevokeToken should revoke a token. In the situation that the original request was to
56 // revoke an access token, then tokenOrTokenID will be a tokenID and userID will be set
57 // but if the original request was for a refresh token, then userID will be empty and
58 // tokenOrTokenID will be the refresh token, not its ID. RevokeToken depends upon GetRefreshTokenInfo
59 // to get information from refresh tokens that are not either "<tokenID>:<userID>" strings
60 // nor JWTs.
61 RevokeToken(ctx context.Context, tokenOrTokenID string, userID string, clientID string) *oidc.Error
62
63 // GetRefreshTokenInfo must return ErrInvalidRefreshToken when presented
64 // with a token that is not a refresh token.
65 GetRefreshTokenInfo(ctx context.Context, clientID string, token string) (userID string, tokenID string, err error)
66
67 SigningKey(context.Context) (SigningKey, error)
68 SignatureAlgorithms(context.Context) ([]jose.SignatureAlgorithm, error)
69 KeySet(context.Context) ([]Key, error)
70 }
71
72 // CanTerminateSessionFromRequest is an optional additional interface that may be implemented by
73 // implementors of Storage as an alternative to TerminateSession of the AuthStorage.
74 // It passes the complete parsed EndSessionRequest to the implementation, which allows access to additional data.
75 // It also allows to modify the uri, which will be used for redirection, (e.g. a UI where the user can consent to the logout)
76 type CanTerminateSessionFromRequest interface {
77 TerminateSessionFromRequest(ctx context.Context, endSessionRequest *EndSessionRequest) (string, error)
78 }
79
80 type ClientCredentialsStorage interface {
81 ClientCredentials(ctx context.Context, clientID, clientSecret string) (Client, error)
82 ClientCredentialsTokenRequest(ctx context.Context, clientID string, scopes []string) (TokenRequest, error)
83 }
84
85 type TokenExchangeStorage interface {
86 // ValidateTokenExchangeRequest will be called to validate parsed (including tokens) Token Exchange Grant request.
87 //
88 // Important validations can include:
89 // - permissions
90 // - set requested token type to some default value if it is empty (rfc 8693 allows it) using SetRequestedTokenType method.
91 // Depending on RequestedTokenType - the following tokens will be issued:
92 // - RefreshTokenType - both access and refresh tokens
93 // - AccessTokenType - only access token
94 // - IDTokenType - only id token
95 // - validation of subject's token type on possibility to be exchanged to the requested token type (according to your requirements)
96 // - scopes (and update them using SetCurrentScopes method)
97 // - set new subject if it differs from exchange subject (impersonation flow)
98 //
99 // Request will include subject's and/or actor's token claims if corresponding tokens are access/id_token issued by op
100 // or third party tokens parsed by TokenExchangeTokensVerifierStorage interface methods.
101 ValidateTokenExchangeRequest(ctx context.Context, request TokenExchangeRequest) error
102
103 // CreateTokenExchangeRequest will be called after parsing and validating token exchange request.
104 // Stored request is not accessed later by op - so it is up to implementer to decide
105 // should this method actually store the request or not (common use case - store for it for audit purposes)
106 CreateTokenExchangeRequest(ctx context.Context, request TokenExchangeRequest) error
107
108 // GetPrivateClaimsFromTokenExchangeRequest will be called during access token creation.
109 // Claims evaluation can be based on all validated request data available, including: scopes, resource, audience, etc.
110 GetPrivateClaimsFromTokenExchangeRequest(ctx context.Context, request TokenExchangeRequest) (claims map[string]any, err error)
111
112 // SetUserinfoFromTokenExchangeRequest will be called during id token creation.
113 // Claims evaluation can be based on all validated request data available, including: scopes, resource, audience, etc.
114 SetUserinfoFromTokenExchangeRequest(ctx context.Context, userinfo *oidc.UserInfo, request TokenExchangeRequest) error
115 }
116
117 // TokenExchangeTokensVerifierStorage is an optional interface used in token exchange process to verify tokens
118 // issued by third-party applications. If interface is not implemented - only tokens issued by op will be exchanged.
119 type TokenExchangeTokensVerifierStorage interface {
120 VerifyExchangeSubjectToken(ctx context.Context, token string, tokenType oidc.TokenType) (tokenIDOrToken string, subject string, tokenClaims map[string]any, err error)
121 VerifyExchangeActorToken(ctx context.Context, token string, tokenType oidc.TokenType) (tokenIDOrToken string, actor string, tokenClaims map[string]any, err error)
122 }
123
124 var ErrInvalidRefreshToken = errors.New("invalid_refresh_token")
125
126 type OPStorage interface {
127 // GetClientByClientID loads a Client. The returned Client is never cached and is only used to
128 // handle the current request.
129 GetClientByClientID(ctx context.Context, clientID string) (Client, error)
130 AuthorizeClientIDSecret(ctx context.Context, clientID, clientSecret string) error
131 // SetUserinfoFromScopes is deprecated and should have an empty implementation for now.
132 // Implement SetUserinfoFromRequest instead.
133 SetUserinfoFromScopes(ctx context.Context, userinfo *oidc.UserInfo, userID, clientID string, scopes []string) error
134 SetUserinfoFromToken(ctx context.Context, userinfo *oidc.UserInfo, tokenID, subject, origin string) error
135 SetIntrospectionFromToken(ctx context.Context, userinfo *oidc.IntrospectionResponse, tokenID, subject, clientID string) error
136 GetPrivateClaimsFromScopes(ctx context.Context, userID, clientID string, scopes []string) (map[string]any, error)
137 GetKeyByIDAndClientID(ctx context.Context, keyID, clientID string) (*jose.JSONWebKey, error)
138 ValidateJWTProfileScopes(ctx context.Context, userID string, scopes []string) ([]string, error)
139 }
140
141 // JWTProfileTokenStorage is an additional, optional storage to implement
142 // implementing it, allows specifying the [AccessTokenType] of the access_token returned form the JWT Profile TokenRequest
143 type JWTProfileTokenStorage interface {
144 JWTProfileTokenType(ctx context.Context, request TokenRequest) (AccessTokenType, error)
145 }
146
147 // CanSetUserinfoFromRequest is an optional additional interface that may be implemented by
148 // implementors of Storage. It allows additional data to be set in id_tokens based on the
149 // request.
150 type CanSetUserinfoFromRequest interface {
151 SetUserinfoFromRequest(ctx context.Context, userinfo *oidc.UserInfo, request IDTokenRequest, scopes []string) error
152 }
153
154 // CanGetPrivateClaimsFromRequest is an optional additional interface that may be implemented by
155 // implementors of Storage. It allows setting the jwt token claims based on the request.
156 type CanGetPrivateClaimsFromRequest interface {
157 GetPrivateClaimsFromRequest(ctx context.Context, request TokenRequest, restrictedScopes []string) (map[string]any, error)
158 }
159
160 // Storage is a required parameter for NewOpenIDProvider(). In addition to the
161 // embedded interfaces below, if the passed Storage implements ClientCredentialsStorage
162 // then the grant type "client_credentials" will be supported. In that case, the access
163 // token returned by CreateAccessToken should be a JWT.
164 // See https://datatracker.ietf.org/doc/html/rfc6749#section-1.3.4 for context.
165 type Storage interface {
166 AuthStorage
167 OPStorage
168 Health(context.Context) error
169 }
170
171 type StorageNotFoundError interface {
172 IsNotFound()
173 }
174
175 type EndSessionRequest struct {
176 UserID string
177 ClientID string
178 IDTokenHintClaims *oidc.IDTokenClaims
179 RedirectURI string
180 LogoutHint string
181 UILocales []language.Tag
182 }
183
184 var ErrDuplicateUserCode = errors.New("user code already exists")
185
186 type DeviceAuthorizationStorage interface {
187 // StoreDeviceAuthorization stores a new device authorization request in the database.
188 // User code will be used by the user to complete the login flow and must be unique.
189 // ErrDuplicateUserCode signals the caller should try again with a new code.
190 //
191 // Note that user codes are low entropy keys and when many exist in the
192 // database, the chance for collisions increases. Therefore, implementers
193 // of this interface must make sure that user codes of expired authentication flows are purged,
194 // after some time.
195 StoreDeviceAuthorization(ctx context.Context, clientID, deviceCode, userCode string, expires time.Time, scopes []string) error
196
197 // GetDeviceAuthorizatonState returns the current state of the device authorization flow in the database.
198 // The method is polled until the authorization is either Completed, Expired or Denied.
199 //
200 // Note: The method name is misspelled ("Authorizaton" instead of "Authorization") and kept for
201 // backward compatibility. A correctly spelled alternative may be introduced in a future major version.
202 GetDeviceAuthorizatonState(ctx context.Context, clientID, deviceCode string) (*DeviceAuthorizationState, error)
203 }
204
205 func assertDeviceStorage(s Storage) (DeviceAuthorizationStorage, error) {
206 storage, ok := s.(DeviceAuthorizationStorage)
207 if !ok {
208 return nil, oidc.ErrUnsupportedGrantType().WithDescription("device_code grant not supported")
209 }
210 return storage, nil
211 }