Skip to content

create custom forward request authenticator #949

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
8 changes: 8 additions & 0 deletions .codeclimate.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
version: "2"
plugins:
gofmt:
enabled: true
golint:
enabled: true
govet:
enabled: true
23 changes: 23 additions & 0 deletions .schemas/authenticators.remote_json.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"$id": "https://raw.githubusercontent.com/ory/oathkeeper/master/.schemas/authenticators.cookie_session.schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"title": "Forward Authenticator Configuration",
"description": "This section is optional when the authenticator is disabled.",
"properties": {
"service_url": {
"title": "Service URL",
"type": "string",
"format": "uri",
"description": "The origin to proxy requests to. If the response is a 200 with body `{ \"subject\": \"...\", \"extra\": {} }`. The request will pass the subject through successfully, otherwise it will be marked as unauthorized.\n\n>If this authenticator is enabled, this value is required.",
"examples": ["https://service-host"]
},
"preserve_path": {
"title": "Preserve Path",
"type": "boolean",
"description": "When set to true, any path specified in `check_session_url` will be preserved instead of overwriting the path with the path from the original request"
}
},
"required": ["service_url"],
"additionalProperties": false
}
1 change: 1 addition & 0 deletions driver/registry_memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ func (r *RegistryMemory) prepareAuthn() {
authn.NewAuthenticatorOAuth2ClientCredentials(r.c, r.Logger()),
authn.NewAuthenticatorOAuth2Introspection(r.c, r.Logger()),
authn.NewAuthenticatorUnauthorized(r.c),
authn.NewAuthenticatorRemoteJSON(r.c),
}

r.authenticators = map[string]authn.Authenticator{}
Expand Down
185 changes: 185 additions & 0 deletions pipeline/authn/authenticator_remote_json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
package authn

import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/url"

"github.com/pkg/errors"
"github.com/tidwall/gjson"

"github.com/ory/go-convenience/stringsx"

"github.com/ory/herodot"

"github.com/ory/oathkeeper/driver/configuration"
"github.com/ory/oathkeeper/helper"
"github.com/ory/oathkeeper/pipeline"
)

func init() {
gjson.AddModifier("this", func(json, arg string) string {
return json
})
}

type AuthenticatorRemoteJSONFilter struct {
}

type AuthenticatorRemoteJSONConfiguration struct {
ServiceURL string `json:"service_url"`
PreservePath bool `json:"preserve_path"`
ExtraFrom string `json:"extra_from"`
SubjectFrom string `json:"subject_from"`
Method string `json:"method"`
UseOriginalMethod bool `json:"use_original_method"`
}

type AuthenticatorRemoteJSON struct {
c configuration.Provider
}

func NewAuthenticatorRemoteJSON(c configuration.Provider) *AuthenticatorRemoteJSON {
return &AuthenticatorRemoteJSON{
c: c,
}
}

func (a *AuthenticatorRemoteJSON) GetID() string {
return "remote_json"
}

func (a *AuthenticatorRemoteJSON) Validate(config json.RawMessage) error {
if !a.c.AuthenticatorIsEnabled(a.GetID()) {
return NewErrAuthenticatorNotEnabled(a)

Check warning on line 56 in pipeline/authn/authenticator_remote_json.go

View check run for this annotation

Codecov / codecov/patch

pipeline/authn/authenticator_remote_json.go#L54-L56

Added lines #L54 - L56 were not covered by tests
}

_, err := a.Config(config)
return err

Check warning on line 60 in pipeline/authn/authenticator_remote_json.go

View check run for this annotation

Codecov / codecov/patch

pipeline/authn/authenticator_remote_json.go#L59-L60

Added lines #L59 - L60 were not covered by tests
}

func (a *AuthenticatorRemoteJSON) Config(config json.RawMessage) (*AuthenticatorRemoteJSONConfiguration, error) {
var c AuthenticatorRemoteJSONConfiguration
if err := a.c.AuthenticatorConfig(a.GetID(), config, &c); err != nil {
return nil, NewErrAuthenticatorMisconfigured(a, err)

Check warning on line 66 in pipeline/authn/authenticator_remote_json.go

View check run for this annotation

Codecov / codecov/patch

pipeline/authn/authenticator_remote_json.go#L66

Added line #L66 was not covered by tests
}

return &c, nil
}

