envoy: Initial changes

This commit is contained in:
Travis Groth 2020-05-18 16:34:31 -04:00
parent 8f78497e99
commit 99e788a9b4
107 changed files with 2542 additions and 3322 deletions

View file

@ -107,7 +107,6 @@ func (p *Proxy) Verify(verifyOnly bool) http.Handler {
if uriString == "" {
if r.Header.Get(httputil.HeaderForwardedProto) == "" || r.Header.Get(httputil.HeaderForwardedHost) == "" {
return httputil.NewError(http.StatusBadRequest, errors.New("no uri to validate"))
}
uriString = r.Header.Get(httputil.HeaderForwardedProto) + "://" + r.Header.Get(httputil.HeaderForwardedHost)
}
@ -116,32 +115,38 @@ func (p *Proxy) Verify(verifyOnly bool) http.Handler {
if err != nil {
return httputil.NewError(http.StatusBadRequest, err)
}
originalRequest := p.getOriginalRequest(r, uri)
authz, err := p.authorize(w, originalRequest)
original := p.getOriginalRequest(r, uri)
authorized, err := p.isAuthorized(original)
if err != nil {
// no session, so redirect
if _, err := sessions.FromContext(r.Context()); err != nil {
if verifyOnly {
return httputil.NewError(http.StatusUnauthorized, err)
}
authN := *p.authenticateSigninURL
q := authN.Query()
q.Set(urlutil.QueryCallbackURI, uri.String())
q.Set(urlutil.QueryRedirectURI, uri.String()) // final destination
q.Set(urlutil.QueryForwardAuth, urlutil.StripPort(r.Host)) // add fwd auth to trusted audience
authN.RawQuery = q.Encode()
httputil.Redirect(w, r, urlutil.NewSignedURL(p.SharedKey, &authN).String(), http.StatusFound)
return nil
}
return err
return httputil.NewError(http.StatusBadRequest, err)
}
w.Header().Set(httputil.HeaderPomeriumJWTAssertion, authz.GetSignedJwt())
if authorized {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Access to %s is allowed.", uri.Host)
return nil
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Access to %s is allowed.", uri.Host)
_, err = sessions.FromContext(r.Context())
hasSession := err == nil
if hasSession {
return httputil.NewError(http.StatusForbidden, errors.New("access denied"))
}
if verifyOnly {
return httputil.NewError(http.StatusUnauthorized, err)
}
// redirect to authenticate
authN := *p.authenticateSigninURL
q := authN.Query()
q.Set(urlutil.QueryCallbackURI, uri.String())
q.Set(urlutil.QueryRedirectURI, uri.String()) // final destination
q.Set(urlutil.QueryForwardAuth, urlutil.StripPort(r.Host)) // add fwd auth to trusted audience
authN.RawQuery = q.Encode()
httputil.Redirect(w, r, urlutil.NewSignedURL(p.SharedKey, &authN).String(), http.StatusFound)
return nil
})
}

View file

