git.iko.soy/typeable/oauth2-proxy
on master help sign in
feature: static public keys file support for oidc provider

Co-authored-by: Jan Larwig <jan@larwig.com> Co-authored-by: JJ Łakis <jacek.lakis@checkatrade.com>

commite28603f7af7a1836ad9d6311414e64a89a4479cc authoraxel7083 <42176370+axel7083@users.noreply.github.com> dateWed 15 Mar 2023, 14:03 (4 years ago) parentae8fb08
9 files changed+154−16
CHANGELOG.md+1 docs/docs/configuration/alpha_config.md+1 docs/docs/configuration/overview.md+2−1 pkg/apis/options/legacy_options.go+3 pkg/apis/options/providers.go+3 pkg/providers/oidc/provider_verifier.go+79−12 pkg/providers/oidc/provider_verifier_test.go+63−2 providers/providers.go+1 providers/providers_test.go+1−1
CHANGELOG.md+1
@@ -16,6 +16,7 @@
1616- [#2620](https://github.com/oauth2-proxy/oauth2-proxy/pull/2620) fix: update code_verifier to use recommended method (@vishvananda)
1717- [#2392](https://github.com/oauth2-proxy/oauth2-proxy/pull/2392) chore: extend test cases for oidc provider and documentation regarding implicit setting of the groups scope when no scope was specified in the config (@jjlakis / @tuunit)
1818- [#2902](https://github.com/oauth2-proxy/oauth2-proxy/pull/2902) feat(entra): add Workload Identity support for Entra ID (@jjlakis)
19+- [#2376](https://github.com/oauth2-proxy/oauth2-proxy/pull/2376) feat: static public keys file support for oidc provider (@axel7083 / @jjlakis)
1920
2021# V7.7.1
2122
docs/docs/configuration/alpha_config.md+1
@@ -410,6 +410,7 @@ character.
410410| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match<br/>the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked<br/>after the initial OAuth redeem & subsequent token refreshes.<br/>default set to 'true'<br/>Warning: In a future release, this will change to 'false' by default for enhanced security. |
411411| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints<br/>default set to 'false' |
412412| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL<br/>eg: https://www.googleapis.com/oauth2/v3/certs |
413+| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use<br/>for verifying JWT tokens |
413414| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,<br/>default set to 'email' |
414415| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups<br/>default set to 'groups' |
415416| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID<br/>default set to 'email' |
docs/docs/configuration/overview.md+2−1
@@ -96,7 +96,8 @@ Provider specific options can be found on their respective subpages.
9696| flag: `--oidc-extra-audience`<br/>toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` |
9797| flag: `--oidc-groups-claim`<br/>toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` |
9898| flag: `--oidc-issuer-url`<br/>toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | |
99−| flag: `--oidc-jwks-url`<br/>toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled | |
99+| flag: `--oidc-jwks-url`<br/>toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | |
100+| flag: `--oidc-public-key-file`<br/>toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list |
100101| flag: `--profile-url`<br/>toml: `profile_url` | string | Profile access endpoint | |
101102| flag: `--prompt`<br/>toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` |
102103| flag: `--provider-ca-file`<br/>toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. |
pkg/apis/options/legacy_options.go+3
@@ -522,6 +522,7 @@ type LegacyProvider struct {
522522 OIDCGroupsClaim string `flag:"oidc-groups-claim" cfg:"oidc_groups_claim"`
523523 OIDCAudienceClaims []string `flag:"oidc-audience-claim" cfg:"oidc_audience_claims"`
524524 OIDCExtraAudiences []string `flag:"oidc-extra-audience" cfg:"oidc_extra_audiences"`
525+ OIDCPublicKeyFiles []string `flag:"oidc-public-key-file" cfg:"oidc_public_key_files"`
525526 LoginURL string `flag:"login-url" cfg:"login_url"`
526527 RedeemURL string `flag:"redeem-url" cfg:"redeem_url"`
527528 ProfileURL string `flag:"profile-url" cfg:"profile_url"`
@@ -581,6 +582,7 @@ func legacyProviderFlagSet() *pflag.FlagSet {
581582 flagSet.String("oidc-email-claim", OIDCEmailClaim, "which OIDC claim contains the user's email")
582583 flagSet.StringSlice("oidc-audience-claim", OIDCAudienceClaims, "which OIDC claims are used as audience to verify against client id")
583584 flagSet.StringSlice("oidc-extra-audience", []string{}, "additional audiences allowed to pass audience verification")
585+ flagSet.StringSlice("oidc-public-key-file", []string{}, "path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times)")
584586 flagSet.String("login-url", "", "Authentication endpoint")
585587 flagSet.String("redeem-url", "", "Token redemption endpoint")
586588 flagSet.String("profile-url", "", "Profile access endpoint")
@@ -697,6 +699,7 @@ func (l *LegacyProvider) convert() (Providers, error) {
697699 GroupsClaim: l.OIDCGroupsClaim,
698700 AudienceClaims: l.OIDCAudienceClaims,
699701 ExtraAudiences: l.OIDCExtraAudiences,
702+ PublicKeyFiles: l.OIDCPublicKeyFiles,
700703 }
701704
702705 // Support for legacy configuration option
pkg/apis/options/providers.go+3
@@ -242,6 +242,9 @@ type OIDCOptions struct {
242242 // JwksURL is the OpenID Connect JWKS URL
243243 // eg: https://www.googleapis.com/oauth2/v3/certs
244244 JwksURL string `json:"jwksURL,omitempty"`
245+ // PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
246+ // for verifying JWT tokens
247+ PublicKeyFiles []string `json:"publicKeyFiles,omitempty"`
245248 // EmailClaim indicates which claim contains the user email,
246249 // default set to 'email'
247250 EmailClaim string `json:"emailClaim,omitempty"`
pkg/providers/oidc/provider_verifier.go+79−12
@@ -2,11 +2,14 @@ package oidc
22
33import (
44 "context"
5+ "crypto"
6+ "crypto/x509"
7+ "encoding/pem"
58 "errors"
69 "fmt"
10+ "os"
711
812 "github.com/coreos/go-oidc/v3/oidc"
9− "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests"
1013 k8serrors "k8s.io/apimachinery/pkg/util/errors"
1114)
1215
@@ -38,6 +41,10 @@ type ProviderVerifierOptions struct {
3841 // eg: https://www.googleapis.com/oauth2/v3/certs
3942 JWKsURL string
4043
44+ // PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
45+ // for verifying JWT tokens
46+ PublicKeyFiles []string
47+
4148 // SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
4249 SkipDiscovery bool
4350
@@ -59,8 +66,12 @@ func (p ProviderVerifierOptions) validate() error {
5966 errs = append(errs, errors.New("missing required setting: issuer-url"))
6067 }
6168
62− if p.SkipDiscovery && p.JWKsURL == "" {
63− errs = append(errs, errors.New("missing required setting: jwks-url"))
69+ if p.SkipDiscovery && p.JWKsURL == "" && len(p.PublicKeyFiles) == 0 {
70+ errs = append(errs, errors.New("missing required setting: jwks-url or public-key-files"))
71+ }
72+
73+ if p.JWKsURL != "" && len(p.PublicKeyFiles) > 0 {
74+ errs = append(errs, errors.New("mutually exclusive settings: jwks-url and public-key-files"))
6475 }
6576
6677 if len(errs) > 0 {
@@ -91,12 +102,12 @@ func (p ProviderVerifierOptions) toOIDCConfig() *oidc.Config {
91102// NewProviderVerifier constructs a ProviderVerifier from the options given.
92103func NewProviderVerifier(ctx context.Context, opts ProviderVerifierOptions) (ProviderVerifier, error) {
93104 if err := opts.validate(); err != nil {
94− return nil, fmt.Errorf("invalid provider verifier options: %v", err)
105+ return nil, fmt.Errorf("invalid provider verifier options: %w", err)
95106 }
96107
97108 verifierBuilder, provider, err := getVerifierBuilder(ctx, opts)
98109 if err != nil {
99− return nil, fmt.Errorf("could not get verifier builder: %v", err)
110+ return nil, fmt.Errorf("could not get verifier builder: %w", err)
100111 }
101112 verifier := NewVerifier(verifierBuilder(opts.toOIDCConfig()), opts.toVerificationOptions())
102113
@@ -117,22 +128,78 @@ type verifierBuilder func(*oidc.Config) *oidc.IDTokenVerifier
117128
118129func getVerifierBuilder(ctx context.Context, opts ProviderVerifierOptions) (verifierBuilder, DiscoveryProvider, error) {
119130 if opts.SkipDiscovery {
131+ var keySet oidc.KeySet
132+ var err error
133+
134+ if opts.JWKsURL != "" {
135+ keySet = oidc.NewRemoteKeySet(ctx, opts.JWKsURL)
136+ } else {
137+ keySet, err = newKeySetFromStatic(opts.PublicKeyFiles)
138+ if err != nil {
139+ return nil, nil, fmt.Errorf("error while parsing public keys: %w", err)
140+ }
141+ }
120142 // Instead of discovering the JWKs URL, it needs to be specified in the opts already
121− return newVerifierBuilder(ctx, opts.IssuerURL, opts.JWKsURL, opts.SupportedSigningAlgs), nil, nil
143+ return newVerifierBuilder(
144+ opts.IssuerURL,
145+ keySet,
146+ opts.SupportedSigningAlgs,
147+ ), nil, nil
122148 }
123149
124150 provider, err := NewProvider(ctx, opts.IssuerURL, opts.SkipIssuerVerification)
125151 if err != nil {
126− return nil, nil, fmt.Errorf("error while discovery OIDC configuration: %v", err)
152+ return nil, nil, fmt.Errorf("error while discovery OIDC configuration: %w", err)
153+ }
154+
155+ return newVerifierBuilder(
156+ opts.IssuerURL,
157+ oidc.NewRemoteKeySet(ctx, provider.Endpoints().JWKsURL),
158+ provider.SupportedSigningAlgs(),
159+ ), provider, nil
160+}
161+
162+// GetPublicKeyFromBytes parses a PEM-encoded public key from a byte array
163+// and returns a crypto.PublicKey object.
164+func getPublicKeyFromBytes(bytes []byte) (crypto.PublicKey, error) {
165+ block, _ := pem.Decode(bytes)
166+ if block == nil {
167+ return nil, errors.New("failed to parse PEM block containing the public key")
168+ }
169+ publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
170+ if err != nil {
171+ return nil, fmt.Errorf("failed to parse public key: %w", err)
127172 }
128− verifierBuilder := newVerifierBuilder(ctx, opts.IssuerURL, provider.Endpoints().JWKsURL, provider.SupportedSigningAlgs())
129− return verifierBuilder, provider, nil
173+
174+ cryptoPublicKey, ok := publicKey.(crypto.PublicKey)
175+ if !ok {
176+ return nil, errors.New("failed to cast public key to crypto.PublicKey")
177+ }
178+
179+ return cryptoPublicKey, nil
180+}
181+
182+// newKeySetFromStatic create a StaticKeySet from a set of files
183+func newKeySetFromStatic(keys []string) (*oidc.StaticKeySet, error) {
184+ keySet := []crypto.PublicKey{}
185+ for _, keyFile := range keys {
186+ bytes, err := os.ReadFile(keyFile)
187+ if err != nil {
188+ return nil, fmt.Errorf("failed to read file: %w", err)
189+ }
190+
191+ publicKey, err := getPublicKeyFromBytes(bytes)
192+ if err != nil {
193+ return nil, fmt.Errorf("failed to create keys: %w", err)
194+ }
195+ keySet = append(keySet, publicKey)
196+ }
197+
198+ return &oidc.StaticKeySet{PublicKeys: keySet}, nil
130199}
131200
132201// newVerifierBuilder returns a function to create a IDToken verifier from an OIDC config.
133−func newVerifierBuilder(ctx context.Context, issuerURL, jwksURL string, supportedSigningAlgs []string) verifierBuilder {
134− ctx = oidc.ClientContext(ctx, requests.DefaultHTTPClient)
135− keySet := oidc.NewRemoteKeySet(ctx, jwksURL)
202+func newVerifierBuilder(issuerURL string, keySet oidc.KeySet, supportedSigningAlgs []string) verifierBuilder {
136203 return func(oidcConfig *oidc.Config) *oidc.IDTokenVerifier {
137204 if len(supportedSigningAlgs) > 0 {
138205 oidcConfig.SupportedSigningAlgs = supportedSigningAlgs
pkg/providers/oidc/provider_verifier_test.go+63−2
@@ -2,6 +2,8 @@ package oidc
22
33import (
44 "context"
5+ "os"
6+ "path/filepath"
57 "time"
68
79 "github.com/golang-jwt/jwt/v5"
@@ -10,6 +12,37 @@ import (
1012 . "github.com/onsi/gomega"
1113)
1214
15+var tempDir string
16+var invalidPublicKeyFilePath string
17+var validPublicKeyFilePath string
18+
19+var _ = BeforeSuite(func() {
20+ var err error
21+
22+ // Create a temporary directory and public key file
23+ tempDir, err = os.MkdirTemp("/tmp", "provider-verifier-test")
24+ Expect(err).ToNot(HaveOccurred())
25+
26+ invalidPublicKeyFilePath = filepath.Join(tempDir, "invalid.key")
27+ validPublicKeyFilePath = filepath.Join(tempDir, "valid.key")
28+
29+ invalidKeyContents := []byte(`-----BEGIN INVALID KEY-----
30+ThisIsNotAValidKey
31+-----END INVALID KEY-----`)
32+ Expect(os.WriteFile(invalidPublicKeyFilePath, invalidKeyContents, 0644)).To(Succeed())
33+
34+ validKeyContents := []byte(`-----BEGIN PUBLIC KEY-----
35+MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALBJK+8qU+aQu2bHxJ8E95AIu2NINztM
36+NmX9R2zI9xlXN8wGQG8kWLYoRLbyiZwY9kdzOBGvYci64wHIjtFswHcCAwEAAQ==
37+-----END PUBLIC KEY-----`)
38+ Expect(os.WriteFile(validPublicKeyFilePath, validKeyContents, 0644)).To(Succeed())
39+})
40+
41+var _ = AfterSuite(func() {
42+ // Clean up temporary directory
43+ Expect(os.RemoveAll(tempDir)).To(Succeed())
44+})
45+
1346var _ = Describe("ProviderVerifier", func() {
1447 var m *mockoidc.MockOIDC
1548
@@ -77,14 +110,42 @@ var _ = Describe("ProviderVerifier", func() {
77110 p.SkipDiscovery = true
78111 p.JWKsURL = ""
79112 },
80− expectedError: "invalid provider verifier options: missing required setting: jwks-url",
113+ expectedError: "invalid provider verifier options: missing required setting: jwks-url or public-key-files",
114+ }),
115+ Entry("with skip discovery, the JWKs URL not empty and len(PublicKeyFiles) is greater than 0", &newProviderVerifierTableInput{
116+ modifyOpts: func(p *ProviderVerifierOptions) {
117+ p.SkipDiscovery = true
118+ p.JWKsURL = "notEmpty"
119+ p.PublicKeyFiles = []string{"notEmpty"}
120+ },
121+ expectedError: "invalid provider verifier options: mutually exclusive settings: jwks-url and public-key-files",
81122 }),
82− Entry("should be succesfful when skipping discovery with the JWKs URL specified", &newProviderVerifierTableInput{
123+ Entry("should be successful when skipping discovery with the JWKs URL specified", &newProviderVerifierTableInput{
83124 modifyOpts: func(p *ProviderVerifierOptions) {
84125 p.SkipDiscovery = true
85126 p.JWKsURL = m.JWKSEndpoint()
86127 },
87128 }),
129+ Entry("should pass when the key is valid", &newProviderVerifierTableInput{
130+ modifyOpts: func(p *ProviderVerifierOptions) {
131+ p.SkipDiscovery = true
132+ p.PublicKeyFiles = []string{validPublicKeyFilePath}
133+ },
134+ }),
135+ Entry("should fail when the key is invalid", &newProviderVerifierTableInput{
136+ modifyOpts: func(p *ProviderVerifierOptions) {
137+ p.SkipDiscovery = true
138+ p.PublicKeyFiles = []string{invalidPublicKeyFilePath}
139+ },
140+ expectedError: "could not get verifier builder: error while parsing public keys",
141+ }),
142+ Entry("should fail when the key file is not found", &newProviderVerifierTableInput{
143+ modifyOpts: func(p *ProviderVerifierOptions) {
144+ p.SkipDiscovery = true
145+ p.PublicKeyFiles = []string{"non-existing"}
146+ },
147+ expectedError: "could not get verifier builder: error while parsing public keys: failed to read file",
148+ }),
88149 )
89150
90151 type verifierTableInput struct {
providers/providers.go+1
@@ -92,6 +92,7 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData,
9292 ExtraAudiences: providerConfig.OIDCConfig.ExtraAudiences,
9393 IssuerURL: providerConfig.OIDCConfig.IssuerURL,
9494 JWKsURL: providerConfig.OIDCConfig.JwksURL,
95+ PublicKeyFiles: providerConfig.OIDCConfig.PublicKeyFiles,
9596 SkipDiscovery: providerConfig.OIDCConfig.SkipDiscovery,
9697 SkipIssuerVerification: providerConfig.OIDCConfig.InsecureSkipIssuerVerification,
9798 })
providers/providers_test.go+1−1
@@ -86,7 +86,7 @@ func TestSkipOIDCDiscovery(t *testing.T) {
8686 }
8787
8888 _, err := newProviderDataFromConfig(providerConfig)
89− g.Expect(err).To(MatchError("error building OIDC ProviderVerifier: invalid provider verifier options: missing required setting: jwks-url"))
89+ g.Expect(err).To(MatchError("error building OIDC ProviderVerifier: invalid provider verifier options: missing required setting: jwks-url or public-key-files"))
9090
9191 providerConfig.LoginURL = msAuthURL
9292 providerConfig.RedeemURL = msTokenURL