Debian Codegraph @

pkg/op/token_request.go

raw
1 package op
2
3 import (
4 "context"
5 "log/slog"
6 "net/http"
7 "net/url"
8
9 httphelper "github.com/zitadel/oidc/v3/pkg/http"
10 "github.com/zitadel/oidc/v3/pkg/oidc"
11 )
12
13 type Exchanger interface {
14 Storage() Storage
15 Decoder() httphelper.Decoder
16 Crypto() Crypto
17 AuthMethodPostSupported() bool
18 AuthMethodPrivateKeyJWTSupported() bool
19 GrantTypeRefreshTokenSupported() bool
20 GrantTypeTokenExchangeSupported() bool
21 GrantTypeJWTAuthorizationSupported() bool
22 GrantTypeClientCredentialsSupported() bool
23 GrantTypeDeviceCodeSupported() bool
24 AccessTokenVerifier(context.Context) *AccessTokenVerifier
25 IDTokenHintVerifier(context.Context) *IDTokenHintVerifier
26 // Deprecated: configure logging with slog.SetDefault.
27 Logger() *slog.Logger
28 }
29
30 func tokenHandler(exchanger Exchanger) func(w http.ResponseWriter, r *http.Request) {
31 return func(w http.ResponseWriter, r *http.Request) {
32 ctx, span := Tracer.Start(r.Context(), "tokenHandler")
33 defer span.End()
34
35 Exchange(w, r.WithContext(ctx), exchanger)
36 }
37 }
38
39 // Exchange performs a token exchange appropriate for the grant type
40 func Exchange(w http.ResponseWriter, r *http.Request, exchanger Exchanger) {
41 ctx, span := Tracer.Start(r.Context(), "Exchange")
42 r = r.WithContext(ctx)
43 defer span.End()
44
45 grantType := r.FormValue("grant_type")
46 switch grantType {
47 case string(oidc.GrantTypeCode):
48 CodeExchange(w, r, exchanger)
49 return
50 case string(oidc.GrantTypeRefreshToken):
51 if exchanger.GrantTypeRefreshTokenSupported() {
52 RefreshTokenExchange(w, r, exchanger)
53 return
54 }
55 case string(oidc.GrantTypeBearer):
56 if ex, ok := exchanger.(JWTAuthorizationGrantExchanger); ok && exchanger.GrantTypeJWTAuthorizationSupported() {
57 JWTProfile(w, r, ex)
58 return
59 }
60 case string(oidc.GrantTypeTokenExchange):
61 if exchanger.GrantTypeTokenExchangeSupported() {
62 TokenExchange(w, r, exchanger)
63 return
64 }
65 case string(oidc.GrantTypeClientCredentials):
66 if exchanger.GrantTypeClientCredentialsSupported() {
67 ClientCredentialsExchange(w, r, exchanger)
68 return
69 }
70 case string(oidc.GrantTypeDeviceCode):
71 if exchanger.GrantTypeDeviceCodeSupported() {
72 DeviceAccessToken(w, r, exchanger)
73 return
74 }
75 case "":
76 RequestError(w, r, oidc.ErrInvalidRequest().WithDescription("grant_type missing"), nil)
77 return
78 }
79 RequestError(w, r, oidc.ErrUnsupportedGrantType().WithDescription("%s not supported", grantType), nil)
80 }
81
82 // AuthenticatedTokenRequest is a helper interface for ParseAuthenticatedTokenRequest
83 // it is implemented by oidc.AuthRequest and oidc.RefreshTokenRequest
84 type AuthenticatedTokenRequest interface {
85 SetClientID(string)
86 SetClientSecret(string)
87 }
88
89 // AuthenticatedTokenRequestAuthMethodChecker reports which client authentication methods
90 // are present on a token request. It is implemented by oidc.AccessTokenRequest and
91 // oidc.RefreshTokenRequest.
92 //
93 // ParseAuthenticatedTokenRequest uses it to reject requests that combine multiple client
94 // authentication methods, as required by https://datatracker.ietf.org/doc/html/rfc6749#section-2.3:
95 // "The client MUST NOT use more than one authentication method in each request."
96 // Requests that do not implement this interface are not checked.
97 type AuthenticatedTokenRequestAuthMethodChecker interface {
98 IsSetClientAssertion() bool
99 IsSetClientIDAndClientSecret() bool
100 }
101
102 // ParseAuthenticatedTokenRequest parses the client_id and client_secret from the HTTP request from either
103 // HTTP Basic Auth header or form body and sets them into the provided authenticatedTokenRequest interface
104 func ParseAuthenticatedTokenRequest(r *http.Request, decoder httphelper.Decoder, request AuthenticatedTokenRequest) error {
105 ctx, span := Tracer.Start(r.Context(), "ParseAuthenticatedTokenRequest")
106 defer span.End()
107 r = r.WithContext(ctx)
108
109 err := r.ParseForm()
110 if err != nil {
111 return oidc.ErrInvalidRequest().WithDescription("error parsing form").WithParent(err)
112 }
113 err = decoder.Decode(request, r.Form)
114 if err != nil {
115 return oidc.ErrInvalidRequest().WithDescription("error decoding form").WithParent(err)
116 }
117
118 var clientID, clientSecret string
119 if checker, ok := request.(AuthenticatedTokenRequestAuthMethodChecker); ok {
120 // https://datatracker.ietf.org/doc/html/rfc6749#section-2.3
121 // The client MUST NOT use more than one authentication method in each request.
122 if checker.IsSetClientAssertion() && checker.IsSetClientIDAndClientSecret() {
123 return oidc.ErrInvalidRequest().WithDescription("client authentication must not use more than one method")
124 }
125 var ok bool
126 clientID, clientSecret, ok = r.BasicAuth()
127 if !ok {
128 return nil
129 }
130 if checker.IsSetClientAssertion() || checker.IsSetClientIDAndClientSecret() {
131 return oidc.ErrInvalidRequest().WithDescription("client authentication must not use more than one method")
132 }
133 } else {
134 var ok bool
135 clientID, clientSecret, ok = r.BasicAuth()
136 if !ok {
137 return nil
138 }
139 }
140
141 clientID, err = url.QueryUnescape(clientID)
142 if err != nil {
143 return oidc.ErrInvalidClient().WithDescription("invalid basic auth header").WithParent(err)
144 }
145 clientSecret, err = url.QueryUnescape(clientSecret)
146 if err != nil {
147 return oidc.ErrInvalidClient().WithDescription("invalid basic auth header").WithParent(err)
148 }
149 request.SetClientID(clientID)
150 request.SetClientSecret(clientSecret)
151 return nil
152 }
153
154 // AuthorizeClientIDSecret authorizes a client by validating the client_id and client_secret (Basic Auth and POST)
155 func AuthorizeClientIDSecret(ctx context.Context, clientID, clientSecret string, storage Storage) error {
156 ctx, span := Tracer.Start(ctx, "AuthorizeClientIDSecret")
157 defer span.End()
158
159 err := storage.AuthorizeClientIDSecret(ctx, clientID, clientSecret)
160 if err != nil {
161 return oidc.ErrInvalidClient().WithDescription("invalid client_id / client_secret").WithParent(err)
162 }
163 return nil
164 }
165
166 // AuthorizeCodeChallenge authorizes a client by validating the code_verifier against the previously sent
167 // code_challenge of the auth request (PKCE)
168 func AuthorizeCodeChallenge(codeVerifier string, challenge *oidc.CodeChallenge) error {
169 if challenge == nil {
170 if codeVerifier != "" {
171 return oidc.ErrInvalidRequest().WithDescription("code_verifier unexpectedly provided")
172 }
173
174 return nil
175 }
176
177 if codeVerifier == "" {
178 return oidc.ErrInvalidRequest().WithDescription("code_verifier required")
179 }
180 if !oidc.VerifyCodeChallenge(challenge, codeVerifier) {
181 return oidc.ErrInvalidGrant().WithDescription("invalid code_verifier")
182 }
183 return nil
184 }
185
186 // AuthorizePrivateJWTKey authorizes a client by validating the client_assertion's signature with a previously
187 // registered public key (JWT Profile)
188 func AuthorizePrivateJWTKey(ctx context.Context, clientAssertion string, exchanger JWTAuthorizationGrantExchanger) (Client, error) {
189 ctx, span := Tracer.Start(ctx, "AuthorizePrivateJWTKey")
190 defer span.End()
191
192 jwtReq, err := VerifyJWTAssertion(ctx, clientAssertion, exchanger.JWTProfileVerifier(ctx))
193 if err != nil {
194 return nil, err
195 }
196 client, err := exchanger.Storage().GetClientByClientID(ctx, jwtReq.Issuer)
197 if err != nil {
198 return nil, err
199 }
200 if client.AuthMethod() != oidc.AuthMethodPrivateKeyJWT {
201 return nil, oidc.ErrInvalidClient()
202 }
203 return client, nil
204 }
205
206 // ValidateGrantType ensures that the requested grant_type is allowed by the client
207 func ValidateGrantType(client interface{ GrantTypes() []oidc.GrantType }, grantType oidc.GrantType) bool {
208 if client == nil {
209 return false
210 }
211 for _, grant := range client.GrantTypes() {
212 if grantType == grant {
213 return true
214 }
215 }
216 return false
217 }