Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

judge: Add endpoint for answering access requests directly #91

Merged
merged 1 commit into from
Jul 22, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 <[email protected]>
*
* 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 <[email protected]>
* @copyright 2017-2018 Aeneas Rekkas <[email protected]>
* @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 <[email protected]>
*
* 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 <[email protected]>
* @copyright 2017-2018 Aeneas Rekkas <[email protected]>
* @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)
})
}
}
Loading