func (a *AuthenticatorRemoteJSON) Authenticate(r *http.Request, session *AuthenticationSession, config json.RawMessage, _ pipeline.Rule) error {
cfg, err := a.Config(config)
if err != nil {
return err

Check warning on line 75 in pipeline/authn/authenticator_remote_json.go

View check run for this annotation

Codecov / codecov/patch

pipeline/authn/authenticator_remote_json.go#L75

Added line #L75 was not covered by tests
}

method := forwardMethod(r, cfg)

body, err := forwardRequestToAuthenticator(r, method, cfg.ServiceURL, cfg.PreservePath)
if err != nil {
return err
}

var (
subject string
extra map[string]interface{}

subjectRaw = []byte(stringsx.Coalesce(gjson.GetBytes(body, cfg.SubjectFrom).Raw, "null"))
extraRaw = []byte(stringsx.Coalesce(gjson.GetBytes(body, cfg.ExtraFrom).Raw, "null"))
)

if err = json.Unmarshal(subjectRaw, &subject); err != nil {
return helper.
ErrForbidden.
WithReasonf("The configured subject_from GJSON path returned an error on JSON output: %s", err.Error()).
WithDebugf("GJSON path: %s\nBody: %s\nResult: %s", cfg.SubjectFrom, body, subjectRaw).
WithTrace(err)

Check warning on line 98 in pipeline/authn/authenticator_remote_json.go

View check run for this annotation

Codecov / codecov/patch

pipeline/authn/authenticator_remote_json.go#L94-L98

Added lines #L94 - L98 were not covered by tests
}

if err = json.Unmarshal(extraRaw, &extra); err != nil {
return helper.
ErrForbidden.
WithReasonf("The configured extra_from GJSON path returned an error on JSON output: %s", err.Error()).
WithDebugf("GJSON path: %s\nBody: %s\nResult: %s", cfg.ExtraFrom, body, extraRaw).
WithTrace(err)

Check warning on line 106 in pipeline/authn/authenticator_remote_json.go

View check run for this annotation

Codecov / codecov/patch

pipeline/authn/authenticator_remote_json.go#L102-L106

Added lines #L102 - L106 were not covered by tests
}

session.Subject = subject
session.Extra = extra
return nil
}

func forwardMethod(r *http.Request, cfg *AuthenticatorRemoteJSONConfiguration) string {
method := cfg.Method
if len(method) == 0 {
if cfg.UseOriginalMethod {
return r.Method
} else {
return http.MethodPost
}
}
return cfg.Method
}

func forwardRequestToAuthenticator(r *http.Request, method string, serviceURL string, preservePath bool) (json.RawMessage, error) {
reqUrl, err := url.Parse(serviceURL)
if err != nil {
return nil, errors.WithStack(
herodot.
ErrInternalServerError.WithReasonf("Unable to parse remote URL: %s", err),
)

Check warning on line 132 in pipeline/authn/authenticator_remote_json.go

View check run for this annotation

Codecov / codecov/patch

pipeline/authn/authenticator_remote_json.go#L129-L132

Added lines #L129 - L132 were not covered by tests
}

if !preservePath {
reqUrl.Path = r.URL.Path
}

var forwardRequestBody io.ReadCloser = nil
if r.Body != nil {
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, helper.ErrBadRequest.WithReason(err.Error()).WithTrace(err)

Check warning on line 143 in pipeline/authn/authenticator_remote_json.go

View check run for this annotation

Codecov / codecov/patch

pipeline/authn/authenticator_remote_json.go#L143

Added line #L143 was not covered by tests
}

err = r.Body.Close()
if err != nil {
return nil, errors.WithStack(
herodot.
ErrInternalServerError.
WithReasonf("Could not close body reader: %s\n", err),
)

Check warning on line 152 in pipeline/authn/authenticator_remote_json.go

View check run for this annotation

Codecov / codecov/patch

pipeline/authn/authenticator_remote_json.go#L148-L152

Added lines #L148 - L152 were not covered by tests
}

// Unfortunately the body reader needs to be read once to forward the request,
// thus the upstream request will fail miserably without recreating a fresh ReaderCloser
forwardRequestBody = io.NopCloser(bytes.NewReader(body))
r.Body = io.NopCloser(bytes.NewReader(body))
}

req := http.Request{
Method: method,
URL: reqUrl,
Header: r.Header,
Body: forwardRequestBody,
}
res, err := http.DefaultClient.Do(req.WithContext(r.Context()))
if err != nil {
return nil, helper.ErrForbidden.WithReason(err.Error()).WithTrace(err)

Check warning on line 169 in pipeline/authn/authenticator_remote_json.go

View check run for this annotation

Codecov / codecov/patch

pipeline/authn/authenticator_remote_json.go#L169

Added line #L169 was not covered by tests
}

return handleResponse(res)
}

func handleResponse(r *http.Response) (json.RawMessage, error) {
if r.StatusCode == http.StatusOK {
body, err := io.ReadAll(r.Body)
if err != nil {
return json.RawMessage{}, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("Remote server returned error: %+v", err))

Check warning on line 179 in pipeline/authn/authenticator_remote_json.go

View check run for this annotation

Codecov / codecov/patch

pipeline/authn/authenticator_remote_json.go#L179

Added line #L179 was not covered by tests
}
return body, nil
} else {
return json.RawMessage{}, errors.WithStack(helper.ErrUnauthorized)
}
}
Loading