Debian Codegraph @

internal/oauth2/provider.go

raw
1 package oauth2
2
3 import (
4 "context"
5 "fmt"
6 "log/slog"
7 "net/http"
8 "strings"
9 "time"
10
11 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config"
12 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/crypto"
13 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2/types"
14 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/tokenstorage"
15 "github.com/zitadel/oidc/v3/pkg/client/rp"
16 httphelper "github.com/zitadel/oidc/v3/pkg/http"
17 "golang.org/x/oauth2"
18 )
19
20 // New returns a [Client] instance.
21 //
22 //nolint:revive // New wires together package dependencies.
23 func New(
24 ctx context.Context, logger *slog.Logger, conf *config.Config,
25 httpClient *http.Client, tokenStorage tokenstorage.Storage, stateCrypto *crypto.Cipher,
26 provider Provider, openvpn openvpnManagementClient,
27 ) (*Client, error) {
28 providerConfig, err := provider.GetProviderConfig()
29 if err != nil {
30 return nil, fmt.Errorf("error fetch configuration for provider %s: %w", provider.GetName(), err)
31 }
32
33 client := &Client{
34 storage: tokenStorage,
35 openvpn: openvpn,
36 conf: conf,
37 logger: logger,
38 provider: provider,
39 stateCrypto: stateCrypto,
40 authorizeParams: make([]rp.URLParamOpt, 0, len(conf.OAuth2.AuthorizeParams)+len(providerConfig.AuthCodeOptions)+1), // +1 for nonce
41 }
42
43 authorizeParams, err := getAuthorizeParams(conf.OAuth2.AuthorizeParams)
44 if err != nil {
45 return nil, fmt.Errorf("error parsing authorize params: %w", err)
46 }
47
48 client.authorizeParams = append(client.authorizeParams, authorizeParams...)
49
50 if providerConfig.AuthCodeOptions != nil {
51 client.authorizeParams = append(client.authorizeParams, func() []oauth2.AuthCodeOption {
52 return providerConfig.AuthCodeOptions
53 })
54 }
55
56 options := client.getRelyingPartyOptions(httpClient)
57
58 scopes := conf.OAuth2.Scopes
59 if len(scopes) == 0 {
60 scopes = providerConfig.Scopes
61 }
62
63 if providerConfig.Endpoint == (oauth2.Endpoint{}) {
64 client.relyingParty, err = newOIDCRelyingParty(ctx, logger, conf, provider, scopes, options)
65 if err != nil {
66 return nil, err
67 }
68 } else {
69 client.relyingParty, err = newOAuthRelyingParty(ctx, logger, conf, provider, scopes, options, providerConfig)
70 if err != nil {
71 return nil, err
72 }
73 }
74
75 if err = client.initializeCELPrograms(); err != nil {
76 return nil, err
77 }
78
79 return client, nil
80 }
81
82 // newOIDCRelyingParty creates a new [rp.NewRelyingPartyOIDC]. This is used for providers that support OIDC.
83 func newOIDCRelyingParty(
84 ctx context.Context, logger *slog.Logger, conf *config.Config, provider Provider, scopes []string, options []rp.Option,
85 ) (rp.RelyingParty, error) {
86 if !conf.OAuth2.Endpoints.Discovery.IsEmpty() {
87 logger.LogAttrs(ctx, slog.LevelInfo, fmt.Sprintf(
88 "discover oidc auto configuration with provider %s for issuer %s with custom discovery url %s",
89 provider.GetName(), conf.OAuth2.Issuer.String(), conf.OAuth2.Endpoints.Discovery.String(),
90 ))
91
92 options = append(options, rp.WithCustomDiscoveryUrl(conf.OAuth2.Endpoints.Discovery.String()))
93 } else {
94 logger.LogAttrs(ctx, slog.LevelInfo, fmt.Sprintf(
95 "discover oidc auto configuration with provider %s for issuer %s",
96 provider.GetName(), conf.OAuth2.Issuer.String(),
97 ))
98 }
99
100 replyingParty, err := rp.NewRelyingPartyOIDC(
101 ctx,
102 conf.OAuth2.Issuer.String(),
103 conf.OAuth2.Client.ID,
104 conf.OAuth2.Client.Secret.String(),
105 conf.HTTP.BaseURL.JoinPath("/oauth2/callback").String(),
106 scopes,
107 options...,
108 )
109 if err != nil {
110 return nil, fmt.Errorf("error OIDC provider: %w", err)
111 }
112
113 return replyingParty, nil
114 }
115
116 // newOAuthRelyingParty creates a new [rp.NewRelyingPartyOAuth]. This is used for providers that do not support OIDC.
117 func newOAuthRelyingParty(
118 ctx context.Context, logger *slog.Logger, conf *config.Config, provider Provider, scopes []string, options []rp.Option, providerConfig types.ProviderConfig,
119 ) (rp.RelyingParty, error) {
120 logger.LogAttrs(ctx, slog.LevelInfo, fmt.Sprintf(
121 "manually configure oauth2 provider with provider %s and providerConfig %s and %s",
122 provider.GetName(), providerConfig.AuthURL, providerConfig.TokenURL,
123 ))
124
125 if provider.GetName() == "generic" {
126 logger.LogAttrs(ctx, slog.LevelWarn, "generic provider with manual configuration is used. Validation of user data is not possible.")
127 }
128
129 replyingParty, err := rp.NewRelyingPartyOAuth(&oauth2.Config{
130 ClientID: conf.OAuth2.Client.ID,
131 ClientSecret: conf.OAuth2.Client.Secret.String(),
132 RedirectURL: conf.HTTP.BaseURL.JoinPath("/oauth2/callback").String(),
133 Scopes: scopes,
134 Endpoint: providerConfig.Endpoint,
135 }, options...)
136 if err != nil {
137 return nil, fmt.Errorf("error oauth2 provider: %w", err)
138 }
139
140 return replyingParty, nil
141 }
142
143 // getRelyingPartyOptions builds the common relying party options for OAuth2 and OIDC clients.
144 func (c *Client) getRelyingPartyOptions(httpClient *http.Client) []rp.Option {
145 basePath := c.conf.HTTP.BaseURL.JoinPath("/oauth2/")
146 cookieKey := []byte(c.conf.HTTP.Secret)
147 cookieOpt := []httphelper.CookieHandlerOpt{
148 httphelper.WithMaxAge(int(c.conf.OpenVPN.AuthPendingTimeout.Seconds()) + 5),
149 httphelper.WithPath(fmt.Sprintf("/%s/", strings.Trim(basePath.Path, "/"))),
150 httphelper.WithDomain(basePath.Hostname()),
151 }
152
153 if c.conf.HTTP.BaseURL.Scheme == "http" {
154 cookieOpt = append(cookieOpt, httphelper.WithUnsecure())
155 }
156
157 cookieHandler := httphelper.NewCookieHandler(cookieKey, cookieKey, cookieOpt...)
158
159 verifierOpts := make([]rp.VerifierOption, 0, 4)
160 verifierOpts = append(
161 verifierOpts,
162 rp.WithIssuedAtMaxAge(30*time.Minute),
163 rp.WithIssuedAtOffset(5*time.Second),
164 )
165
166 if c.conf.OAuth2.Nonce {
167 verifierOpts = append(verifierOpts, rp.WithNonce(func(ctx context.Context) string {
168 if nonce, ok := ctx.Value(types.CtxNonce{}).(string); ok {
169 return nonce
170 }
171
172 return ""
173 }))
174 }
175
176 options := make([]rp.Option, 0, 9)
177 options = append(
178 options,
179 rp.WithAuthStyle(c.conf.OAuth2.AuthStyle.AuthStyle()),
180 rp.WithSigningAlgsFromDiscovery(),
181 rp.WithCookieHandler(cookieHandler),
182 rp.WithVerifierOpts(verifierOpts...),
183 rp.WithHTTPClient(httpClient),
184 rp.WithErrorHandler(func(w http.ResponseWriter, r *http.Request, errorType, errorDesc, encryptedSession string) {
185 c.httpErrorHandler(r.Context(), w, http.StatusInternalServerError, errorType, errorDesc, encryptedSession)
186 }),
187 rp.WithUnauthorizedHandler(func(w http.ResponseWriter, r *http.Request, errorDesc, encryptedSession string) {
188 c.httpErrorHandler(r.Context(), w, http.StatusUnauthorized, "Unauthorized", errorDesc, encryptedSession)
189 }),
190 )
191
192 if c.conf.OAuth2.PKCE {
193 options = append(options, rp.WithPKCE(cookieHandler))
194 }
195
196 if c.conf.OAuth2.Client.PrivateKey.String() != "" {
197 options = append(options, rp.WithJWTProfile(rp.SignerFromKeyAndKeyID(
198 []byte(c.conf.OAuth2.Client.PrivateKey.String()),
199 c.conf.OAuth2.Client.PrivateKeyID,
200 )))
201 }
202
203 return options
204 }