package validation import ( "crypto" "net/url" "os" "strings" "testing" "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "github.com/stretchr/testify/assert" ) const ( cookieSecret = "secretthirtytwobytes+abcdefghijk" clientID = "bazquux" clientSecret = "xyzzyplugh" providerID = "providerID" ) func testOptions() *options.Options { o := options.NewOptions() o.UpstreamServers.Upstreams = append(o.UpstreamServers.Upstreams, options.Upstream{ ID: "upstream", Path: "/", URI: "http://127.0.0.1:8080/", }) o.Cookie.Secret = cookieSecret o.Providers[0].ID = providerID o.Providers[0].ClientID = clientID o.Providers[0].ClientSecret = clientSecret o.EmailDomains = []string{"*"} return o } func errorMsg(msgs []string) string { result := make([]string, 0) result = append(result, "invalid configuration:") result = append(result, msgs...) return strings.Join(result, "\n ") } func TestNewOptions(t *testing.T) { o := options.NewOptions() o.EmailDomains = []string{"*"} err := Validate(o) assert.NotEqual(t, nil, err) expected := errorMsg([]string{ "missing setting: cookie-secret or cookie-secret-file", "provider has empty id: ids are required for all providers", "provider missing setting: client-id", "missing setting: client-secret or client-secret-file"}) assert.Equal(t, expected, err.Error()) } func TestGoogleGroupOptionsWithoutServiceAccountJSON(t *testing.T) { o := testOptions() o.Providers[0].GoogleConfig.AdminEmail = "admin@example.com" err := Validate(o) assert.NotEqual(t, nil, err) expected := errorMsg([]string{ "missing setting: google-service-account-json or google-use-application-default-credentials"}) assert.Equal(t, expected, err.Error()) } func TestGoogleGroupOptionsWithoutAdminEmail(t *testing.T) { o := testOptions() o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.To(true) err := Validate(o) assert.NotEqual(t, nil, err) expected := errorMsg([]string{ "missing setting: google-admin-email"}) assert.Equal(t, expected, err.Error()) } func TestGoogleGroupOptionsWithoutGroups(t *testing.T) { o := testOptions() // Set admin email and application default credentials but no groups - should still require them o.Providers[0].GoogleConfig.AdminEmail = "admin@example.com" o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.To(true) err := Validate(o) // Should pass validation since google-group is now optional assert.Equal(t, nil, err) } func TestGoogleGroupInvalidFile(t *testing.T) { o := testOptions() o.Providers[0].GoogleConfig.Groups = []string{"test_group"} o.Providers[0].GoogleConfig.AdminEmail = "admin@example.com" o.Providers[0].GoogleConfig.ServiceAccountJSON = "file_doesnt_exist.json" err := Validate(o) assert.NotEqual(t, nil, err) expected := errorMsg([]string{ "Google credentials file not found: file_doesnt_exist.json", }) assert.Equal(t, expected, err.Error()) } func TestInitializedOptions(t *testing.T) { o := testOptions() assert.Equal(t, nil, Validate(o)) } // Note that it's not worth testing nonparseable URLs, since url.Parse() // seems to parse damn near anything. func TestRedirectURL(t *testing.T) { o := testOptions() o.RawRedirectURL = "https://myhost.com/oauth2/callback" assert.Equal(t, nil, Validate(o)) expected := &url.URL{ Scheme: "https", Host: "myhost.com", Path: "/oauth2/callback"} assert.Equal(t, expected, o.GetRedirectURL()) } func TestCookieRefreshMustBeLessThanCookieExpire(t *testing.T) { o := testOptions() assert.Equal(t, nil, Validate(o)) o.Cookie.Secret = "0123456789abcdef" o.Cookie.Refresh = o.Cookie.Expire assert.NotEqual(t, nil, Validate(o)) o.Cookie.Refresh -= time.Duration(1) assert.Equal(t, nil, Validate(o)) } func TestBase64CookieSecret(t *testing.T) { o := testOptions() assert.Equal(t, nil, Validate(o)) // 32 byte, base64 (urlsafe) encoded key o.Cookie.Secret = "yHBw2lh2Cvo6aI_jn_qMTr-pRAjtq0nzVgDJNb36jgQ=" assert.Equal(t, nil, Validate(o)) // 32 byte, base64 (urlsafe) encoded key, w/o padding o.Cookie.Secret = "yHBw2lh2Cvo6aI_jn_qMTr-pRAjtq0nzVgDJNb36jgQ" assert.Equal(t, nil, Validate(o)) // 24 byte, base64 (urlsafe) encoded key o.Cookie.Secret = "Kp33Gj-GQmYtz4zZUyUDdqQKx5_Hgkv3" assert.Equal(t, nil, Validate(o)) // 16 byte, base64 (urlsafe) encoded key o.Cookie.Secret = "LFEqZYvYUwKwzn0tEuTpLA==" assert.Equal(t, nil, Validate(o)) // 16 byte, base64 (urlsafe) encoded key, w/o padding o.Cookie.Secret = "LFEqZYvYUwKwzn0tEuTpLA" assert.Equal(t, nil, Validate(o)) } func TestValidateSignatureKey(t *testing.T) { o := testOptions() o.SignatureKey = "sha1:secret" assert.Equal(t, nil, Validate(o)) assert.Equal(t, o.GetSignatureData().Hash, crypto.SHA1) assert.Equal(t, o.GetSignatureData().Key, "secret") } func TestValidateSignatureKeyInvalidSpec(t *testing.T) { o := testOptions() o.SignatureKey = "invalid spec" err := Validate(o) assert.Equal(t, err.Error(), "invalid configuration:\n"+ " invalid signature hash:key spec: "+o.SignatureKey) } func TestValidateSignatureKeyUnsupportedAlgorithm(t *testing.T) { o := testOptions() o.SignatureKey = "unsupported:default secret" err := Validate(o) assert.Equal(t, err.Error(), "invalid configuration:\n"+ " unsupported signature hash algorithm: "+o.SignatureKey) } func TestGCPHealthcheck(t *testing.T) { o := testOptions() o.GCPHealthChecks = true assert.Equal(t, nil, Validate(o)) } func TestRealClientIPHeader(t *testing.T) { // Ensure nil if ReverseProxy not set. o := testOptions() o.RealClientIPHeader = "X-Real-IP" assert.Equal(t, nil, Validate(o)) assert.Nil(t, o.GetRealClientIPParser()) // Ensure simple use case works. o = testOptions() o.ReverseProxy = true o.RealClientIPHeader = "X-Forwarded-For" assert.Equal(t, nil, Validate(o)) assert.NotNil(t, o.GetRealClientIPParser()) // Ensure unknown header format process an error. o = testOptions() o.ReverseProxy = true o.RealClientIPHeader = "Forwarded" err := Validate(o) assert.NotEqual(t, nil, err) expected := errorMsg([]string{ "real_client_ip_header (Forwarded) not accepted parameter value: the http header key (Forwarded) is either invalid or unsupported", }) assert.Equal(t, expected, err.Error()) assert.Nil(t, o.GetRealClientIPParser()) // Ensure invalid header format produces an error. o = testOptions() o.ReverseProxy = true o.RealClientIPHeader = "!934invalidheader-23:" err = Validate(o) assert.NotEqual(t, nil, err) expected = errorMsg([]string{ "real_client_ip_header (!934invalidheader-23:) not accepted parameter value: the http header key (!934invalidheader-23:) is either invalid or unsupported", }) assert.Equal(t, expected, err.Error()) assert.Nil(t, o.GetRealClientIPParser()) } func TestProviderCAFilesError(t *testing.T) { file, err := os.CreateTemp("", "absent.*.crt") assert.NoError(t, err) assert.NoError(t, file.Close()) assert.NoError(t, os.Remove(file.Name())) o := testOptions() o.Providers[0].CAFiles = append(o.Providers[0].CAFiles, file.Name()) err = Validate(o) assert.Error(t, err) assert.Contains(t, err.Error(), "unable to load provider CA file(s)") } func TestParseJwtIssuers(t *testing.T) { testCases := []struct { name string issuers []string jwksURLs []string expected []jwtIssuer msgs []string }{ { name: "issuer and audience without jwks url", issuers: []string{"https://issuer.example.com=client-id"}, expected: []jwtIssuer{ {issuerURI: "https://issuer.example.com", audience: "client-id"}, }, }, { name: "audience containing an equals sign", issuers: []string{"https://issuer.example.com=aud=with=equals"}, expected: []jwtIssuer{ {issuerURI: "https://issuer.example.com", audience: "aud=with=equals"}, }, }, { name: "explicit jwks url overrides the derived url", issuers: []string{"http://sts.example.com/adfs/services/trust=urn:microsoft:userinfo"}, jwksURLs: []string{"http://sts.example.com/adfs/services/trust=https://sts.example.com/adfs/discovery/keys"}, expected: []jwtIssuer{ { issuerURI: "http://sts.example.com/adfs/services/trust", audience: "urn:microsoft:userinfo", jwksURI: "https://sts.example.com/adfs/discovery/keys", }, }, }, { name: "jwks url containing an equals sign", issuers: []string{"https://issuer.example.com=client-id"}, jwksURLs: []string{"https://issuer.example.com=https://issuer.example.com/keys?format=jwks"}, expected: []jwtIssuer{ { issuerURI: "https://issuer.example.com", audience: "client-id", jwksURI: "https://issuer.example.com/keys?format=jwks", }, }, }, { name: "jwks url for an unrelated issuer is ignored", issuers: []string{"https://issuer.example.com=client-id"}, jwksURLs: []string{"https://other.example.com=https://other.example.com/keys"}, expected: []jwtIssuer{ {issuerURI: "https://issuer.example.com", audience: "client-id"}, }, }, { name: "invalid issuer spec is reported", issuers: []string{"https://issuer.example.com"}, expected: []jwtIssuer{}, msgs: []string{"invalid jwt verifier uri=audience spec: https://issuer.example.com"}, }, { name: "invalid jwks url spec is reported", issuers: []string{"https://issuer.example.com=client-id"}, jwksURLs: []string{"https://issuer.example.com"}, expected: []jwtIssuer{ {issuerURI: "https://issuer.example.com", audience: "client-id"}, }, msgs: []string{"invalid jwt issuer jwks url spec: https://issuer.example.com"}, }, { name: "empty jwks url value is reported", issuers: []string{"https://issuer.example.com=client-id"}, jwksURLs: []string{"https://issuer.example.com="}, expected: []jwtIssuer{ {issuerURI: "https://issuer.example.com", audience: "client-id"}, }, msgs: []string{"invalid jwt issuer jwks url spec: https://issuer.example.com="}, }, { name: "empty issuer in jwks url spec is reported", issuers: []string{"https://issuer.example.com=client-id"}, jwksURLs: []string{"=https://issuer.example.com/keys"}, expected: []jwtIssuer{ {issuerURI: "https://issuer.example.com", audience: "client-id"}, }, msgs: []string{"invalid jwt issuer jwks url spec: =https://issuer.example.com/keys"}, }, { name: "multiple issuers each with their own jwks url", issuers: []string{"https://a.example.com=aud-a", "https://b.example.com=aud-b"}, jwksURLs: []string{ "https://a.example.com=https://a.example.com/keys", "https://b.example.com=https://b.example.com/keys", }, expected: []jwtIssuer{ {issuerURI: "https://a.example.com", audience: "aud-a", jwksURI: "https://a.example.com/keys"}, {issuerURI: "https://b.example.com", audience: "aud-b", jwksURI: "https://b.example.com/keys"}, }, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { issuers, msgs := parseJwtIssuers(tc.issuers, tc.jwksURLs, nil) assert.Equal(t, tc.expected, issuers) assert.Equal(t, tc.msgs, msgs) }) } } func TestNewVerifierFromJwtIssuerWithExplicitJWKsURL(t *testing.T) { // An explicit JWKS URL must skip discovery entirely, so the verifier can be // constructed without reaching the issuer (the JWKS is fetched lazily). issuer := jwtIssuer{ issuerURI: "http://sts.example.com/adfs/services/trust", audience: "urn:microsoft:userinfo", jwksURI: "https://sts.example.com/adfs/discovery/keys", } verifier, err := newVerifierFromJwtIssuer(nil, nil, issuer) assert.NoError(t, err) assert.NotNil(t, verifier) }