Skip to content

Commit

Permalink
judge: Add endpoint for answering access requests directly
Browse files Browse the repository at this point in the history
This patch adds endpoint `/judge` to `oathkeeper serve api`. The `/judge` endpoint mimics the behavior of `oathkeeper serve proxy` but instead of forwarding the request to the upstream server, the endpoint answers directly with a HTTP response.

The HTTP response returns status code 200 if the request should be allowed and any other status code (e.g. 401, 403) if not.

Assuming you are making the following request:

```
PUT /judge/my-service/whatever HTTP/1.1
Host: oathkeeper-api:4456
User-Agent: curl/7.54.0
Authorization: bearer some-token
Accept: */*
Content-Type: application/json
Content-Length: 0
```

And you have a rule which allows token `some-bearer` to access `PUT /my-service/whatever` and you have a credentials issuer which does not modify the Authorization header, the response will be:

```
HTTP/1.1 200 OK
Authorization: bearer-sometoken
Content-Length: 0
Connection: Closed
```

If the rule denies the request, the response will be, for example:

```
HTTP/1.1 401 OK
Content-Length: 0
Connection: Closed
```

Close #42

Signed-off-by: arekkas <aeneas@ory.am>
  • Loading branch information
arekkas committed Jul 22, 2018
1 parent d0ad502 commit ecb2b03
Show file tree
Hide file tree
Showing 8 changed files with 487 additions and 5 deletions.
12 changes: 10 additions & 2 deletions cmd/serve_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import (
"github.com/ory/graceful"
"github.com/ory/herodot"
"github.com/ory/metrics-middleware"
"github.com/ory/oathkeeper/judge"
"github.com/ory/oathkeeper/proxy"
"github.com/ory/oathkeeper/rsakey"
"github.com/ory/oathkeeper/rule"
"github.com/rs/cors"
Expand Down Expand Up @@ -78,17 +80,23 @@ HTTP CONTROLS
logger.WithError(err).Fatalln("Unable to initialize the ID Token signing algorithm")
}

matcher := rule.NewCachedMatcher(rules)

enabledAuthenticators, enabledAuthorizers, enabledCredentialIssuers := enabledHandlerNames()
availableAuthenticators, availableAuthorizers, availableCredentialIssuers := availableHandlerNames()

authenticators, authorizers, credentialIssuers := handlerFactories(keyManager)
eval := proxy.NewRequestHandler(logger, authenticators, authorizers, credentialIssuers)

router := httprouter.New()
writer := herodot.NewJSONWriter(logger)
ruleHandler := rule.NewHandler(writer, rules, rule.ValidateRule(
enabledAuthenticators, availableAuthenticators,
enabledAuthorizers, availableAuthorizers,
enabledCredentialIssuers, availableCredentialIssuers,
))
judgeHandler := judge.NewHandler(eval, logger, matcher, router)
keyHandler := rsakey.NewHandler(writer, keyManager)
router := httprouter.New()
health := newHealthHandler(db, writer, router)
ruleHandler.SetRoutes(router)
keyHandler.SetRoutes(router)
Expand All @@ -113,7 +121,7 @@ HTTP CONTROLS
n.Use(segmentMiddleware)
}

n.UseHandler(router)
n.UseHandler(judgeHandler)
ch := cors.New(corsx.ParseOptions()).Handler(n)

