git.iko.soy/typeable/oauth2-proxy
on master help sign in
Add force-json-errors flag
commitd3e036d6192b509e80a73aadef6033e381291a11 authorLuka Zakrajšek <luka@bancek.net> dateTue 5 Oct 2021, 11:24 (5 years ago) parentfd5e23e
6 files changed+34−15
CHANGELOG.md+1 contrib/oauth2-proxy_autocomplete.sh+1−1 docs/docs/configuration/overview.md+1 oauthproxy.go+11−2 oauthproxy_test.go+18−12 pkg/apis/options/options.go+2
CHANGELOG.md+1
@@ -21,6 +21,7 @@
2121- [#1315](https://github.com/oauth2-proxy/oauth2-proxy/pull/1315) linkedin: Update provider to v2 (@wuurrd)
2222- [#1348](https://github.com/oauth2-proxy/oauth2-proxy/pull/1348) Using the native httputil proxy code for websockets rather than yhat/wsutil to properly handle HTTP-level failures (@thetrime)
2323- [#1379](https://github.com/oauth2-proxy/oauth2-proxy/pull/1379) Fix the manual sign in with --htpasswd-user-group switch (@janrotter)
24+- [#1375](https://github.com/oauth2-proxy/oauth2-proxy/pull/1375) Added `--force-json-errors` flag (@bancek)
2425- [#1337](https://github.com/oauth2-proxy/oauth2-proxy/pull/1337) Changing user field type to text when using htpasswd (@pburgisser)
2526- [#1239](https://github.com/oauth2-proxy/oauth2-proxy/pull/1239) Base GitLab provider implementation on OIDCProvider (@NickMeves)
2627- [#1276](https://github.com/oauth2-proxy/oauth2-proxy/pull/1276) Update crypto and switched to new github.com/golang-jwt/jwt (@JVecsei)
contrib/oauth2-proxy_autocomplete.sh+1−1
@@ -24,7 +24,7 @@ _oauth2_proxy() {
2424 COMPREPLY=( $(compgen -W 'X-Real-IP X-Forwarded-For X-ProxyUser-IP' -- ${cur}) )
2525 return 0
2626 ;;
27− --@(http-address|https-address|redirect-url|upstream|basic-auth-password|skip-auth-regex|flush-interval|extra-jwt-issuers|email-domain|whitelist-domain|trusted-ip|keycloak-group|azure-tenant|bitbucket-team|bitbucket-repository|github-org|github-team|github-repo|github-token|gitlab-group|github-user|google-group|google-admin-email|google-service-account-json|client-id|client_secret|banner|footer|proxy-prefix|ping-path|cookie-name|cookie-secret|cookie-domain|cookie-path|cookie-expire|cookie-refresh|cookie-samesite|redist-sentinel-master-name|redist-sentinel-connection-urls|redist-cluster-connection-urls|logging-max-size|logging-max-age|logging-max-backups|standard-logging-format|request-logging-format|exclude-logging-paths|auth-logging-format|oidc-issuer-url|oidc-jwks-url|login-url|redeem-url|profile-url|resource|validate-url|scope|approval-prompt|signature-key|acr-values|jwt-key|pubjwk-url))
27+ --@(http-address|https-address|redirect-url|upstream|basic-auth-password|skip-auth-regex|flush-interval|extra-jwt-issuers|email-domain|whitelist-domain|trusted-ip|keycloak-group|azure-tenant|bitbucket-team|bitbucket-repository|github-org|github-team|github-repo|github-token|gitlab-group|github-user|google-group|google-admin-email|google-service-account-json|client-id|client_secret|banner|footer|proxy-prefix|ping-path|cookie-name|cookie-secret|cookie-domain|cookie-path|cookie-expire|cookie-refresh|cookie-samesite|redist-sentinel-master-name|redist-sentinel-connection-urls|redist-cluster-connection-urls|logging-max-size|logging-max-age|logging-max-backups|standard-logging-format|request-logging-format|exclude-logging-paths|auth-logging-format|oidc-issuer-url|oidc-jwks-url|login-url|redeem-url|profile-url|resource|validate-url|scope|approval-prompt|signature-key|acr-values|jwt-key|pubjwk-url|force-json-errors))
2828 return 0
2929 ;;
3030 esac
docs/docs/configuration/overview.md+1
@@ -103,6 +103,7 @@ An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/
103103| `--exclude-logging-paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` |`""` (no paths excluded) |
104104| `--flush-interval` | duration | period between flushing response buffers when streaming responses | `"1s"` |
105105| `--force-https` | bool | enforce https redirect | `false` |
106+| `--force-json-errors` | force JSON errors instead of HTTP error pages or redirects | `false` |
106107| `--banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | |
107108| `--footer` | string | custom (html) footer string. Use `"-"` to disable default footer. | |
108109| `--github-org` | string | restrict logins to members of this organisation | |
oauthproxy.go+11−2
@@ -82,6 +82,7 @@ type OAuthProxy struct {
8282 SkipProviderButton bool
8383 skipAuthPreflight bool
8484 skipJwtBearerTokens bool
85+ forceJSONErrors bool
8586 realClientIPParser ipapi.RealClientIPParser
8687 trustedIPs *ip.NetSet
8788
@@ -198,6 +199,7 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
198199 skipJwtBearerTokens: opts.SkipJwtBearerTokens,
199200 realClientIPParser: opts.GetRealClientIPParser(),
200201 SkipProviderButton: opts.SkipProviderButton,
202+ forceJSONErrors: opts.ForceJSONErrors,
201203 trustedIPs: trustedIPs,
202204
203205 basicAuthValidator: basicAuthValidator,
@@ -850,7 +852,7 @@ func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) {
850852 p.headersChain.Then(p.upstreamProxy).ServeHTTP(rw, req)
851853 case ErrNeedsLogin:
852854 // we need to send the user to a login screen
853− if isAjax(req) {
855+ if p.forceJSONErrors || isAjax(req) {
854856 // no point redirecting an AJAX request
855857 p.errorJSON(rw, http.StatusUnauthorized)
856858 return
@@ -863,7 +865,11 @@ func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) {
863865 }
864866
865867 case ErrAccessDenied:
866− p.ErrorPage(rw, req, http.StatusForbidden, "The session failed authorization checks")
868+ if p.forceJSONErrors {
869+ p.errorJSON(rw, http.StatusForbidden)
870+ } else {
871+ p.ErrorPage(rw, req, http.StatusForbidden, "The session failed authorization checks")
872+ }
867873
868874 default:
869875 // unknown error
@@ -1056,4 +1062,7 @@ func isAjax(req *http.Request) bool {
10561062func (p *OAuthProxy) errorJSON(rw http.ResponseWriter, code int) {
10571063 rw.Header().Set("Content-Type", applicationJSON)
10581064 rw.WriteHeader(code)
1065+ // we need to send some JSON response because we set the Content-Type to
1066+ // application/json
1067+ rw.Write([]byte("{}"))
10591068}
oauthproxy_test.go+18−12
@@ -1535,9 +1535,10 @@ type ajaxRequestTest struct {
15351535 proxy *OAuthProxy
15361536}
15371537
1538−func newAjaxRequestTest() (*ajaxRequestTest, error) {
1538+func newAjaxRequestTest(forceJSONErrors bool) (*ajaxRequestTest, error) {
15391539 test := &ajaxRequestTest{}
15401540 test.opts = baseTestOptions()
1541+ test.opts.ForceJSONErrors = forceJSONErrors
15411542 err := validation.Validate(test.opts)
15421543 if err != nil {
15431544 return nil, err
@@ -1552,59 +1553,64 @@ func newAjaxRequestTest() (*ajaxRequestTest, error) {
15521553 return test, nil
15531554}
15541555
1555−func (test *ajaxRequestTest) getEndpoint(endpoint string, header http.Header) (int, http.Header, error) {
1556+func (test *ajaxRequestTest) getEndpoint(endpoint string, header http.Header) (int, http.Header, []byte, error) {
15561557 rw := httptest.NewRecorder()
15571558 req, err := http.NewRequest(http.MethodGet, endpoint, strings.NewReader(""))
15581559 if err != nil {
1559− return 0, nil, err
1560+ return 0, nil, nil, err
15601561 }
15611562 req.Header = header
15621563 test.proxy.ServeHTTP(rw, req)
1563− return rw.Code, rw.Header(), nil
1564+ return rw.Code, rw.Header(), rw.Body.Bytes(), nil
15641565}
15651566
1566−func testAjaxUnauthorizedRequest(t *testing.T, header http.Header) {
1567− test, err := newAjaxRequestTest()
1567+func testAjaxUnauthorizedRequest(t *testing.T, header http.Header, forceJSONErrors bool) {
1568+ test, err := newAjaxRequestTest(forceJSONErrors)
15681569 if err != nil {
15691570 t.Fatal(err)
15701571 }
15711572 endpoint := "/test"
15721573
1573− code, rh, err := test.getEndpoint(endpoint, header)
1574+ code, rh, body, err := test.getEndpoint(endpoint, header)
15741575 assert.NoError(t, err)
15751576 assert.Equal(t, http.StatusUnauthorized, code)
15761577 mime := rh.Get("Content-Type")
15771578 assert.Equal(t, applicationJSON, mime)
1579+ assert.Equal(t, []byte("{}"), body)
15781580}
15791581func TestAjaxUnauthorizedRequest1(t *testing.T) {
15801582 header := make(http.Header)
15811583 header.Add("accept", applicationJSON)
15821584
1583− testAjaxUnauthorizedRequest(t, header)
1585+ testAjaxUnauthorizedRequest(t, header, false)
15841586}
15851587
15861588func TestAjaxUnauthorizedRequest2(t *testing.T) {
15871589 header := make(http.Header)
15881590 header.Add("Accept", applicationJSON)
15891591
1590− testAjaxUnauthorizedRequest(t, header)
1592+ testAjaxUnauthorizedRequest(t, header, false)
15911593}
15921594
15931595func TestAjaxUnauthorizedRequestAccept1(t *testing.T) {
15941596 header := make(http.Header)
15951597 header.Add("Accept", "application/json, text/plain, */*")
15961598
1597− testAjaxUnauthorizedRequest(t, header)
1599+ testAjaxUnauthorizedRequest(t, header, false)
1600+}
1601+
1602+func TestForceJSONErrorsUnauthorizedRequest(t *testing.T) {
1603+ testAjaxUnauthorizedRequest(t, nil, true)
15981604}
15991605
16001606func TestAjaxForbiddendRequest(t *testing.T) {
1601− test, err := newAjaxRequestTest()
1607+ test, err := newAjaxRequestTest(false)
16021608 if err != nil {
16031609 t.Fatal(err)
16041610 }
16051611 endpoint := "/test"
16061612 header := make(http.Header)
1607− code, rh, err := test.getEndpoint(endpoint, header)
1613+ code, rh, _, err := test.getEndpoint(endpoint, header)
16081614 assert.NoError(t, err)
16091615 assert.Equal(t, http.StatusForbidden, code)
16101616 mime := rh.Get("Content-Type")
pkg/apis/options/options.go+2
@@ -58,6 +58,7 @@ type Options struct {
5858 SkipProviderButton bool `flag:"skip-provider-button" cfg:"skip_provider_button"`
5959 SSLInsecureSkipVerify bool `flag:"ssl-insecure-skip-verify" cfg:"ssl_insecure_skip_verify"`
6060 SkipAuthPreflight bool `flag:"skip-auth-preflight" cfg:"skip_auth_preflight"`
61+ ForceJSONErrors bool `flag:"force-json-errors" cfg:"force_json_errors"`
6162
6263 SignatureKey string `flag:"signature-key" cfg:"signature_key"`
6364 GCPHealthChecks bool `flag:"gcp-healthchecks" cfg:"gcp_healthchecks"`
@@ -121,6 +122,7 @@ func NewFlagSet() *pflag.FlagSet {
121122 flagSet.Bool("skip-auth-preflight", false, "will skip authentication for OPTIONS requests")
122123 flagSet.Bool("ssl-insecure-skip-verify", false, "skip validation of certificates presented when using HTTPS providers")
123124 flagSet.Bool("skip-jwt-bearer-tokens", false, "will skip requests that have verified JWT bearer tokens (default false)")
125+ flagSet.Bool("force-json-errors", false, "will force JSON errors instead of HTTP error pages or redirects")
124126 flagSet.StringSlice("extra-jwt-issuers", []string{}, "if skip-jwt-bearer-tokens is set, a list of extra JWT issuer=audience pairs (where the issuer URL has a .well-known/openid-configuration or a .well-known/jwks.json)")
125127
126128 flagSet.StringSlice("email-domain", []string{}, "authenticate emails with the specified domain (may be given multiple times). Use * to authenticate any email")