git.iko.soy/typeable/oauth2-proxy
on master help sign in
Merge pull request #2589 from ianroberts/file-upstream-rewrite
e293dddJoel Speed
CHANGELOG.md+1
@@ -15,6 +15,7 @@
15- [#2459](https://github.com/oauth2-proxy/oauth2-proxy/pull/2459) chore(deps): Updated to ginkgo v2 (@kvanzuijlen, @tuunit)
15- [#2459](https://github.com/oauth2-proxy/oauth2-proxy/pull/2459) chore(deps): Updated to ginkgo v2 (@kvanzuijlen, @tuunit)
16- [#2112](https://github.com/oauth2-proxy/oauth2-proxy/pull/2112) docs: update list of providers which support refresh tokens (@mikefab-msf)
16- [#2112](https://github.com/oauth2-proxy/oauth2-proxy/pull/2112) docs: update list of providers which support refresh tokens (@mikefab-msf)
17- [#2734](https://github.com/oauth2-proxy/oauth2-proxy/pull/2734) Added s390x architecture option support (@priby05)
17- [#2734](https://github.com/oauth2-proxy/oauth2-proxy/pull/2734) Added s390x architecture option support (@priby05)
18+- [#2589](https://github.com/oauth2-proxy/oauth2-proxy/pull/2589) Added support for regex path matching and rewriting when using a static `file:` upstream (@ianroberts)
18
19
19# V7.6.0
20# V7.6.0
20
21
docs/docs/configuration/alpha_config.md+1−1
@@ -524,7 +524,7 @@ Requests will be proxied to this upstream if the path matches the request path.
524| ----- | ---- | ----------- |
524| ----- | ---- | ----------- |
525| `id` | _string_ | ID should be a unique identifier for the upstream.<br/>This value is required for all upstreams. |
525| `id` | _string_ | ID should be a unique identifier for the upstream.<br/>This value is required for all upstreams. |
526| `path` | _string_ | Path is used to map requests to the upstream server.<br/>The closest match will take precedence and all Paths must be unique.<br/>Path can also take a pattern when used with RewriteTarget.<br/>Path segments can be captured and matched using regular experessions.<br/>Eg:<br/>- `^/foo$`: Match only the explicit path `/foo`<br/>- `^/bar/$`: Match any path prefixed with `/bar/`<br/>- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget |
526| `path` | _string_ | Path is used to map requests to the upstream server.<br/>The closest match will take precedence and all Paths must be unique.<br/>Path can also take a pattern when used with RewriteTarget.<br/>Path segments can be captured and matched using regular experessions.<br/>Eg:<br/>- `^/foo$`: Match only the explicit path `/foo`<br/>- `^/bar/$`: Match any path prefixed with `/bar/`<br/>- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget |
527−| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to<br/>the upstream server.<br/>Use the Path to capture segments for reuse within the rewrite target.<br/>Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite<br/>the request `/baz/abc/123` to `/foo/abc/123` before proxying to the<br/>upstream server. |
527+| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to<br/>the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem<br/>(for a `file:` upstream).<br/>Use the Path to capture segments for reuse within the rewrite target.<br/>Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite<br/>the request `/baz/abc/123` to `/foo/abc/123` before proxying to the<br/>upstream server. Or if the upstream were `file:///app`, a request for<br/>`/baz/info.html` would return the contents of the file `/app/foo/info.html`. |
528| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File<br/>based URL. It may include a path, in which case all requests will be served<br/>under that path.<br/>Eg:<br/>- http://localhost:8080<br/>- https://service.localhost<br/>- https://service.localhost/path<br/>- file://host/path<br/>If the URI's path is "/base" and the incoming request was for "/dir",<br/>the upstream request will be for "/base/dir". |
528| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File<br/>based URL. It may include a path, in which case all requests will be served<br/>under that path.<br/>Eg:<br/>- http://localhost:8080<br/>- https://service.localhost<br/>- https://service.localhost/path<br/>- file://host/path<br/>If the URI's path is "/base" and the incoming request was for "/dir",<br/>the upstream request will be for "/base/dir". |
529| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.<br/>This option is insecure and will allow potential Man-In-The-Middle attacks<br/>between OAuth2 Proxy and the upstream server.<br/>Defaults to false. |
529| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.<br/>This option is insecure and will allow potential Man-In-The-Middle attacks<br/>between OAuth2 Proxy and the upstream server.<br/>Defaults to false. |
530| `static` | _bool_ | Static will make all requests to this upstream have a static response.<br/>The response will have a body of "Authenticated" and a response code<br/>matching StaticCode.<br/>If StaticCode is not set, the response will return a 200 response. |
530| `static` | _bool_ | Static will make all requests to this upstream have a static response.<br/>The response will have a body of "Authenticated" and a response code<br/>matching StaticCode.<br/>If StaticCode is not set, the response will return a 200 response. |
pkg/apis/options/upstreams.go+4−2
@@ -39,11 +39,13 @@ type Upstream struct {
39 Path string `json:"path,omitempty"`
39 Path string `json:"path,omitempty"`
40
40
41 // RewriteTarget allows users to rewrite the request path before it is sent to
41 // RewriteTarget allows users to rewrite the request path before it is sent to
42− // the upstream server.
42+ // the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
43+ // (for a `file:` upstream).
43 // Use the Path to capture segments for reuse within the rewrite target.
44 // Use the Path to capture segments for reuse within the rewrite target.
44 // Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
45 // Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
45 // the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
46 // the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
46− // upstream server.
47+ // upstream server. Or if the upstream were `file:///app`, a request for
48+ // `/baz/info.html` would return the contents of the file `/app/foo/info.html`.
47 RewriteTarget string `json:"rewriteTarget,omitempty"`
49 RewriteTarget string `json:"rewriteTarget,omitempty"`
48
50
49 // The URI of the upstream server. This may be an HTTP(S) server of a File
51 // The URI of the upstream server. This may be an HTTP(S) server of a File
pkg/upstream/file.go+39−5
@@ -2,9 +2,12 @@ package upstream
2
2
3import (
3import (
4 "net/http"
4 "net/http"
5+ "net/url"
5 "runtime"
6 "runtime"
6 "strings"
7 "strings"
7
8
9+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
10+
8 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
11 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
9)
12)
10
13
@@ -12,22 +15,53 @@ const fileScheme = "file"
12
15
13// newFileServer creates a new fileServer that can serve requests
16// newFileServer creates a new fileServer that can serve requests
14// to a file system location.
17// to a file system location.
15−func newFileServer(id, path, fileSystemPath string) http.Handler {
18+func newFileServer(upstream options.Upstream, fileSystemPath string) http.Handler {
19+ handler := newFileServerForPath(fileSystemPath)
20+
21+ if upstream.RewriteTarget == "" {
22+ // if the upstream does not have a rewrite target, strip off the Path prefix
23+ // (so e.g. a request for /static/some-file.html looks for some-file.html
24+ // relative to the fileSystemPath rather than static/some-file.html).
25+ handler = http.StripPrefix(upstream.Path, handler)
26+ } else {
27+ // if the upstream *does* have a rewrite target then that means the target
28+ // path relative to the fileSystemPath will be the one in the (rewritten)
29+ // RequestURI.
30+ handler = requestURIToURL(handler)
31+ }
16 return &fileServer{
32 return &fileServer{
17− upstream: id,
33+ upstream: upstream.ID,
18− handler: newFileServerForPath(path, fileSystemPath),
34+ handler: handler,
19 }
35 }
20}
36}
21
37
22// newFileServerForPath creates a http.Handler to serve files from the filesystem
38// newFileServerForPath creates a http.Handler to serve files from the filesystem
23−func newFileServerForPath(path string, filesystemPath string) http.Handler {
39+func newFileServerForPath(filesystemPath string) http.Handler {
24 // Windows fileSSystemPath will be be prefixed with `/`, eg`/C:/...,
40 // Windows fileSSystemPath will be be prefixed with `/`, eg`/C:/...,
25 // if they were parsed by url.Parse`
41 // if they were parsed by url.Parse`
26 if runtime.GOOS == "windows" {
42 if runtime.GOOS == "windows" {
27 filesystemPath = strings.TrimPrefix(filesystemPath, "/")
43 filesystemPath = strings.TrimPrefix(filesystemPath, "/")
28 }
44 }
29
45
30− return http.StripPrefix(path, http.FileServer(http.Dir(filesystemPath)))
46+ return http.FileServer(http.Dir(filesystemPath))
47+}
48+
49+// requestURIToURL returns a Handler that replaces the URL in its request with
50+// the result of parsing req.RequestURI. This is necessary for file handlers
51+// that have a rewrite target, since http.FileServer uses req.URL.Path when
52+// looking for the target file, but the rewrite handler only updates the
53+// RequestURI, leaving the original path in the URL.
54+func requestURIToURL(handler http.Handler) http.Handler {
55+ return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
56+ reqURL, err := url.ParseRequestURI(req.RequestURI)
57+ if err != nil {
58+ http.Error(rw, "500 Internal Server Error", http.StatusInternalServerError)
59+ return
60+ }
61+
62+ req.URL = reqURL
63+ handler.ServeHTTP(rw, req)
64+ })
31}
65}
32
66
33// fileServer represents a single filesystem upstream proxy
67// fileServer represents a single filesystem upstream proxy
pkg/upstream/file_test.go+7−1
@@ -7,6 +7,8 @@ import (
7 "net/http/httptest"
7 "net/http/httptest"
8 "os"
8 "os"
9
9
10+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
11+
10 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
12 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
11 . "github.com/onsi/ginkgo/v2"
13 . "github.com/onsi/ginkgo/v2"
12 . "github.com/onsi/gomega"
14 . "github.com/onsi/gomega"
@@ -31,8 +33,12 @@ var _ = Describe("File Server Suite", func() {
31 _, err := io.ReadFull(rand.Reader, idBytes)
33 _, err := io.ReadFull(rand.Reader, idBytes)
32 Expect(err).ToNot(HaveOccurred())
34 Expect(err).ToNot(HaveOccurred())
33 id = string(idBytes)
35 id = string(idBytes)
36+ upstream := options.Upstream{
37+ ID: id,
38+ Path: "/files",
39+ }
34
40
35− handler = newFileServer(id, "/files", filesDir)
41+ handler = newFileServer(upstream, filesDir)
36 })
42 })
37
43
38 AfterEach(func() {
44 AfterEach(func() {
pkg/upstream/proxy.go+1−1
@@ -81,7 +81,7 @@ func (m *multiUpstreamProxy) registerStaticResponseHandler(upstream options.Upst
81// registerFileServer registers a new fileServer based on the configuration given.
81// registerFileServer registers a new fileServer based on the configuration given.
82func (m *multiUpstreamProxy) registerFileServer(upstream options.Upstream, u *url.URL, writer pagewriter.Writer) error {
82func (m *multiUpstreamProxy) registerFileServer(upstream options.Upstream, u *url.URL, writer pagewriter.Writer) error {
83 logger.Printf("mapping path %q => file system %q", upstream.Path, u.Path)
83 logger.Printf("mapping path %q => file system %q", upstream.Path, u.Path)
84− return m.registerHandler(upstream, newFileServer(upstream.ID, upstream.Path, u.Path), writer)
84+ return m.registerHandler(upstream, newFileServer(upstream, u.Path), writer)
85}
85}
86
86
87// registerHTTPUpstreamProxy registers a new httpUpstreamProxy based on the configuration given.
87// registerHTTPUpstreamProxy registers a new httpUpstreamProxy based on the configuration given.
pkg/upstream/proxy_test.go+17
@@ -51,6 +51,12 @@ var _ = Describe("Proxy Suite", func() {
51 Path: "/files/",
51 Path: "/files/",
52 URI: fmt.Sprintf("file:///%s", filesDir),
52 URI: fmt.Sprintf("file:///%s", filesDir),
53 },
53 },
54+ {
55+ ID: "rewrite-file-backend",
56+ Path: "^/rewrite-files/.*/(.*)$",
57+ RewriteTarget: "/$1",
58+ URI: fmt.Sprintf("file:///%s", filesDir),
59+ },
54 {
60 {
55 ID: "static-backend",
61 ID: "static-backend",
56 Path: "/static/",
62 Path: "/static/",
@@ -174,6 +180,17 @@ var _ = Describe("Proxy Suite", func() {
174 },
180 },
175 upstream: "file-backend",
181 upstream: "file-backend",
176 }),
182 }),
183+ Entry("with a request to the File backend with rewrite", &proxyTableInput{
184+ target: "http://example.localhost/rewrite-files/anything-at-all/foo",
185+ response: testHTTPResponse{
186+ code: 200,
187+ header: map[string][]string{
188+ contentType: {textPlainUTF8},
189+ },
190+ raw: "foo",
191+ },
192+ upstream: "rewrite-file-backend",
193+ }),
177 Entry("with a request to the Static backend", &proxyTableInput{
194 Entry("with a request to the Static backend", &proxyTableInput{
178 target: "http://example.localhost/static/bar",
195 target: "http://example.localhost/static/bar",
179 response: testHTTPResponse{
196 response: testHTTPResponse{