@ -1,30 +1,46 @@
package proxy
import (
"errors"
"context"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
envoy_service_auth_v2 "github.com/envoyproxy/go-control-plane/envoy/service/auth/v2"
"github.com/google/go-cmp/cmp"
"google.golang.org/grpc"
"gopkg.in/square/go-jose.v2/jwt"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/encoding"
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/internal/encoding/mock"
pb "github.com/pomerium/pomerium/internal/grpc/authorize"
"github.com/pomerium/pomerium/internal/grpc/authorize/client"
"github.com/pomerium/pomerium/internal/httputil"
"github.com/pomerium/pomerium/internal/sessions"
mstore "github.com/pomerium/pomerium/internal/sessions/mock"
"github.com/pomerium/pomerium/internal/urlutil"
)
type mockCheckClient struct {
response *envoy_service_auth_v2.CheckResponse
err error
}
func (m *mockCheckClient) Check(ctx context.Context, in *envoy_service_auth_v2.CheckRequest, opts ...grpc.CallOption) (*envoy_service_auth_v2.CheckResponse, error) {
return m.response, m.err
}
func TestProxy_ForwardAuth(t *testing.T) {
t.Parallel()
allowClient := &mockCheckClient{
response: &envoy_service_auth_v2.CheckResponse{
HttpResponse: &envoy_service_auth_v2.CheckResponse_OkResponse{},
},
}
opts := testOptions(t)
tests := []struct {
name string
@ -40,31 +56,27 @@ func TestProxy_ForwardAuth(t *testing.T) {
cipher encoding.MarshalUnmarshaler
sessionStore sessions.SessionStore
authorizer client.Authorizer
authorizer envoy_service_auth_v2.AuthorizationClient
wantStatus int
wantBody string
}{
{"good redirect not required", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusOK, "Access to some.domain.example is allowed."},
{"good verify only, no redirect", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/verify", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusOK, ""},
{"bad empty domain uri", opts, nil, http.MethodGet, nil, map[string]string{"uri": ""}, "https://some.domain.example/", "", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusBadRequest, "{\"Status\":400,\"Error\":\"Bad Request: no uri to validate\"}\n"},
{"bad naked domain uri", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/", "a.naked.domain", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusBadRequest, "{\"Status\":400,\"Error\":\"Bad Request: a.naked.domain url does contain a valid scheme\"}\n"},
{"bad naked domain uri verify only", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/verify", "a.naked.domain", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusBadRequest, "{\"Status\":400,\"Error\":\"Bad Request: a.naked.domain url does contain a valid scheme\"}\n"},
{"bad empty verification uri", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/", " ", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusBadRequest, "{\"Status\":400,\"Error\":\"Bad Request: %20 url does contain a valid scheme\"}\n"},
{"bad empty verification uri verify only", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/verify", " ", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusBadRequest, "{\"Status\":400,\"Error\":\"Bad Request: %20 url does contain a valid scheme\"}\n"},
{"not authorized", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: false}}, http.StatusForbidden, "{\"Status\":403,\"Error\":\"Forbidden: request denied\"}\n"},
{"not authorized verify endpoint", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/verify", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: false}}, http.StatusForbidden, "{\"Status\":403,\"Error\":\"Forbidden: request denied\"}\n"},
{"not authorized because of error", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeError: errors.New("authz error")}, http.StatusInternalServerError, "{\"Status\":500,\"Error\":\"Internal Server Error: authz error\"}\n"},
{"expired", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(-10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: false}}, http.StatusForbidden, "{\"Status\":403,\"Error\":\"Forbidden: request denied\"}\n"},
{"good redirect not required", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusOK, "Access to some.domain.example is allowed."},
{"good verify only, no redirect", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/verify", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusOK, ""},
{"bad empty domain uri", opts, nil, http.MethodGet, nil, map[string]string{"uri": ""}, "https://some.domain.example/", "", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusBadRequest, "{\"Status\":400,\"Error\":\"Bad Request: no uri to validate\"}\n"},
{"bad naked domain uri", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/", "a.naked.domain", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusBadRequest, "{\"Status\":400,\"Error\":\"Bad Request: a.naked.domain url does contain a valid scheme\"}\n"},
{"bad naked domain uri verify only", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/verify", "a.naked.domain", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusBadRequest, "{\"Status\":400,\"Error\":\"Bad Request: a.naked.domain url does contain a valid scheme\"}\n"},
{"bad empty verification uri", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/", " ", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusBadRequest, "{\"Status\":400,\"Error\":\"Bad Request: %20 url does contain a valid scheme\"}\n"},
{"bad empty verification uri verify only", opts, nil, http.MethodGet, nil, nil, "https://some.domain.example/verify", " ", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusBadRequest, "{\"Status\":400,\"Error\":\"Bad Request: %20 url does contain a valid scheme\"}\n"},
// traefik
{"good traefik callback", opts, nil, http.MethodGet, map[string]string{httputil.HeaderForwardedURI: "https://some.domain.example?" + urlutil.QuerySessionEncrypted + "=" + goodEncryptionString}, nil, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusFound, ""},
{"bad traefik callback bad session", opts, nil, http.MethodGet, map[string]string{httputil.HeaderForwardedURI: "https://some.domain.example?" + urlutil.QuerySessionEncrypted + "=" + goodEncryptionString + "garbage"}, nil, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusBadRequest, ""},
{"bad traefik callback bad url", opts, nil, http.MethodGet, map[string]string{httputil.HeaderForwardedURI: urlutil.QuerySessionEncrypted + ""}, nil, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusBadRequest, ""},
{"good traefik verify uri from headers", opts, nil, http.MethodGet, map[string]string{httputil.HeaderForwardedProto: "https", httputil.HeaderForwardedHost: "some.domain.example:8080"}, nil, "https://some.domain.example/", "", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusOK, ""},
{"good traefik callback", opts, nil, http.MethodGet, map[string]string{httputil.HeaderForwardedURI: "https://some.domain.example?" + urlutil.QuerySessionEncrypted + "=" + goodEncryptionString}, nil, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusFound, ""},
{"bad traefik callback bad session", opts, nil, http.MethodGet, map[string]string{httputil.HeaderForwardedURI: "https://some.domain.example?" + urlutil.QuerySessionEncrypted + "=" + goodEncryptionString + "garbage"}, nil, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusBadRequest, ""},
{"bad traefik callback bad url", opts, nil, http.MethodGet, map[string]string{httputil.HeaderForwardedURI: urlutil.QuerySessionEncrypted + ""}, nil, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusBadRequest, ""},
{"good traefik verify uri from headers", opts, nil, http.MethodGet, map[string]string{httputil.HeaderForwardedProto: "https", httputil.HeaderForwardedHost: "some.domain.example:8080"}, nil, "https://some.domain.example/", "", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusOK, ""},
// // nginx
{"good nginx callback redirect", opts, nil, http.MethodGet, nil, map[string]string{urlutil.QueryRedirectURI: "https://some.domain.example/", urlutil.QuerySessionEncrypted: goodEncryptionString}, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusFound, ""},
{"good nginx callback set session okay but return unauthorized", opts, nil, http.MethodGet, nil, map[string]string{urlutil.QueryRedirectURI: "https://some.domain.example/", urlutil.QuerySessionEncrypted: goodEncryptionString}, "https://some.domain.example/verify", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusUnauthorized, ""},
{"bad nginx callback failed to set session", opts, nil, http.MethodGet, nil, map[string]string{urlutil.QueryRedirectURI: "https://some.domain.example/", urlutil.QuerySessionEncrypted: goodEncryptionString + "nope"}, "https://some.domain.example/verify", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, client.MockAuthorize{AuthorizeResponse: &pb.IsAuthorizedReply{Allow: true}}, http.StatusBadRequest, ""},
{"good nginx callback redirect", opts, nil, http.MethodGet, nil, map[string]string{urlutil.QueryRedirectURI: "https://some.domain.example/", urlutil.QuerySessionEncrypted: goodEncryptionString}, "https://some.domain.example/", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusFound, ""},
{"good nginx callback set session okay but return unauthorized", opts, nil, http.MethodGet, nil, map[string]string{urlutil.QueryRedirectURI: "https://some.domain.example/", urlutil.QuerySessionEncrypted: goodEncryptionString}, "https://some.domain.example/verify", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusUnauthorized, ""},
{"bad nginx callback failed to set session", opts, nil, http.MethodGet, nil, map[string]string{urlutil.QueryRedirectURI: "https://some.domain.example/", urlutil.QuerySessionEncrypted: goodEncryptionString + "nope"}, "https://some.domain.example/verify", "https://some.domain.example", &mock.Encoder{}, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Minute))}}, allowClient, http.StatusBadRequest, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@ -72,8 +84,8 @@ func TestProxy_ForwardAuth(t *testing.T) {
if err != nil {
t.Fatal(err)
}
p.authzClient = tt.authorizer
p.sessionStore = tt.sessionStore
p.AuthorizeClient = tt.authorizer
signer, err := jws.NewHS256Signer(nil, "mock")
if err != nil {
t.Fatal(err)
@ -110,7 +122,7 @@ func TestProxy_ForwardAuth(t *testing.T) {
router := p.registerFwdAuthHandlers()
router.ServeHTTP(w, r)
if status := w.Code; status != tt.wantStatus {
t.Errorf("status code: got %v want %v", status, tt.wantStatus)
t.Errorf("status code: got %v want %v in %s", status, tt.wantStatus, tt.name)
t.Errorf("\n%+v", w.Body.String())
}

View file

@ -36,7 +36,6 @@ func (p *Proxy) registerDashboardHandlers(r *mux.Router) *mux.Router {
h.Path("/sign_out").HandlerFunc(p.SignOut).Methods(http.MethodGet, http.MethodPost)
// admin endpoints authorization is also delegated to authorizer service
admin := h.PathPrefix("/admin").Subrouter()
admin.Use(p.AuthorizeSession)
admin.Path("/impersonate").Handler(httputil.HandlerFunc(p.Impersonate)).Methods(http.MethodPost)
// Authenticate service callback handlers and middleware

View file

@ -93,7 +93,6 @@ func TestProxy_UserDashboard(t *testing.T) {
}
p.encoder = tt.cipher
p.sessionStore = tt.session
p.AuthorizeClient = tt.authorizer
r := httptest.NewRequest(tt.method, "/", nil)
state, _ := tt.session.LoadSession(r)
@ -147,7 +146,6 @@ func TestProxy_Impersonate(t *testing.T) {
}
p.encoder = tt.cipher
p.sessionStore = tt.sessionStore
p.AuthorizeClient = tt.authorizer
postForm := url.Values{}
postForm.Add("email", tt.email)
postForm.Add("group", tt.groups)
@ -257,7 +255,6 @@ func TestProxy_Callback(t *testing.T) {
}
p.encoder = tt.cipher
p.sessionStore = tt.sessionStore
p.AuthorizeClient = tt.authorizer
p.UpdateOptions(tt.options)
redirectURI := &url.URL{Scheme: tt.scheme, Host: tt.host, Path: tt.path}
queryString := redirectURI.Query()
@ -398,7 +395,6 @@ func TestProxy_ProgrammaticCallback(t *testing.T) {
}
p.encoder = tt.cipher
p.sessionStore = tt.sessionStore
p.AuthorizeClient = tt.authorizer
p.UpdateOptions(tt.options)
redirectURI, _ := url.Parse(tt.redirectURI)
queryString := redirectURI.Query()

View file

@ -1,18 +1,16 @@
package proxy
import (
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
envoy_service_auth_v2 "github.com/envoyproxy/go-control-plane/envoy/service/auth/v2"
"github.com/golang/protobuf/ptypes"
"github.com/gorilla/mux"
"github.com/rs/zerolog"
"github.com/pomerium/pomerium/internal/grpc/authorize"
"github.com/pomerium/pomerium/internal/httputil"
"github.com/pomerium/pomerium/internal/log"
"github.com/pomerium/pomerium/internal/sessions"
@ -36,47 +34,6 @@ func (p *Proxy) AuthenticateSession(next http.Handler) http.Handler {
})
}
func (p *Proxy) refresh(ctx context.Context, oldSession string) (string, error) {
ctx, span := trace.StartSpan(ctx, "proxy.AuthenticateSession/refresh")
defer span.End()
s := &sessions.State{}
if err := p.encoder.Unmarshal([]byte(oldSession), s); err != nil {
return "", httputil.NewError(http.StatusBadRequest, err)
}
// 1 - build a signed url to call refresh on authenticate service
refreshURI := *p.authenticateRefreshURL
q := refreshURI.Query()
q.Set(urlutil.QueryAccessTokenID, s.AccessTokenID) // hash value points to parent token
q.Set(urlutil.QueryAudience, strings.Join(s.Audience, ",")) // request's audience, this route
refreshURI.RawQuery = q.Encode()
signedRefreshURL := urlutil.NewSignedURL(p.SharedKey, &refreshURI).String()
// 2 - http call to authenticate service
req, err := http.NewRequestWithContext(ctx, http.MethodGet, signedRefreshURL, nil)
if err != nil {
return "", fmt.Errorf("proxy: refresh request: %v", err)
}
req.Header.Set("X-Requested-With", "XmlHttpRequest")
req.Header.Set("Accept", "application/json")
res, err := httputil.DefaultClient.Do(req)
if err != nil {
return "", fmt.Errorf("proxy: client err %s: %w", signedRefreshURL, err)
}
defer res.Body.Close()
newJwt, err := ioutil.ReadAll(io.LimitReader(res.Body, 4<<10))
if err != nil {
return "", err
}
// auth couldn't refersh the session, delete the session and reload via 302
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("proxy: backend refresh failed: %s", newJwt)
}
return string(newJwt), nil
}
func (p *Proxy) redirectToSignin(w http.ResponseWriter, r *http.Request) error {
signinURL := *p.authenticateSigninURL
q := signinURL.Query()
@ -88,61 +45,46 @@ func (p *Proxy) redirectToSignin(w http.ResponseWriter, r *http.Request) error {
return nil
}
// AuthorizeSession is middleware to enforce a user is authorized for a request.
// Session state is retrieved from the users's request context.
func (p *Proxy) AuthorizeSession(next http.Handler) http.Handler {
return httputil.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
ctx, span := trace.StartSpan(r.Context(), "proxy.AuthorizeSession")
defer span.End()
authz, err := p.authorize(w, r)
if err != nil {
return err
}
r.Header.Set(httputil.HeaderPomeriumJWTAssertion, authz.GetSignedJwt())
next.ServeHTTP(w, r.WithContext(ctx))
return nil
})
}
func (p *Proxy) authorize(w http.ResponseWriter, r *http.Request) (*authorize.IsAuthorizedReply, error) {
ctx, span := trace.StartSpan(r.Context(), "proxy.authorize")
defer span.End()
jwt, _ := sessions.FromContext(ctx)
authz, err := p.AuthorizeClient.Authorize(ctx, jwt, r)
func (p *Proxy) isAuthorized(r *http.Request) (bool, error) {
tm, err := ptypes.TimestampProto(time.Now())
if err != nil {
return nil, httputil.NewError(http.StatusInternalServerError, err)
return false, httputil.NewError(http.StatusInternalServerError, fmt.Errorf("error creating protobuf timestamp from current time: %w", err))
}
if authz.GetSessionExpired() {
newJwt, err := p.refresh(ctx, jwt)
if err != nil {
p.sessionStore.ClearSession(w, r)
log.FromRequest(r).Warn().Err(err).Msg("proxy: refresh failed")
return nil, p.redirectToSignin(w, r)
}
if err = p.sessionStore.SaveSession(w, r, newJwt); err != nil {
return nil, httputil.NewError(http.StatusUnauthorized, err)
}
authz, err = p.AuthorizeClient.Authorize(ctx, newJwt, r)
if err != nil {
return nil, httputil.NewError(http.StatusUnauthorized, err)
httpAttrs := &envoy_service_auth_v2.AttributeContext_HttpRequest{
Method: "GET",
Headers: map[string]string{},
Path: r.URL.Path,
Host: r.URL.Host,
Scheme: r.URL.Scheme,
Fragment: r.URL.Fragment,
}
for k := range r.Header {
httpAttrs.Headers[k] = r.Header.Get(k)
if r.URL.RawQuery != "" {
// envoy expects the query string in the path
httpAttrs.Path += "?" + r.URL.RawQuery
}
}
if !authz.GetAllow() {
log.FromRequest(r).Warn().
Strs("reason", authz.GetDenyReasons()).
Bool("allow", authz.GetAllow()).
Bool("expired", authz.GetSessionExpired()).
Msg("proxy/authorize: deny")
return nil, httputil.NewError(http.StatusForbidden, errors.New("request denied"))
res, err := p.authzClient.Check(r.Context(), &envoy_service_auth_v2.CheckRequest{
Attributes: &envoy_service_auth_v2.AttributeContext{
Request: &envoy_service_auth_v2.AttributeContext_Request{
Time: tm,
Http: httpAttrs,
},
},
})
if err != nil {
return false, httputil.NewError(http.StatusInternalServerError, err)
}
return authz, nil
switch res.HttpResponse.(type) {
case *envoy_service_auth_v2.CheckResponse_OkResponse:
return true, nil
default:
return false, nil
}
}
// SetResponseHeaders sets a map of response headers.

View file

@ -13,8 +13,6 @@ import (
"github.com/pomerium/pomerium/internal/encoding"
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/internal/encoding/mock"
"github.com/pomerium/pomerium/internal/grpc/authorize"
"github.com/pomerium/pomerium/internal/grpc/authorize/client"
"github.com/pomerium/pomerium/internal/identity"
"github.com/pomerium/pomerium/internal/sessions"
mstore "github.com/pomerium/pomerium/internal/sessions/mock"
@ -146,65 +144,6 @@ func Test_jwtClaimMiddleware(t *testing.T) {
}
func TestProxy_AuthorizeSession(t *testing.T) {
t.Parallel()
fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, http.StatusText(http.StatusOK))
w.WriteHeader(http.StatusOK)
})
tests := []struct {
name string
refreshRespStatus int
session sessions.SessionStore
authzClient client.Authorizer
ctxError error
provider identity.Authenticator
wantStatus int
}{
{"user is authorized", 200, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Second))}}, client.MockAuthorize{AuthorizeResponse: &authorize.IsAuthorizedReply{Allow: true}}, nil, identity.MockProvider{}, http.StatusOK},
{"user is not authorized", 200, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Second))}}, client.MockAuthorize{AuthorizeResponse: &authorize.IsAuthorizedReply{Allow: false}}, nil, identity.MockProvider{}, http.StatusForbidden},
{"ctx error", 200, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Second))}}, client.MockAuthorize{AuthorizeResponse: &authorize.IsAuthorizedReply{Allow: true}}, errors.New("hi"), identity.MockProvider{}, http.StatusOK},
{"authz client error", 200, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Second))}}, client.MockAuthorize{AuthorizeError: errors.New("err")}, nil, identity.MockProvider{}, http.StatusInternalServerError},
{"expired, reauth failed", 200, &mstore.Store{Session: &sessions.State{Email: "user@test.example", Expiry: jwt.NewNumericDate(time.Now().Add(10 * time.Second))}}, client.MockAuthorize{AuthorizeResponse: &authorize.IsAuthorizedReply{SessionExpired: true}}, nil, identity.MockProvider{}, http.StatusForbidden},
//todo(bdd): it's a bit tricky to test the refresh flow
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.refreshRespStatus)
fmt.Fprintln(w, "REFRESH GOOD")
}))
defer ts.Close()
rURL := ts.URL
a := Proxy{
SharedKey: "80ldlrU2d7w+wVpKNfevk6fmb8otEx6CqOfshj2LwhQ=",
cookieSecret: []byte("80ldlrU2d7w+wVpKNfevk6fmb8otEx6CqOfshj2LwhQ="),
authenticateURL: uriParseHelper("https://authenticate.corp.example"),
authenticateSigninURL: uriParseHelper("https://authenticate.corp.example/sign_in"),
authenticateRefreshURL: uriParseHelper(rURL),
sessionStore: tt.session,
AuthorizeClient: tt.authzClient,
encoder: &mock.Encoder{},
}
r := httptest.NewRequest(http.MethodGet, "/", nil)
state, _ := tt.session.LoadSession(r)
ctx := r.Context()
ctx = sessions.NewContext(ctx, state, tt.ctxError)
r = r.WithContext(ctx)
r.Header.Set("Accept", "application/json")
w := httptest.NewRecorder()
got := a.AuthorizeSession(fn)
got.ServeHTTP(w, r)
if status := w.Code; status != tt.wantStatus {
t.Errorf("AuthorizeSession() error = %v, wantErr %v\n%v", w.Result().StatusCode, tt.wantStatus, w.Body.String())
}
})
}
}
func TestProxy_SetResponseHeaders(t *testing.T) {
t.Parallel()
fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

View file

@ -6,18 +6,15 @@ package proxy
import (
"crypto/cipher"
"crypto/tls"
"encoding/base64"
"fmt"
"html/template"
stdlog "log"
"net/http"
stdhttputil "net/http/httputil"
"net/url"
"regexp"
"strings"
"sync/atomic"
"time"
envoy_service_auth_v2 "github.com/envoyproxy/go-control-plane/envoy/service/auth/v2"
"github.com/gorilla/mux"
"github.com/pomerium/pomerium/config"
@ -26,16 +23,13 @@ import (
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/internal/frontend"
"github.com/pomerium/pomerium/internal/grpc"
"github.com/pomerium/pomerium/internal/grpc/authorize/client"
"github.com/pomerium/pomerium/internal/httputil"
"github.com/pomerium/pomerium/internal/log"
"github.com/pomerium/pomerium/internal/middleware"
"github.com/pomerium/pomerium/internal/sessions"
"github.com/pomerium/pomerium/internal/sessions/cookie"
"github.com/pomerium/pomerium/internal/sessions/header"
"github.com/pomerium/pomerium/internal/sessions/queryparam"
"github.com/pomerium/pomerium/internal/telemetry/metrics"
"github.com/pomerium/pomerium/internal/tripper"
"github.com/pomerium/pomerium/internal/urlutil"
)
@ -74,25 +68,23 @@ type Proxy struct {
SharedKey string
sharedCipher cipher.AEAD
authorizeURL *url.URL
authenticateURL *url.URL
authenticateSigninURL *url.URL
authenticateSignoutURL *url.URL
authenticateRefreshURL *url.URL
authorizeURL *url.URL
encoder encoding.Unmarshaler
cookieOptions *cookie.Options
cookieSecret []byte
refreshCooldown time.Duration
sessionStore sessions.SessionStore
sessionLoaders []sessions.SessionLoader
templates *template.Template
jwtClaimHeaders []string
authzClient envoy_service_auth_v2.AuthorizationClient
AuthorizeClient client.Authorizer
encoder encoding.Unmarshaler
cookieOptions *cookie.Options
cookieSecret []byte
defaultUpstreamTimeout time.Duration
refreshCooldown time.Duration
Handler http.Handler
sessionStore sessions.SessionStore
sessionLoaders []sessions.SessionLoader
templates *template.Template
jwtClaimHeaders []string
currentRouter atomic.Value
}
// New takes a Proxy service from options and a validation function.
@ -129,11 +121,10 @@ func New(opts config.Options) (*Proxy, error) {
sharedCipher: sharedCipher,
encoder: encoder,
cookieSecret: decodedCookieSecret,
cookieOptions: cookieOptions,
defaultUpstreamTimeout: opts.DefaultUpstreamTimeout,
refreshCooldown: opts.RefreshCooldown,
sessionStore: cookieStore,
cookieSecret: decodedCookieSecret,
cookieOptions: cookieOptions,
refreshCooldown: opts.RefreshCooldown,
sessionStore: cookieStore,
sessionLoaders: []sessions.SessionLoader{
cookieStore,
header.NewStore(encoder, "Pomerium"),
@ -141,6 +132,7 @@ func New(opts config.Options) (*Proxy, error) {
templates: template.Must(frontend.NewTemplates()),
jwtClaimHeaders: opts.JWTClaimsHeaders,
}
p.currentRouter.Store(httputil.NewRouter())
// errors checked in ValidateOptions
p.authorizeURL, _ = urlutil.DeepCopy(opts.AuthorizeURL)
p.authenticateURL, _ = urlutil.DeepCopy(opts.AuthenticateURL)
@ -148,13 +140,6 @@ func New(opts config.Options) (*Proxy, error) {
p.authenticateSignoutURL = p.authenticateURL.ResolveReference(&url.URL{Path: signoutURL})
p.authenticateRefreshURL = p.authenticateURL.ResolveReference(&url.URL{Path: refreshURL})
if err := p.UpdatePolicies(&opts); err != nil {
return nil, err
}
metrics.AddPolicyCountCallback("proxy", func() int64 {
return int64(len(opts.Policies))
})
authzConn, err := grpc.NewGRPCClientConn(&grpc.Options{
Addr: p.authorizeURL,
OverrideCertificateName: opts.OverrideCertificateName,
@ -167,9 +152,16 @@ func New(opts config.Options) (*Proxy, error) {
if err != nil {
return nil, err
}
p.authzClient = envoy_service_auth_v2.NewAuthorizationClient(authzConn)
p.AuthorizeClient, err = client.New(authzConn)
return p, err
if err := p.UpdatePolicies(&opts); err != nil {
return nil, err
}
metrics.AddPolicyCountCallback("proxy", func() int64 {
return int64(len(opts.Policies))
})
return p, nil
}
// UpdateOptions implements the OptionsUpdater interface and updates internal
@ -207,160 +199,13 @@ func (p *Proxy) UpdatePolicies(opts *config.Options) error {
if err := policy.Validate(); err != nil {
return fmt.Errorf("proxy: invalid policy %w", err)
}
r = p.reverseProxyHandler(r, policy)
}
p.Handler = r
p.currentRouter.Store(r)
return nil
}
func (p *Proxy) reverseProxyHandler(r *mux.Router, policy config.Policy) *mux.Router {
// 1. Create the reverse proxy connection
proxy := stdhttputil.NewSingleHostReverseProxy(policy.Destination)
// 2. Create a sublogger to handle any error logs
sublogger := log.With().Str("route", policy.String()).Logger()
proxy.ErrorLog = stdlog.New(&log.StdLogWrapper{Logger: &sublogger}, "", 0)
// 3. Rewrite host headers and add X-Forwarded-Host header
director := proxy.Director
proxy.Director = func(req *http.Request) {
req.Header.Add(httputil.HeaderForwardedHost, req.Host)
director(req)
if !policy.PreserveHostHeader {
req.Host = policy.Destination.Host
}
}
// 4. Override any custom transport settings (e.g. TLS settings, etc)
proxy.Transport = p.roundTripperFromPolicy(&policy)
// 5. Create a sub-router with a matcher derived from the policy (host, path, etc...)
rp := r.MatcherFunc(routeMatcherFuncFromPolicy(policy)).Subrouter()
rp.PathPrefix("/").Handler(proxy)
// Optional: If websockets are enabled, do not set a handler request timeout
// websockets cannot use the non-hijackable timeout-handler
if !policy.AllowWebsockets {
timeout := p.defaultUpstreamTimeout
if policy.UpstreamTimeout != 0 {
timeout = policy.UpstreamTimeout
}
timeoutMsg := fmt.Sprintf("%s timed out in %s", policy.Destination.Host, timeout)
rp.Use(middleware.TimeoutHandlerFunc(timeout, timeoutMsg))
}
// Optional: a cors preflight check, skip access control middleware
if policy.CORSAllowPreflight {
log.Warn().Str("route", policy.String()).Msg("proxy: cors preflight enabled")
rp.Use(middleware.CorsBypass(proxy))
}
// Optional: if additional headers are to be set for this url
if len(policy.SetRequestHeaders) != 0 {
log.Warn().Interface("headers", policy.SetRequestHeaders).Msg("proxy: set request headers")
rp.Use(SetResponseHeaders(policy.SetRequestHeaders))
}
// Optional: if a public route, skip access control middleware
if policy.AllowPublicUnauthenticatedAccess {
log.Warn().Str("route", policy.String()).Msg("proxy: all access control disabled")
return r
}
// 4. Retrieve the user session and add it to the request context
rp.Use(sessions.RetrieveSession(p.sessionLoaders...))
// 5. AuthN - Verify user session has been added to the request context
rp.Use(p.AuthenticateSession)
// 6. AuthZ - Verify the user is authorized for route
rp.Use(p.AuthorizeSession)
// 7. Strip the user session cookie from the downstream request
rp.Use(middleware.StripCookie(p.cookieOptions.Name))
// 8 . Add claim details to the request logger context and headers
rp.Use(p.jwtClaimMiddleware(false))
return r
}
// roundTripperFromPolicy adjusts the std library's `DefaultTransport RoundTripper`
// for a given route. A route's `RoundTripper` establishes network connections
// as needed and caches them for reuse by subsequent calls.
func (p *Proxy) roundTripperFromPolicy(policy *config.Policy) http.RoundTripper {
transport := http.DefaultTransport.(*http.Transport).Clone()
c := tripper.NewChain()
c = c.Append(metrics.HTTPMetricsRoundTripper("proxy", policy.Destination.Host))
var tlsClientConfig tls.Config
var isCustomClientConfig bool
if policy.TLSSkipVerify {
tlsClientConfig.InsecureSkipVerify = true
isCustomClientConfig = true
log.Warn().Str("policy", policy.String()).Msg("proxy: tls skip verify")
}
if policy.RootCAs != nil {
tlsClientConfig.RootCAs = policy.RootCAs
isCustomClientConfig = true
log.Debug().Str("policy", policy.String()).Msg("proxy: custom root ca")
}
if policy.ClientCertificate != nil {
tlsClientConfig.Certificates = []tls.Certificate{*policy.ClientCertificate}
isCustomClientConfig = true
log.Debug().Str("policy", policy.String()).Msg("proxy: client certs enabled")
}
if policy.TLSServerName != "" {
tlsClientConfig.ServerName = policy.TLSServerName
isCustomClientConfig = true
log.Debug().Str("policy", policy.String()).Msgf("proxy: tls override hostname: %s", policy.TLSServerName)
}
// We avoid setting a custom client config unless we have to as
// if TLSClientConfig is nil, the default configuration is used.
if isCustomClientConfig {
transport.TLSClientConfig = &tlsClientConfig
}
return c.Then(transport)
}
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p.Handler.ServeHTTP(w, r)
}
// routeMatcherFuncFromPolicy returns a mux matcher function which compares an http request with a policy.
//
// Routes can be filtered by the `source`, `prefix`, `path` and `regex` fields in the policy config.
func routeMatcherFuncFromPolicy(policy config.Policy) mux.MatcherFunc {
// match by source
sourceMatches := func(r *http.Request) bool {
return r.Host == policy.Source.Host
}
// match by prefix
prefixMatches := func(r *http.Request) bool {
return policy.Prefix == "" ||
strings.HasPrefix(r.URL.Path, policy.Prefix)
}
// match by path
pathMatches := func(r *http.Request) bool {
return policy.Path == "" ||
r.URL.Path == policy.Path
}
// match by path regex
var regexMatches func(*http.Request) bool
if policy.Regex == "" {
regexMatches = func(r *http.Request) bool { return true }
} else if re, err := regexp.Compile(policy.Regex); err == nil {
regexMatches = func(r *http.Request) bool {
return re.MatchString(r.URL.Path)
}
} else {
log.Error().Err(err).Str("regex", policy.Regex).Msg("proxy: invalid regex in policy, ignoring route")
regexMatches = func(r *http.Request) bool { return false }
}
return func(r *http.Request, rm *mux.RouteMatch) bool {
return sourceMatches(r) && prefixMatches(r) && pathMatches(r) && regexMatches(r)
}
p.currentRouter.Load().(*mux.Router).ServeHTTP(w, r)
}

View file

@ -1,16 +1,12 @@
package proxy
import (
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/pomerium/pomerium/config"
)
@ -233,182 +229,3 @@ func Test_UpdateOptions(t *testing.T) {
var p *Proxy
p.UpdateOptions(config.Options{})
}
func TestNewReverseProxy(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
hostname, _, _ := net.SplitHostPort(r.Host)
w.Write([]byte(hostname))
}))
defer backend.Close()
backendURL, _ := url.Parse(backend.URL)
backendHostname, backendPort, _ := net.SplitHostPort(backendURL.Host)
backendHost := net.JoinHostPort(backendHostname, backendPort)
proxyURL, _ := url.Parse(backendURL.Scheme + "://" + backendHost + "/")
ts := httptest.NewUnstartedServer(nil)
ts.Start()
defer ts.Close()
p, err := New(testOptions(t))
if err != nil {
t.Fatal(err)
}
newPolicy := config.Policy{To: proxyURL.String(), From: ts.URL, AllowPublicUnauthenticatedAccess: true}
err = newPolicy.Validate()
if err != nil {
t.Fatal(err)
}
proxyHandler := p.reverseProxyHandler(mux.NewRouter(), newPolicy)
ts.Config.Handler = proxyHandler
getReq, _ := http.NewRequest("GET", newPolicy.From, nil)
res, err := http.DefaultClient.Do(getReq)
if err != nil {
t.Fatal(err)
}
if res.StatusCode != 200 {
t.Errorf("Failed to find route handler")
}
bodyBytes, _ := ioutil.ReadAll(res.Body)
if g, e := string(bodyBytes), backendHostname; g != e {
t.Errorf("got body %q; expected %q", g, e)
}
}
func TestRouteMatcherFuncFromPolicy(t *testing.T) {
tests := []struct {
source, prefix, path, regex string
incomingURL string
expect bool
msg string
}{
// host in source
{"https://www.example.com", "", "", "",
"https://www.example.com", true,
"should match when host is the same as source host"},
{"https://www.example.com/", "", "", "",
"https://www.example.com", true,
"should match when host is the same as source host with trailing slash"},
{"https://www.example.com", "", "", "",
"https://www.google.com", false,
"should not match when host is different from source host"},
// path prefix
{"https://www.example.com", "/admin", "", "",
"https://www.example.com/admin/someaction", true,
"should match when path begins with prefix"},
{"https://www.example.com", "/admin", "", "",
"https://www.example.com/notadmin", false,
"should not match when path does not begin with prefix"},
// path
{"https://www.example.com", "", "/admin", "",
"https://www.example.com/admin", true,
"should match when path is the same as the policy path"},
{"https://www.example.com", "", "/admin", "",
"https://www.example.com/admin/someaction", false,
"should not match when path merely begins with the policy path"},
{"https://www.example.com", "", "/admin", "",
"https://www.example.com/notadmin", false,
"should not match when path is different from the policy path"},
// path regex
{"https://www.example.com", "", "", "^/admin/[a-z]+$",
"https://www.example.com/admin/someaction", true,
"should match when path matches policy path regex"},
{"https://www.example.com", "", "", "^/admin/[a-z]+$",
"https://www.example.com/notadmin", false,
"should not match when path does not match policy path regex"},
{"https://www.example.com", "", "", "invalid[",
"https://www.example.com/invalid", false,
"should not match on invalid policy path regex"},
}
for _, tt := range tests {
srcURL, err := url.Parse(tt.source)
if err != nil {
panic(err)
}
src := &config.StringURL{URL: srcURL}
matcher := routeMatcherFuncFromPolicy(config.Policy{
Source: src,
Prefix: tt.prefix,
Path: tt.path,
Regex: tt.regex,
})
req, err := http.NewRequest("GET", tt.incomingURL, nil)
if err != nil {
panic(err)
}
actual := matcher(req, nil)
if actual != tt.expect {
t.Errorf("%s (source=%s prefix=%s path=%s regex=%s incoming-url=%s)",
tt.msg, tt.source, tt.prefix, tt.path, tt.regex, tt.incomingURL)
}
}
}
func TestPolicyPrefixRouting(t *testing.T) {
adminServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "admin: "+r.URL.Path)
}))
defer adminServer.Close()
publicServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "public: "+r.URL.Path)
}))
defer publicServer.Close()
opts := testOptions(t)
opts.Policies = []config.Policy{
{
From: "https://from.example.com",
To: "http://" + adminServer.Listener.Addr().String(),
Prefix: "/admin",
AllowPublicUnauthenticatedAccess: true,
},
{
From: "https://from.example.com",
To: "http://" + publicServer.Listener.Addr().String(),
AllowPublicUnauthenticatedAccess: true,
},
}
p, err := New(opts)
if err != nil {
t.Fatalf("error creating proxy: %v", err)
}
t.Run("admin", func(t *testing.T) {
req, err := http.NewRequest("GET", "https://from.example.com/admin/path", nil)
if err != nil {
t.Fatalf("error creating http request: %v", err)
}
rr := httptest.NewRecorder()
p.ServeHTTP(rr, req)
rr.Flush()
if rr.Body.String() != "admin: /admin/path" {
t.Errorf("expected admin request to go to the admin backend")
}
})
t.Run("non-admin", func(t *testing.T) {
req, err := http.NewRequest("GET", "https://from.example.com/nonadmin/path", nil)
if err != nil {
t.Fatalf("error creating http request: %v", err)
}
rr := httptest.NewRecorder()
p.ServeHTTP(rr, req)
rr.Flush()
if rr.Body.String() != "public: /nonadmin/path" {
t.Errorf("expected non-admin request to go to the public backend")
}
})
}