-
Notifications
You must be signed in to change notification settings - Fork 7
Add vice-users OAuth callback relay to vice-operator #144
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
|
|
||
| "github.com/cyverse-de/go-mod/viceauth" | ||
| "github.com/labstack/echo/v4" | ||
| ) | ||
|
|
||
| // viceUsersCallbackPath is the fixed path of the OAuth callback relay. It is | ||
| // combined with --public-url to form OPERATOR_CALLBACK_URL, the static | ||
| // redirect_uri that must be registered in Keycloak. | ||
| const viceUsersCallbackPath = "/auth/callback" | ||
|
|
||
| // ViceUsersAuthConfig configures the vice-users OAuth callback relay. | ||
| type ViceUsersAuthConfig struct { | ||
| // StateCodec verifies the HMAC-signed OAuth state produced by vice-proxy. | ||
| StateCodec *viceauth.Codec | ||
|
|
||
| // BaseDomain is the VICE base domain (e.g. "cyverse.run"). The relay only | ||
| // redirects to single-label subdomains of this domain, so a forged or | ||
| // tampered state cannot turn the callback into an open redirect. | ||
| BaseDomain string | ||
| } | ||
|
|
||
| // isAllowedHost reports whether host is a single-label subdomain of the VICE | ||
| // base domain. host is expected to already have any port stripped (as | ||
| // url.URL.Hostname does). This is the open-redirect guard for the relay. | ||
| func (cfg *ViceUsersAuthConfig) isAllowedHost(host string) bool { | ||
| suffix := "." + cfg.BaseDomain | ||
| label, ok := strings.CutSuffix(host, suffix) | ||
| if !ok { | ||
| return false | ||
| } | ||
| return label != "" && !strings.Contains(label, ".") | ||
| } | ||
|
|
||
| // handleViceUsersCallback returns the OAuth callback relay handler. | ||
| // | ||
| // The operator's callback URL is registered in Keycloak as the static | ||
| // redirect_uri for the OAuth client vice-proxy authenticates against — | ||
| // Keycloak cannot wildcard-match per-app VICE subdomains, so a single fixed | ||
| // callback is needed. Keycloak delivers the authorization code here; the | ||
| // handler recovers the original app URL from the signed state and relays the | ||
| // browser back to it with the code intact. It is intentionally stateless and | ||
| // does no token exchange — vice-proxy holds the client secret and redeems the | ||
| // code itself. | ||
| func handleViceUsersCallback(cfg *ViceUsersAuthConfig) echo.HandlerFunc { | ||
| return func(c echo.Context) error { | ||
| q := c.Request().URL.Query() | ||
|
|
||
| // Surface Keycloak-side errors instead of relaying a useless redirect. | ||
| if errParam := q.Get("error"); errParam != "" { | ||
| return echo.NewHTTPError(http.StatusUnauthorized, | ||
| fmt.Sprintf("Keycloak error: %s — %s", errParam, q.Get("error_description"))) | ||
| } | ||
|
|
||
| code := q.Get("code") | ||
| state := q.Get("state") | ||
| if code == "" || state == "" { | ||
| return echo.NewHTTPError(http.StatusBadRequest, "missing code or state") | ||
| } | ||
|
|
||
| // A decode error means a forged or corrupted state — refuse to relay. | ||
| claims, err := cfg.StateCodec.Decode(state) | ||
| if err != nil { | ||
| return echo.NewHTTPError(http.StatusBadRequest, "invalid state") | ||
| } | ||
|
|
||
| // Reject anything that isn't a plain https URL on an allowed VICE | ||
| // subdomain. origin.User is refused outright — userinfo has no place in | ||
| // a relay target and is a classic redirect-spoofing vector. | ||
| origin, err := url.Parse(claims.Origin) | ||
| if err != nil || origin.Scheme != "https" || origin.User != nil || !cfg.isAllowedHost(origin.Hostname()) { | ||
| return echo.NewHTTPError(http.StatusBadRequest, "invalid redirect target") | ||
| } | ||
|
|
||
| // Re-attach code + state so vice-proxy can validate state against its | ||
| // cookie and exchange the code. Preserve any path/query already present; | ||
| // drop any fragment, which has no business in a server-side redirect. | ||
| oq := origin.Query() | ||
| oq.Set("code", code) | ||
| oq.Set("state", state) | ||
| origin.RawQuery = oq.Encode() | ||
| origin.Fragment = "" | ||
|
|
||
| return c.Redirect(http.StatusTemporaryRedirect, origin.String()) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "net/url" | ||
| "testing" | ||
|
|
||
| "github.com/cyverse-de/go-mod/viceauth" | ||
| "github.com/labstack/echo/v4" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestIsAllowedHost(t *testing.T) { | ||
| cfg := &ViceUsersAuthConfig{BaseDomain: "cyverse.run"} | ||
| tests := []struct { | ||
| host string | ||
| want bool | ||
| }{ | ||
| {"a1234abcd.cyverse.run", true}, | ||
| {"cyverse.run", false}, // base domain itself, no subdomain | ||
| {"a.b.cyverse.run", false}, // nested subdomain | ||
| {"a1234.cyverse.run.evil.com", false}, | ||
| {"xcyverse.run", false}, // suffix without the dot boundary | ||
| {"evil.com", false}, | ||
| {"", false}, | ||
| } | ||
| for _, tt := range tests { | ||
| t.Run(tt.host, func(t *testing.T) { | ||
| assert.Equal(t, tt.want, cfg.isAllowedHost(tt.host)) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| // runCallback invokes the callback handler against a synthetic request and | ||
| // returns the recorder. echo.HTTPError results are run through the default | ||
| // error handler so the recorder reflects the status the client would see. | ||
| func runCallback(t *testing.T, cfg *ViceUsersAuthConfig, rawQuery string) *httptest.ResponseRecorder { | ||
| t.Helper() | ||
| e := echo.New() | ||
| req := httptest.NewRequest(http.MethodGet, "/vice-users/callback?"+rawQuery, nil) | ||
| rec := httptest.NewRecorder() | ||
| c := e.NewContext(req, rec) | ||
| if err := handleViceUsersCallback(cfg)(c); err != nil { | ||
| e.HTTPErrorHandler(err, c) | ||
| } | ||
| return rec | ||
| } | ||
|
|
||
| func TestHandleViceUsersCallback(t *testing.T) { | ||
| codec := viceauth.NewCodec([]byte("test-secret")) | ||
| cfg := &ViceUsersAuthConfig{StateCodec: codec, BaseDomain: "cyverse.run"} | ||
|
|
||
| state := func(t *testing.T, c *viceauth.Codec, origin string) string { | ||
| t.Helper() | ||
| s, err := c.Encode(viceauth.StateClaims{StateID: "sid", Origin: origin}) | ||
| require.NoError(t, err) | ||
| return s | ||
| } | ||
|
|
||
| validState := state(t, codec, "https://a1234abcd.cyverse.run:4343/foo?x=1") | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| query url.Values | ||
| wantCode int | ||
| }{ | ||
| { | ||
| name: "valid bounce", | ||
| query: url.Values{"code": {"abc"}, "state": {validState}}, | ||
| wantCode: http.StatusTemporaryRedirect, | ||
| }, | ||
| { | ||
| name: "keycloak error param", | ||
| query: url.Values{"error": {"access_denied"}, "error_description": {"nope"}}, | ||
| wantCode: http.StatusUnauthorized, | ||
| }, | ||
| { | ||
| name: "missing code", | ||
| query: url.Values{"state": {validState}}, | ||
| wantCode: http.StatusBadRequest, | ||
| }, | ||
| { | ||
| name: "missing state", | ||
| query: url.Values{"code": {"abc"}}, | ||
| wantCode: http.StatusBadRequest, | ||
| }, | ||
| { | ||
| name: "bad signature", | ||
| query: url.Values{"code": {"abc"}, "state": {state(t, viceauth.NewCodec([]byte("other-secret")), "https://a1234abcd.cyverse.run/")}}, | ||
| wantCode: http.StatusBadRequest, | ||
| }, | ||
| { | ||
| name: "off-domain origin", | ||
| query: url.Values{"code": {"abc"}, "state": {state(t, codec, "https://evil.com/")}}, | ||
| wantCode: http.StatusBadRequest, | ||
| }, | ||
| { | ||
| name: "nested subdomain origin", | ||
| query: url.Values{"code": {"abc"}, "state": {state(t, codec, "https://a.b.cyverse.run/")}}, | ||
| wantCode: http.StatusBadRequest, | ||
| }, | ||
| { | ||
| name: "non-https origin", | ||
| query: url.Values{"code": {"abc"}, "state": {state(t, codec, "http://a1234abcd.cyverse.run/")}}, | ||
| wantCode: http.StatusBadRequest, | ||
| }, | ||
| { | ||
| name: "userinfo in origin", | ||
| query: url.Values{"code": {"abc"}, "state": {state(t, codec, "https://attacker@a1234abcd.cyverse.run/")}}, | ||
| wantCode: http.StatusBadRequest, | ||
| }, | ||
| } | ||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| rec := runCallback(t, cfg, tt.query.Encode()) | ||
| require.Equal(t, tt.wantCode, rec.Code) | ||
|
|
||
| if tt.wantCode != http.StatusTemporaryRedirect { | ||
| return | ||
| } | ||
| // On a successful bounce the browser is sent back to the app's | ||
| // own URL with code + state re-attached and the original query | ||
| // preserved. | ||
| loc, err := url.Parse(rec.Header().Get("Location")) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, "https", loc.Scheme) | ||
| assert.Equal(t, "a1234abcd.cyverse.run:4343", loc.Host) | ||
| assert.Equal(t, "/foo", loc.Path) | ||
| assert.Equal(t, "abc", loc.Query().Get("code")) | ||
| assert.Equal(t, validState, loc.Query().Get("state")) | ||
| assert.Equal(t, "1", loc.Query().Get("x")) | ||
| }) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I view this endpoint as essentially a relay that allows us to use a static callback URL in the Keycloak OIDC client for each VICE operator. This endpoint uses the state parameter to determine which vice-proxy to redirect the browser to and does some sanity checks on the request to ensure that the state parameter is signed with the appropriate key and that the browser is only redirected to authorized locations.
Rewording the comment may not be necessary, but I didn't develop a thorough understanding of how this works until I read the code. I'm not sure that the original comment helped me understand it (although I must admit that I'm not entirely sure that it didn't help me understand the endpoint either). 😆