Debian Codegraph @

pkg/client/client.go

raw
1 package client
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "log/slog"
9 "net/http"
10 "net/url"
11 "strings"
12 "time"
13
14 "github.com/go-jose/go-jose/v4"
15 "github.com/zitadel/oidc/v3/internal/otel"
16 "golang.org/x/oauth2"
17
18 "github.com/zitadel/oidc/v3/pkg/crypto"
19 httphelper "github.com/zitadel/oidc/v3/pkg/http"
20 "github.com/zitadel/oidc/v3/pkg/oidc"
21 )
22
23 var (
24 Encoder = httphelper.Encoder(oidc.NewEncoder())
25 Tracer = otel.Tracer("github.com/zitadel/oidc/pkg/client")
26 )
27
28 // Deprecated: This interface function Auth() is no longer invoked because it violates
29 // RFC 6749 §2.3: The client MUST NOT use more than one authentication method in each request.
30 //
31 // Configure the OAuth2 endpoint AuthStyle (e.g., oauth2.AuthStyleInHeader)
32 // or use the "authFn" parameter in the related functions for custom needs.
33 type ClientSecretBasicAuthRequest interface {
34 Auth(req *http.Request)
35 }
36
37 // Discover calls the discovery endpoint of the provided issuer and returns its configuration
38 // It accepts an optional argument "wellknownUrl" which can be used to override the discovery endpoint url
39 func Discover(ctx context.Context, issuer string, httpClient *http.Client, wellKnownUrl ...string) (*oidc.DiscoveryConfiguration, error) {
40 ctx, span := Tracer.Start(ctx, "Discover")
41 defer span.End()
42
43 wellKnown := strings.TrimSuffix(issuer, "/") + oidc.DiscoveryEndpoint
44 if len(wellKnownUrl) == 1 && wellKnownUrl[0] != "" {
45 wellKnown = wellKnownUrl[0]
46 }
47 req, err := http.NewRequestWithContext(ctx, http.MethodGet, wellKnown, nil)
48 if err != nil {
49 return nil, err
50 }
51 discoveryConfig := new(oidc.DiscoveryConfiguration)
52 err = httphelper.HttpRequest(httpClient, req, &discoveryConfig)
53 if err != nil {
54 return nil, errors.Join(oidc.ErrDiscoveryFailed, err)
55 }
56 slog.DebugContext(ctx, "discover", "config", discoveryConfig)
57
58 if discoveryConfig.Issuer != issuer {
59 return nil, oidc.ErrIssuerInvalid
60 }
61 return discoveryConfig, nil
62 }
63
64 type TokenEndpointCaller interface {
65 TokenEndpoint() string
66 HttpClient() *http.Client
67 }
68
69 func CallTokenEndpoint(ctx context.Context, request any, caller TokenEndpointCaller) (newToken *oauth2.Token, err error) {
70 return CallTokenEndpointWithAuthFn(ctx, request, nil, caller)
71 }
72
73 func CallTokenEndpointWithAuthFn(ctx context.Context, request any, authFn any, caller TokenEndpointCaller) (newToken *oauth2.Token, err error) {
74 ctx, span := Tracer.Start(ctx, "callTokenEndpoint")
75 defer span.End()
76
77 req, err := httphelper.FormRequest(ctx, caller.TokenEndpoint(), request, Encoder, authFn)
78 if err != nil {
79 return nil, err
80 }
81
82 tokenRes := new(oidc.AccessTokenResponse)
83 if err := httphelper.HttpRequest(caller.HttpClient(), req, &tokenRes); err != nil {
84 return nil, err
85 }
86 token := &oauth2.Token{
87 AccessToken: tokenRes.AccessToken,
88 TokenType: tokenRes.TokenType,
89 RefreshToken: tokenRes.RefreshToken,
90 Expiry: time.Now().UTC().Add(time.Duration(tokenRes.ExpiresIn) * time.Second),
91 }
92 if tokenRes.IDToken != "" {
93 token = token.WithExtra(map[string]any{
94 "id_token": tokenRes.IDToken,
95 })
96 }
97 return token, nil
98 }
99
100 type EndSessionCaller interface {
101 GetEndSessionEndpoint() string
102 HttpClient() *http.Client
103 }
104
105 func CallEndSessionEndpoint(ctx context.Context, request any, authFn any, caller EndSessionCaller) (*url.URL, error) {
106 ctx, span := Tracer.Start(ctx, "CallEndSessionEndpoint")
107 defer span.End()
108
109 endpoint := caller.GetEndSessionEndpoint()
110 if endpoint == "" {
111 return nil, fmt.Errorf("end session %w", ErrEndpointNotSet)
112 }
113
114 req, err := httphelper.FormRequest(ctx, endpoint, request, Encoder, authFn)
115 if err != nil {
116 return nil, err
117 }
118 client := caller.HttpClient()
119 cl := *client
120 cl.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
121 return http.ErrUseLastResponse
122 }
123 resp, err := cl.Do(req)
124 if err != nil {
125 return nil, err
126 }
127 defer resp.Body.Close()
128 if resp.StatusCode < 200 || resp.StatusCode >= 400 {
129 body, err := io.ReadAll(io.LimitReader(resp.Body, httphelper.MaxResponseBodySize))
130 if err != nil {
131 return nil, err
132 }
133 return nil, fmt.Errorf("EndSession failure, %d status code: %s", resp.StatusCode, string(body))
134 }
135 location, err := resp.Location()
136 if err != nil {
137 if errors.Is(err, http.ErrNoLocation) {
138 return nil, nil
139 }
140 return nil, err
141 }
142 return location, nil
143 }
144
145 type RevokeCaller interface {
146 GetRevokeEndpoint() string
147 HttpClient() *http.Client
148 }
149
150 type RevokeRequest struct {
151 Token string `schema:"token"`
152 TokenTypeHint string `schema:"token_type_hint"`
153 ClientID string `schema:"client_id"`
154 ClientSecret string `schema:"client_secret"`
155 }
156
157 // Deprecated: This function is no longer invoked because it violates
158 // RFC 6749 §2.3: The client MUST NOT use more than one authentication method in each request.
159 //
160 // Configure the OAuth2 endpoint AuthStyle (e.g., oauth2.AuthStyleInHeader)
161 // or use the "authFn" parameter in the related functions for custom needs.
162 func (r RevokeRequest) Auth(req *http.Request) {
163 if r.ClientSecret != "" {
164 req.SetBasicAuth(url.QueryEscape(r.ClientID), url.QueryEscape(r.ClientSecret))
165 }
166 }
167
168 func CallRevokeEndpoint(ctx context.Context, request any, authFn any, caller RevokeCaller) error {
169 ctx, span := Tracer.Start(ctx, "CallRevokeEndpoint")
170 defer span.End()
171
172 endpoint := caller.GetRevokeEndpoint()
173 if endpoint == "" {
174 return fmt.Errorf("revoke %w", ErrEndpointNotSet)
175 }
176
177 req, err := httphelper.FormRequest(ctx, endpoint, request, Encoder, authFn)
178 if err != nil {
179 return err
180 }
181
182 client := caller.HttpClient()
183 cl := *client
184 cl.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
185 return http.ErrUseLastResponse
186 }
187 resp, err := cl.Do(req)
188 if err != nil {
189 return err
190 }
191 defer resp.Body.Close()
192 // According to RFC7009 in section 2.2:
193 // "The content of the response body is ignored by the client as all
194 // necessary information is conveyed in the response code."
195 if resp.StatusCode != 200 {
196 body, err := io.ReadAll(io.LimitReader(resp.Body, httphelper.MaxResponseBodySize))
197 if err == nil {
198 return fmt.Errorf("revoke returned status %d and text: %s", resp.StatusCode, string(body))
199 } else {
200 return fmt.Errorf("revoke returned status %d", resp.StatusCode)
201 }
202 }
203 return nil
204 }
205
206 func CallTokenExchangeEndpoint(ctx context.Context, request any, authFn any, caller TokenEndpointCaller) (resp *oidc.TokenExchangeResponse, err error) {
207 ctx, span := Tracer.Start(ctx, "CallTokenExchangeEndpoint")
208 defer span.End()
209
210 req, err := httphelper.FormRequest(ctx, caller.TokenEndpoint(), request, Encoder, authFn)
211 if err != nil {
212 return nil, err
213 }
214 tokenRes := new(oidc.TokenExchangeResponse)
215 if err := httphelper.HttpRequest(caller.HttpClient(), req, &tokenRes); err != nil {
216 return nil, err
217 }
218 return tokenRes, nil
219 }
220
221 func NewSignerFromPrivateKeyByte(key []byte, keyID string) (jose.Signer, error) {
222 privateKey, algorithm, err := crypto.BytesToPrivateKey(key)
223 if err != nil {
224 return nil, err
225 }
226 signingKey := jose.SigningKey{
227 Algorithm: algorithm,
228 Key: &jose.JSONWebKey{Key: privateKey, KeyID: keyID},
229 }
230 return jose.NewSigner(signingKey, &jose.SignerOptions{})
231 }
232
233 func SignedJWTProfileAssertion(clientID string, audience []string, expiration time.Duration, signer jose.Signer) (string, error) {
234 iat := time.Now()
235 exp := iat.Add(expiration)
236 return crypto.Sign(&oidc.JWTTokenRequest{
237 Issuer: clientID,
238 Subject: clientID,
239 Audience: audience,
240 ExpiresAt: oidc.FromTime(exp),
241 IssuedAt: oidc.FromTime(iat),
242 }, signer)
243 }
244
245 type DeviceAuthorizationCaller interface {
246 GetDeviceAuthorizationEndpoint() string
247 HttpClient() *http.Client
248 }
249
250 type deviceAuthorizationOptions struct {
251 dpopJKT string
252 }
253
254 type deviceAuthorizationOption func(*deviceAuthorizationOptions)
255
256 func (o deviceAuthorizationOption) apply(options *deviceAuthorizationOptions) {
257 o(options)
258 }
259
260 // DeviceAuthorizationOption configures a device authorization request.
261 //
262 // Experimental: OpenID Connect Key Binding 1.0 is a draft standard.
263 // This API may change or be removed without a major version bump.
264 type DeviceAuthorizationOption interface {
265 apply(*deviceAuthorizationOptions)
266 }
267
268 // WithDPoPJKT adds the `dpop_jkt` parameter from OpenID Connect Key Binding
269 // 1.0, Section 3.1 to a device authorization request.
270 //
271 // Experimental: OpenID Connect Key Binding 1.0 is a draft standard.
272 // This API may change or be removed without a major version bump.
273 func WithDPoPJKT(thumbprint string) DeviceAuthorizationOption {
274 return deviceAuthorizationOption(func(options *deviceAuthorizationOptions) {
275 options.dpopJKT = thumbprint
276 })
277 }
278
279 type deviceAuthorizationRequest struct {
280 *oidc.ClientCredentialsRequest
281 DPoPJKT string `schema:"dpop_jkt,omitempty"`
282 }
283
284 // CallDeviceAuthorizationEndpoint calls the device authorization endpoint.
285 func CallDeviceAuthorizationEndpoint(ctx context.Context, request *oidc.ClientCredentialsRequest, caller DeviceAuthorizationCaller, authFn any, opts ...DeviceAuthorizationOption) (*oidc.DeviceAuthorizationResponse, error) {
286 ctx, span := Tracer.Start(ctx, "CallDeviceAuthorizationEndpoint")
287 defer span.End()
288 options := new(deviceAuthorizationOptions)
289 for _, opt := range opts {
290 opt.apply(options)
291 }
292
293 endpoint := caller.GetDeviceAuthorizationEndpoint()
294 if endpoint == "" {
295 return nil, fmt.Errorf("device authorization %w", ErrEndpointNotSet)
296 }
297
298 req, err := httphelper.FormRequest(ctx, endpoint, &deviceAuthorizationRequest{
299 ClientCredentialsRequest: request,
300 DPoPJKT: options.dpopJKT,
301 }, Encoder, authFn)
302 if err != nil {
303 return nil, err
304 }
305
306 resp := new(oidc.DeviceAuthorizationResponse)
307 if err := httphelper.HttpRequest(caller.HttpClient(), req, &resp); err != nil {
308 return nil, err
309 }
310 return resp, nil
311 }
312
313 type DeviceAccessTokenRequest struct {
314 *oidc.ClientCredentialsRequest
315 oidc.DeviceAccessTokenRequest
316 }
317
318 // Deprecated: This function is no longer invoked because it violates
319 // RFC 6749 §2.3: The client MUST NOT use more than one authentication method in each request.
320 //
321 // Configure the OAuth2 endpoint AuthStyle (e.g., oauth2.AuthStyleInHeader)
322 // or use the "authFn" parameter in the related functions for custom needs.
323 func (r *DeviceAccessTokenRequest) Auth(req *http.Request) {
324 if r.ClientSecret != "" {
325 req.SetBasicAuth(url.QueryEscape(r.ClientID), url.QueryEscape(r.ClientSecret))
326 }
327 }
328
329 // CallDeviceAccessTokenEndpointWithAuthFn calls the device access token endpoint, accepting an authFn for custom authentication.
330 func CallDeviceAccessTokenEndpointWithAuthFn(ctx context.Context, request *DeviceAccessTokenRequest, caller TokenEndpointCaller, authFn any) (*oidc.AccessTokenResponse, error) {
331 ctx, span := Tracer.Start(ctx, "CallDeviceAccessTokenEndpoint")
332 defer span.End()
333
334 req, err := httphelper.FormRequest(ctx, caller.TokenEndpoint(), request, Encoder, authFn)
335 if err != nil {
336 return nil, err
337 }
338
339 resp := new(oidc.AccessTokenResponse)
340 if err := httphelper.HttpRequest(caller.HttpClient(), req, &resp); err != nil {
341 return nil, err
342 }
343 return resp, nil
344 }
345
346 // Deprecated: Use CallDeviceAccessTokenEndpointWithAuthFn instead.
347 func CallDeviceAccessTokenEndpoint(ctx context.Context, request *DeviceAccessTokenRequest, caller TokenEndpointCaller) (*oidc.AccessTokenResponse, error) {
348 return CallDeviceAccessTokenEndpointWithAuthFn(ctx, request, caller, nil)
349 }
350
351 // PollDeviceAccessTokenEndpointWithAuthFn polls the device access token endpoint, accepting an authFn for custom authentication.
352 func PollDeviceAccessTokenEndpointWithAuthFn(ctx context.Context, interval time.Duration, request *DeviceAccessTokenRequest, caller TokenEndpointCaller, authFn any) (*oidc.AccessTokenResponse, error) {
353 ctx, span := Tracer.Start(ctx, "PollDeviceAccessTokenEndpoint")
354 defer span.End()
355
356 for {
357 timer := time.After(interval)
358 select {
359 case <-ctx.Done():
360 return nil, ctx.Err()
361 case <-timer:
362 }
363
364 ctx, cancel := context.WithTimeout(ctx, interval)
365 defer cancel()
366
367 resp, err := CallDeviceAccessTokenEndpointWithAuthFn(ctx, request, caller, authFn)
368 if err == nil {
369 return resp, nil
370 }
371 if errors.Is(err, context.DeadlineExceeded) {
372 interval += 5 * time.Second
373 }
374 var target *oidc.Error
375 if !errors.As(err, &target) {
376 return nil, err
377 }
378 switch target.ErrorType {
379 case oidc.AuthorizationPending:
380 continue
381 case oidc.SlowDown:
382 interval += 5 * time.Second
383 continue
384 default:
385 return nil, err
386 }
387 }
388 }
389
390 // Deprecated: Use PollDeviceAccessTokenEndpointWithAuthFn instead.
391 func PollDeviceAccessTokenEndpoint(ctx context.Context, interval time.Duration, request *DeviceAccessTokenRequest, caller TokenEndpointCaller) (*oidc.AccessTokenResponse, error) {
392 return PollDeviceAccessTokenEndpointWithAuthFn(ctx, interval, request, caller, nil)
393 }