Debian Codegraph @

pkg/op/op.go

raw
1 package op
2
3 import (
4 "context"
5 "fmt"
6 "log/slog"
7 "net/http"
8 "net/url"
9 "time"
10
11 "github.com/go-chi/chi/v5"
12 "github.com/go-jose/go-jose/v4"
13 "github.com/rs/cors"
14 "github.com/zitadel/oidc/v3/internal/otel"
15 "github.com/zitadel/schema"
16 "golang.org/x/text/language"
17
18 httphelper "github.com/zitadel/oidc/v3/pkg/http"
19 "github.com/zitadel/oidc/v3/pkg/oidc"
20 )
21
22 const (
23 healthEndpoint = "/healthz"
24 readinessEndpoint = "/ready"
25 authCallbackPathSuffix = "/callback"
26 defaultAuthorizationEndpoint = "authorize"
27 defaultTokenEndpoint = "oauth/token"
28 defaultIntrospectEndpoint = "oauth/introspect"
29 defaultUserinfoEndpoint = "userinfo"
30 defaultRevocationEndpoint = "revoke"
31 defaultEndSessionEndpoint = "end_session"
32 defaultKeysEndpoint = "keys"
33 defaultDeviceAuthzEndpoint = "/device_authorization"
34 )
35
36 var (
37 DefaultEndpoints = &Endpoints{
38 Authorization: NewEndpoint(defaultAuthorizationEndpoint),
39 Token: NewEndpoint(defaultTokenEndpoint),
40 Introspection: NewEndpoint(defaultIntrospectEndpoint),
41 Userinfo: NewEndpoint(defaultUserinfoEndpoint),
42 Revocation: NewEndpoint(defaultRevocationEndpoint),
43 EndSession: NewEndpoint(defaultEndSessionEndpoint),
44 JwksURI: NewEndpoint(defaultKeysEndpoint),
45 DeviceAuthorization: NewEndpoint(defaultDeviceAuthzEndpoint),
46 }
47
48 DefaultSupportedClaims = []string{
49 "sub",
50 "aud",
51 "exp",
52 "iat",
53 "iss",
54 "auth_time",
55 "nonce",
56 "acr",
57 "amr",
58 "c_hash",
59 "at_hash",
60 "act",
61 "scopes",
62 "client_id",
63 "azp",
64 "preferred_username",
65 "name",
66 "family_name",
67 "given_name",
68 "locale",
69 "email",
70 "email_verified",
71 "phone_number",
72 "phone_number_verified",
73 }
74
75 defaultCORSOptions = cors.Options{
76 AllowCredentials: true,
77 AllowedHeaders: []string{
78 "Origin",
79 "Accept",
80 "Accept-Language",
81 "Authorization",
82 "Content-Type",
83 "X-Requested-With",
84 },
85 AllowedMethods: []string{
86 http.MethodGet,
87 http.MethodHead,
88 http.MethodPost,
89 },
90 ExposedHeaders: []string{
91 "Location",
92 "Content-Length",
93 },
94 AllowOriginFunc: func(_ string) bool {
95 return true
96 },
97 }
98 )
99
100 var Tracer = otel.Tracer("github.com/zitadel/oidc/pkg/op")
101
102 type OpenIDProvider interface {
103 http.Handler
104 Configuration
105 Storage() Storage
106 Decoder() httphelper.Decoder
107 Encoder() httphelper.Encoder
108 IDTokenHintVerifier(context.Context) *IDTokenHintVerifier
109 AccessTokenVerifier(context.Context) *AccessTokenVerifier
110 Crypto() Crypto
111 DefaultLogoutRedirectURI() string
112 Probes() []ProbesFn
113 // Deprecated: configure logging with slog.SetDefault.
114 Logger() *slog.Logger
115
116 // Deprecated: Provider now implements http.Handler directly.
117 HttpHandler() http.Handler
118 }
119
120 type HttpInterceptor func(http.Handler) http.Handler
121
122 type corsOptioner interface {
123 CORSOptions() *cors.Options
124 }
125
126 func CreateRouter(o OpenIDProvider, interceptors ...HttpInterceptor) chi.Router {
127 router := chi.NewRouter()
128 if co, ok := o.(corsOptioner); ok {
129 if opts := co.CORSOptions(); opts != nil {
130 router.Use(cors.New(*opts).Handler)
131 }
132 } else {
133 router.Use(cors.New(defaultCORSOptions).Handler)
134 }
135 router.Use(intercept(o.IssuerFromRequest, interceptors...))
136 router.HandleFunc(healthEndpoint, healthHandler)
137 router.HandleFunc(readinessEndpoint, readyHandler(o.Probes()))
138 router.HandleFunc(oidc.DiscoveryEndpoint, discoveryHandler(o, o.Storage()))
139 router.HandleFunc(o.AuthorizationEndpoint().Relative(), authorizeHandler(o))
140 router.HandleFunc(authCallbackPath(o), AuthorizeCallbackHandler(o))
141 router.HandleFunc(o.TokenEndpoint().Relative(), tokenHandler(o))
142 router.HandleFunc(o.IntrospectionEndpoint().Relative(), introspectionHandler(o))
143 router.HandleFunc(o.UserinfoEndpoint().Relative(), userinfoHandler(o))
144 router.HandleFunc(o.RevocationEndpoint().Relative(), revocationHandler(o))
145 router.HandleFunc(o.EndSessionEndpoint().Relative(), endSessionHandler(o))
146 router.HandleFunc(o.KeysEndpoint().Relative(), keysHandler(o.Storage()))
147 router.HandleFunc(o.DeviceAuthorizationEndpoint().Relative(), DeviceAuthorizationHandler(o))
148 return router
149 }
150
151 // AuthCallbackURL builds the url for the redirect (with the requestID) after a successful login
152 func AuthCallbackURL(o OpenIDProvider) func(context.Context, string) string {
153 return func(ctx context.Context, requestID string) string {
154 return o.AuthorizationEndpoint().Absolute(IssuerFromContext(ctx)) + authCallbackPathSuffix + "?id=" + url.QueryEscape(requestID)
155 }
156 }
157
158 func authCallbackPath(o OpenIDProvider) string {
159 return o.AuthorizationEndpoint().Relative() + authCallbackPathSuffix
160 }
161
162 type Config struct {
163 CryptoKey [32]byte // for encrypting access token via NewAESCrypto; will be overwritten by WithCrypto
164 CryptoKeyId string
165 DefaultLogoutRedirectURI string
166 CodeMethodS256 bool
167 AuthMethodPost bool
168 AuthMethodPrivateKeyJWT bool
169 GrantTypeRefreshToken bool
170 RequestObjectSupported bool
171 SupportedUILocales []language.Tag
172 SupportedClaims []string
173 SupportedScopes []string
174 DeviceAuthorization DeviceAuthorizationConfig
175 BackChannelLogoutSupported bool
176 BackChannelLogoutSessionSupported bool
177 }
178
179 // Endpoints defines endpoint routes.
180 type Endpoints struct {
181 Authorization *Endpoint
182 Token *Endpoint
183 Introspection *Endpoint
184 Userinfo *Endpoint
185 Revocation *Endpoint
186 EndSession *Endpoint
187 CheckSessionIframe *Endpoint
188 JwksURI *Endpoint
189 DeviceAuthorization *Endpoint
190 }
191
192 // NewOpenIDProvider creates a provider. The provider provides (with HttpHandler())
193 // a http.Router that handles a suite of endpoints (some paths can be overridden):
194 //
195 // /healthz
196 // /ready
197 // /.well-known/openid-configuration
198 // /oauth/token
199 // /oauth/introspect
200 // /callback
201 // /authorize
202 // /userinfo
203 // /revoke
204 // /end_session
205 // /keys
206 // /device_authorization
207 //
208 // This does not include login. Login is handled with a redirect that includes the
209 // request ID. The redirect for logins is specified per-client by Client.LoginURL().
210 // Successful logins should mark the request as authorized and redirect back to
211 // op.AuthCallbackURL(provider) which is probably /callback. On the redirect back
212 // to the AuthCallbackURL, the request id should be passed as the "id" parameter.
213 //
214 // Deprecated: use [NewProvider] with an issuer function direct.
215 func NewOpenIDProvider(issuer string, config *Config, storage Storage, opOpts ...Option) (*Provider, error) {
216 return NewProvider(config, storage, StaticIssuer(issuer), opOpts...)
217 }
218
219 // NewForwardedOpenIDProvider tries to establish the issuer from the request Host.
220 //
221 // Deprecated: use [NewProvider] with an issuer function direct.
222 func NewDynamicOpenIDProvider(path string, config *Config, storage Storage, opOpts ...Option) (*Provider, error) {
223 return NewProvider(config, storage, IssuerFromHost(path), opOpts...)
224 }
225
226 // NewForwardedOpenIDProvider tries to establish the Issuer from a Forwarded request header, if it is set.
227 // See [IssuerFromForwardedOrHost] for details.
228 //
229 // Deprecated: use [NewProvider] with an issuer function direct.
230 func NewForwardedOpenIDProvider(path string, config *Config, storage Storage, opOpts ...Option) (*Provider, error) {
231 return NewProvider(config, storage, IssuerFromForwardedOrHost(path), opOpts...)
232 }
233
234 // NewProvider creates a provider with a router on it's embedded http.Handler.
235 // Issuer is a function that must return the issuer on every request.
236 // Typically [StaticIssuer], [IssuerFromHost] or [IssuerFromForwardedOrHost] can be used.
237 //
238 // The router handles a suite of endpoints (some paths can be overridden):
239 //
240 // /healthz
241 // /ready
242 // /.well-known/openid-configuration
243 // /oauth/token
244 // /oauth/introspect
245 // /callback
246 // /authorize
247 // /userinfo
248 // /revoke
249 // /end_session
250 // /keys
251 // /device_authorization
252 //
253 // This does not include login. Login is handled with a redirect that includes the
254 // request ID. The redirect for logins is specified per-client by Client.LoginURL().
255 // Successful logins should mark the request as authorized and redirect back to
256 // op.AuthCallbackURL(provider) which is probably /callback. On the redirect back
257 // to the AuthCallbackURL, the request id should be passed as the "id" parameter.
258 func NewProvider(
259 config *Config,
260 storage Storage,
261 issuer func(insecure bool) (IssuerFromRequest, error),
262 opOpts ...Option,
263 ) (_ *Provider, err error) {
264 keySet := &OpenIDKeySet{storage}
265 easgcmCrypto := NewAES256GCMCrypto(config.CryptoKey, config.CryptoKeyId)
266 crypto := NewCompositeCrypto(
267 easgcmCrypto,
268 []Decrypter{
269 easgcmCrypto,
270 NewAESCrypto(config.CryptoKey),
271 },
272 )
273 o := &Provider{
274 config: config,
275 storage: storage,
276 accessTokenKeySet: keySet,
277 idTokenHinKeySet: keySet,
278 crypto: crypto,
279 endpoints: DefaultEndpoints,
280 timer: make(<-chan time.Time),
281 corsOpts: &defaultCORSOptions,
282 }
283
284 for _, optFunc := range opOpts {
285 if err := optFunc(o); err != nil {
286 return nil, err
287 }
288 }
289
290 o.issuer, err = issuer(o.insecure)
291 if err != nil {
292 return nil, err
293 }
294 o.Handler = CreateRouter(o, o.interceptors...)
295 o.decoder = schema.NewDecoder()
296 o.decoder.IgnoreUnknownKeys(true)
297 o.encoder = oidc.NewEncoder()
298 return o, nil
299 }
300
301 type Provider struct {
302 http.Handler
303 config *Config
304 issuer IssuerFromRequest
305 insecure bool
306 endpoints *Endpoints
307 storage Storage
308 accessTokenKeySet oidc.KeySet
309 idTokenHinKeySet oidc.KeySet
310 crypto Crypto
311 decoder *schema.Decoder
312 encoder *schema.Encoder
313 interceptors []HttpInterceptor
314 timer <-chan time.Time
315 accessTokenVerifierOpts []AccessTokenVerifierOpt
316 idTokenHintVerifierOpts []IDTokenHintVerifierOpt
317 corsOpts *cors.Options
318 }
319
320 func (o *Provider) IssuerFromRequest(r *http.Request) string {
321 return o.issuer(r)
322 }
323
324 func (o *Provider) Insecure() bool {
325 return o.insecure
326 }
327
328 func (o *Provider) AuthorizationEndpoint() *Endpoint {
329 return o.endpoints.Authorization
330 }
331
332 func (o *Provider) TokenEndpoint() *Endpoint {
333 return o.endpoints.Token
334 }
335
336 func (o *Provider) IntrospectionEndpoint() *Endpoint {
337 return o.endpoints.Introspection
338 }
339
340 func (o *Provider) UserinfoEndpoint() *Endpoint {
341 return o.endpoints.Userinfo
342 }
343
344 func (o *Provider) RevocationEndpoint() *Endpoint {
345 return o.endpoints.Revocation
346 }
347
348 func (o *Provider) EndSessionEndpoint() *Endpoint {
349 return o.endpoints.EndSession
350 }
351
352 func (o *Provider) DeviceAuthorizationEndpoint() *Endpoint {
353 return o.endpoints.DeviceAuthorization
354 }
355
356 func (o *Provider) CheckSessionIframe() *Endpoint {
357 return o.endpoints.CheckSessionIframe
358 }
359
360 func (o *Provider) KeysEndpoint() *Endpoint {
361 return o.endpoints.JwksURI
362 }
363
364 func (o *Provider) AuthMethodPostSupported() bool {
365 return o.config.AuthMethodPost
366 }
367
368 func (o *Provider) CodeMethodS256Supported() bool {
369 return o.config.CodeMethodS256
370 }
371
372 func (o *Provider) AuthMethodPrivateKeyJWTSupported() bool {
373 return o.config.AuthMethodPrivateKeyJWT
374 }
375
376 func (o *Provider) TokenEndpointSigningAlgorithmsSupported() []string {
377 return []string{"RS256"}
378 }
379
380 func (o *Provider) GrantTypeRefreshTokenSupported() bool {
381 return o.config.GrantTypeRefreshToken
382 }
383
384 func (o *Provider) GrantTypeTokenExchangeSupported() bool {
385 _, ok := o.storage.(TokenExchangeStorage)
386 return ok
387 }
388
389 func (o *Provider) GrantTypeJWTAuthorizationSupported() bool {
390 return true
391 }
392
393 func (o *Provider) GrantTypeDeviceCodeSupported() bool {
394 _, ok := o.storage.(DeviceAuthorizationStorage)
395 return ok
396 }
397
398 func (o *Provider) IntrospectionAuthMethodPrivateKeyJWTSupported() bool {
399 return true
400 }
401
402 func (o *Provider) IntrospectionEndpointSigningAlgorithmsSupported() []string {
403 return []string{"RS256"}
404 }
405
406 func (o *Provider) GrantTypeClientCredentialsSupported() bool {
407 _, ok := o.storage.(ClientCredentialsStorage)
408 return ok
409 }
410
411 func (o *Provider) RevocationAuthMethodPrivateKeyJWTSupported() bool {
412 return true
413 }
414
415 func (o *Provider) RevocationEndpointSigningAlgorithmsSupported() []string {
416 return []string{"RS256"}
417 }
418
419 func (o *Provider) RequestObjectSupported() bool {
420 return o.config.RequestObjectSupported
421 }
422
423 func (o *Provider) RequestObjectSigningAlgorithmsSupported() []string {
424 return []string{"RS256"}
425 }
426
427 func (o *Provider) SupportedUILocales() []language.Tag {
428 return o.config.SupportedUILocales
429 }
430
431 func (o *Provider) DeviceAuthorization() DeviceAuthorizationConfig {
432 return o.config.DeviceAuthorization
433 }
434
435 func (o *Provider) BackChannelLogoutSupported() bool {
436 return o.config.BackChannelLogoutSupported
437 }
438
439 func (o *Provider) BackChannelLogoutSessionSupported() bool {
440 return o.config.BackChannelLogoutSessionSupported
441 }
442
443 func (o *Provider) Storage() Storage {
444 return o.storage
445 }
446
447 func (o *Provider) Decoder() httphelper.Decoder {
448 return o.decoder
449 }
450
451 func (o *Provider) Encoder() httphelper.Encoder {
452 return o.encoder
453 }
454
455 func (o *Provider) IDTokenHintVerifier(ctx context.Context) *IDTokenHintVerifier {
456 return NewIDTokenHintVerifier(IssuerFromContext(ctx), o.idTokenHinKeySet, o.idTokenHintVerifierOpts...)
457 }
458
459 func (o *Provider) JWTProfileVerifier(ctx context.Context) *JWTProfileVerifier {
460 return NewJWTProfileVerifier(o.Storage(), IssuerFromContext(ctx), 1*time.Hour, time.Second)
461 }
462
463 func (o *Provider) AccessTokenVerifier(ctx context.Context) *AccessTokenVerifier {
464 return NewAccessTokenVerifier(IssuerFromContext(ctx), o.accessTokenKeySet, o.accessTokenVerifierOpts...)
465 }
466
467 func (o *Provider) Crypto() Crypto {
468 return o.crypto
469 }
470
471 func (o *Provider) DefaultLogoutRedirectURI() string {
472 return o.config.DefaultLogoutRedirectURI
473 }
474
475 func (o *Provider) Probes() []ProbesFn {
476 return []ProbesFn{
477 ReadyStorage(o.Storage()),
478 }
479 }
480
481 func (o *Provider) CORSOptions() *cors.Options {
482 return o.corsOpts
483 }
484
485 // Logger returns the global default logger.
486 // Deprecated: configure logging with [slog.SetDefault].
487 func (o *Provider) Logger() *slog.Logger {
488 return slog.Default()
489 }
490
491 // Deprecated: Provider now implements http.Handler directly.
492 func (o *Provider) HttpHandler() http.Handler {
493 return o
494 }
495
496 type OpenIDKeySet struct {
497 Storage
498 }
499
500 // VerifySignature implements the oidc.KeySet interface
501 // providing an implementation for the keys stored in the OP Storage interface
502 func (o *OpenIDKeySet) VerifySignature(ctx context.Context, jws *jose.JSONWebSignature) ([]byte, error) {
503 keySet, err := o.Storage.KeySet(ctx)
504 if err != nil {
505 return nil, fmt.Errorf("error fetching keys: %w", err)
506 }
507 keyID, alg := oidc.GetKeyIDAndAlg(jws)
508 key, err := oidc.FindMatchingKey(keyID, oidc.KeyUseSignature, alg, jsonWebKeySet(keySet).Keys...)
509 if err != nil {
510 return nil, fmt.Errorf("invalid signature: %w", err)
511 }
512 return jws.Verify(&key)
513 }
514
515 type Option func(o *Provider) error
516
517 // WithAllowInsecure allows the use of http (instead of https) for issuers
518 // this is not recommended for production use and violates the OIDC specification
519 func WithAllowInsecure() Option {
520 return func(o *Provider) error {
521 o.insecure = true
522 return nil
523 }
524 }
525
526 func WithCustomAuthEndpoint(endpoint *Endpoint) Option {
527 return func(o *Provider) error {
528 if err := endpoint.Validate(); err != nil {
529 return err
530 }
531 o.endpoints.Authorization = endpoint
532 return nil
533 }
534 }
535
536 func WithCustomTokenEndpoint(endpoint *Endpoint) Option {
537 return func(o *Provider) error {
538 if err := endpoint.Validate(); err != nil {
539 return err
540 }
541 o.endpoints.Token = endpoint
542 return nil
543 }
544 }
545
546 func WithCustomIntrospectionEndpoint(endpoint *Endpoint) Option {
547 return func(o *Provider) error {
548 if err := endpoint.Validate(); err != nil {
549 return err
550 }
551 o.endpoints.Introspection = endpoint
552 return nil
553 }
554 }
555
556 func WithCustomUserinfoEndpoint(endpoint *Endpoint) Option {
557 return func(o *Provider) error {
558 if err := endpoint.Validate(); err != nil {
559 return err
560 }
561 o.endpoints.Userinfo = endpoint
562 return nil
563 }
564 }
565
566 func WithCustomRevocationEndpoint(endpoint *Endpoint) Option {
567 return func(o *Provider) error {
568 if err := endpoint.Validate(); err != nil {
569 return err
570 }
571 o.endpoints.Revocation = endpoint
572 return nil
573 }
574 }
575
576 func WithCustomEndSessionEndpoint(endpoint *Endpoint) Option {
577 return func(o *Provider) error {
578 if err := endpoint.Validate(); err != nil {
579 return err
580 }
581 o.endpoints.EndSession = endpoint
582 return nil
583 }
584 }
585
586 func WithCustomKeysEndpoint(endpoint *Endpoint) Option {
587 return func(o *Provider) error {
588 if err := endpoint.Validate(); err != nil {
589 return err
590 }
591 o.endpoints.JwksURI = endpoint
592 return nil
593 }
594 }
595
596 func WithCustomDeviceAuthorizationEndpoint(endpoint *Endpoint) Option {
597 return func(o *Provider) error {
598 if err := endpoint.Validate(); err != nil {
599 return err
600 }
601 o.endpoints.DeviceAuthorization = endpoint
602 return nil
603 }
604 }
605
606 // WithCustomEndpoints sets multiple endpoints at once.
607 // None of the endpoints may be nil, or an error will
608 // be returned when the Option used by the Provider.
609 func WithCustomEndpoints(auth, token, userInfo, revocation, endSession, keys *Endpoint) Option {
610 return func(o *Provider) error {
611 for _, e := range []*Endpoint{auth, token, userInfo, revocation, endSession, keys} {
612 if err := e.Validate(); err != nil {
613 return err
614 }
615 }
616 o.endpoints.Authorization = auth
617 o.endpoints.Token = token
618 o.endpoints.Userinfo = userInfo
619 o.endpoints.Revocation = revocation
620 o.endpoints.EndSession = endSession
621 o.endpoints.JwksURI = keys
622 return nil
623 }
624 }
625
626 func WithHttpInterceptors(interceptors ...HttpInterceptor) Option {
627 return func(o *Provider) error {
628 o.interceptors = append(o.interceptors, interceptors...)
629 return nil
630 }
631 }
632
633 // WithAccessTokenKeySet allows passing a KeySet with public keys for Access Token verification.
634 // The default KeySet uses the [Storage] interface
635 func WithAccessTokenKeySet(keySet oidc.KeySet) Option {
636 return func(o *Provider) error {
637 o.accessTokenKeySet = keySet
638 return nil
639 }
640 }
641
642 func WithAccessTokenVerifierOpts(opts ...AccessTokenVerifierOpt) Option {
643 return func(o *Provider) error {
644 o.accessTokenVerifierOpts = opts
645 return nil
646 }
647 }
648
649 // WithIDTokenHintKeySet allows passing a KeySet with public keys for ID Token Hint verification.
650 // The default KeySet uses the [Storage] interface.
651 func WithIDTokenHintKeySet(keySet oidc.KeySet) Option {
652 return func(o *Provider) error {
653 o.idTokenHinKeySet = keySet
654 return nil
655 }
656 }
657
658 func WithIDTokenHintVerifierOpts(opts ...IDTokenHintVerifierOpt) Option {
659 return func(o *Provider) error {
660 o.idTokenHintVerifierOpts = opts
661 return nil
662 }
663 }
664
665 func WithCORSOptions(opts *cors.Options) Option {
666 return func(o *Provider) error {
667 o.corsOpts = opts
668 return nil
669 }
670 }
671
672 // WithLogger is retained for source compatibility.
673 // Deprecated: use [slog.SetDefault]. This option has no effect.
674 func WithLogger(*slog.Logger) Option {
675 return func(*Provider) error {
676 return nil
677 }
678 }
679
680 // WithCrypto allows the user to pass their own Crypto implementation.
681 //
682 // If provided, this will overwrite Config.CryptoKey.
683 func WithCrypto(crypto Crypto) Option {
684 return func(o *Provider) error {
685 o.crypto = crypto
686 return nil
687 }
688 }
689
690 func intercept(i IssuerFromRequest, interceptors ...HttpInterceptor) func(handler http.Handler) http.Handler {
691 issuerInterceptor := NewIssuerInterceptor(i)
692 return func(handler http.Handler) http.Handler {
693 for i := len(interceptors) - 1; i >= 0; i-- {
694 handler = interceptors[i](handler)
695 }
696 return issuerInterceptor.Handler(handler)
697 }
698 }