go refreshKeys(keyManager)
Expand Down
31 changes: 31 additions & 0 deletions docs/api.swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,37 @@
}
}
},
"/judge": {
"get": {
"description": "This endpoint mirrors the proxy capability of ORY Oathkeeper's proxy functionality but instead of forwarding the\nrequest to the upstream server, returns 200 (request should be allowed), 401 (unauthorized), or 403 (forbidden)\nstatus codes. This endpoint can be used to integrate with other API Proxies like Ambassador, Kong, Envoy, and many more.",
"schemes": [
"http",
"https"
],
"tags": [
"judge"
],
"summary": "Judge if a request should be allowed or not",
"operationId": "judge",
"responses": {
"200": {
"$ref": "#/responses/emptyResponse"
},
"401": {
"$ref": "#/responses/genericError"
},
"403": {
"$ref": "#/responses/genericError"
},
"404": {
"$ref": "#/responses/genericError"
},
"500": {
"$ref": "#/responses/genericError"
}
}
}
},
"/rules": {
"get": {
"description": "This method returns an array of all rules that are stored in the backend. This is useful if you want to get a full\nview of what rules you have currently in place.",
Expand Down
118 changes: 118 additions & 0 deletions judge/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* Copyright © 2017-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Aeneas Rekkas <aeneas+oss@aeneas.io>
* @copyright 2017-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
* @license Apache-2.0
*/

package judge

import (
"net/http"

"github.com/julienschmidt/httprouter"
"github.com/ory/herodot"
"github.com/ory/oathkeeper/proxy"
"github.com/ory/oathkeeper/rsakey"
"github.com/ory/oathkeeper/rule"
"github.com/sirupsen/logrus"
)

const (
JudgePath = "/judge"
)

func NewHandler(handler *proxy.RequestHandler, logger logrus.FieldLogger, matcher rule.Matcher, router *httprouter.Router) *Handler {
if logger == nil {
logger = logrus.New()
}
return &Handler{
Logger: logger,
Matcher: matcher,
RequestHandler: handler,
H: herodot.NewNegotiationHandler(logger),
Router: router,
}
}

type Handler struct {
Logger logrus.FieldLogger
RequestHandler *proxy.RequestHandler
KeyManager rsakey.Manager
Matcher rule.Matcher
H herodot.Writer
Router *httprouter.Router
}

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if len(r.URL.Path) >= len(JudgePath) && r.URL.Path[:len(JudgePath)] == JudgePath {
r.URL.Scheme = "http"
r.URL.Host = r.Host
if r.TLS != nil {
r.URL.Scheme = "https"
}
r.URL.Path = r.URL.Path[len(JudgePath):]

h.judge(w, r)
} else {
h.Router.ServeHTTP(w, r)
}
}

// swagger:route GET /judge judge judge
//
// Judge if a request should be allowed or not
//
// This endpoint mirrors the proxy capability of ORY Oathkeeper's proxy functionality but instead of forwarding the
// request to the upstream server, returns 200 (request should be allowed), 401 (unauthorized), or 403 (forbidden)
// status codes. This endpoint can be used to integrate with other API Proxies like Ambassador, Kong, Envoy, and many more.
//
// Schemes: http, https
//
// Responses:
// 200: emptyResponse
// 401: genericError
// 403: genericError
// 404: genericError
// 500: genericError
func (h *Handler) judge(w http.ResponseWriter, r *http.Request) {
rl, err := h.Matcher.MatchRule(r.Method, r.URL)
if err != nil {
h.Logger.WithError(err).
WithField("granted", false).
WithField("access_url", r.URL.String()).
Warn("Access request denied")
h.H.WriteError(w, r, err)
return
}

if err := h.RequestHandler.HandleRequest(r, rl); err != nil {
h.Logger.WithError(err).
WithField("granted", false).
WithField("access_url", r.URL.String()).
Warn("Access request denied")
h.H.WriteError(w, r, err)
return
}

h.Logger.
WithField("granted", true).
WithField("access_url", r.URL.String()).
Warn("Access request granted")

w.Header().Set("Authorization", r.Header.Get("Authorization"))
w.WriteHeader(http.StatusOK)
}
196 changes: 196 additions & 0 deletions judge/handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/*
* Copyright © 2017-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Aeneas Rekkas <aeneas+oss@aeneas.io>
* @copyright 2017-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
* @license Apache-2.0
*/

package judge

import (
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"testing"

"github.com/julienschmidt/httprouter"
"github.com/ory/oathkeeper/proxy"
"github.com/ory/oathkeeper/rule"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestProxy(t *testing.T) {
matcher := &rule.CachedMatcher{Rules: map[string]rule.Rule{}}
rh := proxy.NewRequestHandler(
nil,
[]proxy.Authenticator{proxy.NewAuthenticatorNoOp(), proxy.NewAuthenticatorAnonymous("anonymous"), proxy.NewAuthenticatorBroken()},
[]proxy.Authorizer{proxy.NewAuthorizerAllow(), proxy.NewAuthorizerDeny()},
[]proxy.CredentialsIssuer{proxy.NewCredentialsIssuerNoOp(), proxy.NewCredentialsIssuerBroken()},
)

router := httprouter.New()
d := NewHandler(rh, nil, matcher, router)

ts := httptest.NewServer(d)
defer ts.Close()

ruleNoOpAuthenticator := rule.Rule{
Match: rule.RuleMatch{Methods: []string{"GET"}, URL: ts.URL + "/authn-noop/<[0-9]+>"},
Authenticators: []rule.RuleHandler{{Handler: "noop"}},
Upstream: rule.Upstream{URL: ""},
}
ruleNoOpAuthenticatorModifyUpstream := rule.Rule{
Match: rule.RuleMatch{Methods: []string{"GET"}, URL: ts.URL + "/strip-path/authn-noop/<[0-9]+>"},
Authenticators: []rule.RuleHandler{{Handler: "noop"}},
Upstream: rule.Upstream{URL: "", StripPath: "/strip-path/", PreserveHost: true},
}

for k, tc := range []struct {
url string
code int
messages []string
rules []rule.Rule
transform func(r *http.Request)
authz string
d string
}{
{
d: "should fail because url does not exist in rule set",
url: ts.URL + "/judge" + "/invalid",
rules: []rule.Rule{},
code: http.StatusNotFound,
},
{
d: "should fail because url does exist but is matched by two rules",
url: ts.URL + "/judge" + "/authn-noop/1234",
rules: []rule.Rule{ruleNoOpAuthenticator, ruleNoOpAuthenticator},
code: http.StatusInternalServerError,
},
{
d: "should pass",
url: ts.URL + "/judge" + "/authn-noop/1234",
rules: []rule.Rule{ruleNoOpAuthenticator},
code: http.StatusOK,
transform: func(r *http.Request) {
r.Header.Add("Authorization", "bearer token")
},
authz: "bearer token",
},
{
d: "should pass",
url: ts.URL + "/judge" + "/strip-path/authn-noop/1234",
rules: []rule.Rule{ruleNoOpAuthenticatorModifyUpstream},
code: http.StatusOK,
transform: func(r *http.Request) {
r.Header.Add("Authorization", "bearer token")
},
authz: "bearer token",
},
{
d: "should fail because no authorizer was configured",
url: ts.URL + "/judge" + "/authn-anon/authz-none/cred-none/1234",
rules: []rule.Rule{{
Match: rule.RuleMatch{Methods: []string{"GET"}, URL: ts.URL + "/authn-anon/authz-none/cred-none/<[0-9]+>"},
Authenticators: []rule.RuleHandler{{Handler: "anonymous"}},
Upstream: rule.Upstream{URL: ""},
}},
transform: func(r *http.Request) {
r.Header.Add("Authorization", "bearer token")
},
code: http.StatusUnauthorized,
},
{
d: "should fail because no credentials issuer was configured",
url: ts.URL + "/judge" + "/authn-anon/authz-allow/cred-none/1234",
rules: []rule.Rule{{
Match: rule.RuleMatch{Methods: []string{"GET"}, URL: ts.URL + "/authn-anon/authz-allow/cred-none/<[0-9]+>"},
Authenticators: []rule.RuleHandler{{Handler: "anonymous"}},
Authorizer: rule.RuleHandler{Handler: "allow"},
Upstream: rule.Upstream{URL: ""},
}},
code: http.StatusInternalServerError,
},
{
d: "should pass with anonymous and everything else set to noop",
url: ts.URL + "/judge" + "/authn-anon/authz-allow/cred-noop/1234",
rules: []rule.Rule{{
Match: rule.RuleMatch{Methods: []string{"GET"}, URL: ts.URL + "/authn-anon/authz-allow/cred-noop/<[0-9]+>"},
Authenticators: []rule.RuleHandler{{Handler: "anonymous"}},
Authorizer: rule.RuleHandler{Handler: "allow"},
CredentialsIssuer: rule.RuleHandler{Handler: "noop"},
Upstream: rule.Upstream{URL: ""},
}},
code: http.StatusOK,
authz: "",
},
{
d: "should fail when authorizer fails",
url: ts.URL + "/judge" + "/authn-anon/authz-deny/cred-noop/1234",
rules: []rule.Rule{{
Match: rule.RuleMatch{Methods: []string{"GET"}, URL: ts.URL + "/authn-anon/authz-deny/cred-noop/<[0-9]+>"},
Authenticators: []rule.RuleHandler{{Handler: "anonymous"}},
Authorizer: rule.RuleHandler{Handler: "deny"},
CredentialsIssuer: rule.RuleHandler{Handler: "noop"},
Upstream: rule.Upstream{URL: ""},
}},
code: http.StatusForbidden,
},
{
d: "should fail when authenticator fails",
url: ts.URL + "/judge" + "/authn-broken/authz-none/cred-none/1234",
rules: []rule.Rule{{
Match: rule.RuleMatch{Methods: []string{"GET"}, URL: ts.URL + "/authn-broken/authz-none/cred-none/<[0-9]+>"},
Authenticators: []rule.RuleHandler{{Handler: "broken"}},
Upstream: rule.Upstream{URL: ""},
}},
code: http.StatusUnauthorized,
},
{
d: "should fail when credentials issuer fails",
url: ts.URL + "/judge" + "/authn-anonymous/authz-allow/cred-broken/1234",
rules: []rule.Rule{{
Match: rule.RuleMatch{Methods: []string{"GET"}, URL: ts.URL + "/authn-anonymous/authz-allow/cred-broken/<[0-9]+>"},
Authenticators: []rule.RuleHandler{{Handler: "anonymous"}},
Authorizer: rule.RuleHandler{Handler: "allow"},
CredentialsIssuer: rule.RuleHandler{Handler: "broken"},
Upstream: rule.Upstream{URL: ""},
}},
code: http.StatusInternalServerError,
},
} {
t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) {
matcher.Rules = map[string]rule.Rule{}
for k, r := range tc.rules {
matcher.Rules[strconv.Itoa(k)] = r
}

req, err := http.NewRequest("GET", tc.url, nil)
require.NoError(t, err)
if tc.transform != nil {
tc.transform(req)
}

res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()

assert.Equal(t, res.Header.Get("Authorization"), tc.authz)
assert.Equal(t, tc.code, res.StatusCode)
})
}
}

0 comments on commit ecb2b03

Please sign in to comment.