Skip to content
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
21 changes: 18 additions & 3 deletions api/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -535,13 +535,12 @@
},
"/redirect": {
"get": {
"description": "Receives authorization code and state from the OAuth2 provider,\nthen redirects the browser back to the desktop client's local HTTP listener.",
"description": "Receives the authorization response from the OAuth2 provider,\nthen redirects the browser back to the desktop client's local HTTP listener.\nIf the user cancels or denies consent, the provider sends error (e.g. access_denied)\nand state instead of code; these are forwarded to the client so it can fail immediately.",
"parameters": [
{
"description": "Authorization code from OAuth2 provider",
"description": "Authorization code from OAuth2 provider (required unless error is present)",
"in": "query",
"name": "code",
"required": true,
"schema": {
"type": "string"
}
Expand All @@ -554,6 +553,22 @@
"schema": {
"type": "string"
}
},
{
"description": "OAuth2 error code from provider, e.g. access_denied when consent is cancelled",
"in": "query",
"name": "error",
"schema": {
"type": "string"
}
},
{
"description": "Human-readable error description from provider",
"in": "query",
"name": "error_description",
"schema": {
"type": "string"
}
}
],
"responses": {
Expand Down
60 changes: 60 additions & 0 deletions internal/app/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,66 @@ func TestMWLegacyHandler_Redirect(t *testing.T) {
r.Contains(w.Body.String(), "http://localhost:1234/cb")
}

func TestMWLegacyHandler_RedirectConsentCancelled(t *testing.T) {
r := require.New(t)
srv := newTestServer()

req := httptest.NewRequest(http.MethodGet,
"/oauth/v1/redirect?error=access_denied&error_description=User+cancelled&state=100-http://localhost:1234/cb", nil)
w := httptest.NewRecorder()
srv.MWLegacyHandler().ServeHTTP(w, req)

r.Equal(http.StatusOK, w.Code)
r.Contains(w.Header().Get("Content-Type"), "text/html")
body := w.Body.String()
r.Contains(body, "http://localhost:1234/cb?error=access_denied")
r.Contains(body, "error_description=User+cancelled")
r.Contains(body, "Sign-in was cancelled or did not complete.")
r.NotContains(body, "Authentication complete.")
}

func TestMWLegacyHandler_RedirectErrorWithoutState(t *testing.T) {
r := require.New(t)
srv := newTestServer()

req := httptest.NewRequest(http.MethodGet, "/oauth/v1/redirect?error=access_denied", nil)
w := httptest.NewRecorder()
srv.MWLegacyHandler().ServeHTTP(w, req)

r.Equal(http.StatusOK, w.Code)
var resp map[string]any
r.NoError(json.Unmarshal(w.Body.Bytes(), &resp))
r.Equal("core/Fault", resp["mwtype"])
}

func TestMWLegacyHandler_RedirectErrorWithInvalidState(t *testing.T) {
r := require.New(t)
srv := newTestServer()

req := httptest.NewRequest(http.MethodGet, "/oauth/v1/redirect?error=access_denied&state=100-javascript:alert(1)", nil)
w := httptest.NewRecorder()
srv.MWLegacyHandler().ServeHTTP(w, req)

r.Equal(http.StatusOK, w.Code)
var resp map[string]any
r.NoError(json.Unmarshal(w.Body.Bytes(), &resp))
r.Equal("core/Fault", resp["mwtype"])
}

func TestMWLegacyHandler_RedirectMissingCodeAndError(t *testing.T) {
r := require.New(t)
srv := newTestServer()

req := httptest.NewRequest(http.MethodGet, "/oauth/v1/redirect?state=100-http://localhost:1234/cb", nil)
w := httptest.NewRecorder()
srv.MWLegacyHandler().ServeHTTP(w, req)

r.Equal(http.StatusOK, w.Code)
var resp map[string]any
r.NoError(json.Unmarshal(w.Body.Bytes(), &resp))
r.Equal("core/Fault", resp["mwtype"])
}

func TestMWLegacyHandler_Token(t *testing.T) {
r := require.New(t)
srv := newTestServer()
Expand Down
28 changes: 17 additions & 11 deletions internal/catalog.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 18 additions & 3 deletions internal/docs/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -535,13 +535,12 @@
},
"/redirect": {
"get": {
"description": "Receives authorization code and state from the OAuth2 provider,\nthen redirects the browser back to the desktop client's local HTTP listener.",
"description": "Receives the authorization response from the OAuth2 provider,\nthen redirects the browser back to the desktop client's local HTTP listener.\nIf the user cancels or denies consent, the provider sends error (e.g. access_denied)\nand state instead of code; these are forwarded to the client so it can fail immediately.",
"parameters": [
{
"description": "Authorization code from OAuth2 provider",
"description": "Authorization code from OAuth2 provider (required unless error is present)",
"in": "query",
"name": "code",
"required": true,
"schema": {
"type": "string"
}
Expand All @@ -554,6 +553,22 @@
"schema": {
"type": "string"
}
},
{
"description": "OAuth2 error code from provider, e.g. access_denied when consent is cancelled",
"in": "query",
"name": "error",
"schema": {
"type": "string"
}
},
{
"description": "Human-readable error description from provider",
"in": "query",
"name": "error_description",
"schema": {
"type": "string"
}
}
],
"responses": {
Expand Down
7 changes: 7 additions & 0 deletions internal/locales/en-US/out.gotext.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@
"translatorComment": "Copied from source.",
"fuzzy": true
},
{
"id": "Sign-in was cancelled or did not complete. You may close this tab.",
"message": "Sign-in was cancelled or did not complete. You may close this tab.",
"translation": "Sign-in was cancelled or did not complete. You may close this tab.",
"translatorComment": "Copied from source.",
"fuzzy": true
},
{
"id": "Click here if not redirected automatically.",
"message": "Click here if not redirected automatically.",
Expand Down
5 changes: 5 additions & 0 deletions internal/locales/fr-FR/messages.gotext.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
"id": "Click here if not redirected automatically.",
"message": "Click here if not redirected automatically.",
"translation": "Cliquez ici si vous n'êtes pas redirigé automatiquement."
},
{
"id": "Sign-in was cancelled or did not complete. You may close this tab.",
"message": "Sign-in was cancelled or did not complete. You may close this tab.",
"translation": "La connexion a été annulée ou n'a pas abouti. Vous pouvez fermer cet onglet."
}
]
}
5 changes: 5 additions & 0 deletions internal/locales/fr-FR/out.gotext.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
"message": "Authentication complete. You may close this tab.",
"translation": "Authentification terminée. Vous pouvez fermer cet onglet."
},
{
"id": "Sign-in was cancelled or did not complete. You may close this tab.",
"message": "Sign-in was cancelled or did not complete. You may close this tab.",
"translation": "La connexion a été annulée ou n'a pas abouti. Vous pouvez fermer cet onglet."
},
{
"id": "Click here if not redirected automatically.",
"message": "Click here if not redirected automatically.",
Expand Down
42 changes: 28 additions & 14 deletions internal/redirect/redirect.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,30 +91,30 @@ func loadRedirectTemplate() *template.Template {
}

// @Summary OAuth2 redirect callback
// @Description Receives authorization code and state from the OAuth2 provider,
// @Description Receives the authorization response from the OAuth2 provider,
// @Description then redirects the browser back to the desktop client's local HTTP listener.
// @Description If the user cancels or denies consent, the provider sends error (e.g. access_denied)
// @Description and state instead of code; these are forwarded to the client so it can fail immediately.
// @Tags oauth
// @Produce html
// @Param code query string true "Authorization code from OAuth2 provider"
// @Param state query string true "State containing appID and client redirect URL (format: appID-redirectURL)"
// @Success 200 {string} string "HTML page that redirects the browser"
// @Failure 200 {object} domain.FaultResponse "Fault on missing or invalid parameters"
// @Param code query string false "Authorization code from OAuth2 provider (required unless error is present)"
// @Param state query string true "State containing appID and client redirect URL (format: appID-redirectURL)"
// @Param error query string false "OAuth2 error code from provider, e.g. access_denied when consent is cancelled"
// @Param error_description query string false "Human-readable error description from provider"
// @Success 200 {string} string "HTML page that redirects the browser"
// @Failure 200 {object} domain.FaultResponse "Fault on missing or invalid parameters"
// @Router /redirect [get]
func (h *handler) handleRedirect(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
state := r.URL.Query().Get("state")
query := r.URL.Query()
providerErr := query.Get("error")

if state == "" || code == "" {
domain.WriteFault(w, "StatusBadRequest", "state and code query params not found")
return
}

appID, stateURL, faultMsg := parseRedirectState(state)
appID, stateURL, faultMsg := parseCallback(query.Get("code"), query.Get("state"), providerErr)
if faultMsg != "" {
domain.WriteFault(w, "StatusBadRequest", faultMsg)
return
}

// The full query (code or error, plus state) is forwarded to the client listener.
newURL := *r.URL
newURL.Scheme = stateURL.Scheme
newURL.Host = stateURL.Host
Expand All @@ -128,11 +128,16 @@ func (h *handler) handleRedirect(w http.ResponseWriter, r *http.Request) {
title = app.Description
}

complete := p.Sprintf("Authentication complete. You may close this tab.")
if providerErr != "" {
complete = p.Sprintf("Sign-in was cancelled or did not complete. You may close this tab.")
}

data := redirectData{
URL: template.URL(newURL.String()),
Lang: tag.String(),
Title: title,
Complete: p.Sprintf("Authentication complete. You may close this tab."),
Complete: complete,
ClickHere: p.Sprintf("Click here if not redirected automatically."),
}

Expand All @@ -143,6 +148,15 @@ func (h *handler) handleRedirect(w http.ResponseWriter, r *http.Request) {
loadRedirectTemplate().Execute(w, data) //nolint:errcheck
}

// parseCallback requires a valid state so the browser can always be sent back to
// the client, plus either an authorization code or a provider error.
func parseCallback(code, state, providerErr string) (appID string, stateURL *url.URL, faultMsg string) {
if state == "" || (code == "" && providerErr == "") {
return "", nil, "state and code query params not found"
}
return parseRedirectState(state)
}

func parseRedirectState(state string) (appID string, stateURL *url.URL, faultMsg string) {
pieces := strings.SplitN(state, "-", 2)
if len(pieces) != 2 {
Expand Down
23 changes: 21 additions & 2 deletions matlab/example_usage.m
Original file line number Diff line number Diff line change
Expand Up @@ -62,25 +62,31 @@
authCode = "";
authState = "";
authScope = "";
authError = "";
authErrorDesc = "";
for i = 1:numel(queryParams)
if queryParams(i).Name == "code"
authCode = string(queryParams(i).Value);
elseif queryParams(i).Name == "state"
authState = string(queryParams(i).Value);
elseif queryParams(i).Name == "scope"
authScope = string(queryParams(i).Value);
elseif queryParams(i).Name == "error"
authError = string(queryParams(i).Value);
elseif queryParams(i).Name == "error_description"
authErrorDesc = urldecode(string(queryParams(i).Value));
end
end
else
% Read the HTTP request
pause(0.5);
rawRequest = read(server, server.NumBytesAvailable, "string");

% Send a minimal HTTP response so the browser shows success
% Send a minimal HTTP response so the browser tab can be closed
httpResponse = "HTTP/1.1 200 OK" + newline + ...
"Content-Type: text/html" + newline + ...
"Connection: close" + newline + newline + ...
"<html><body><h3>Authentication complete. You may close this tab.</h3></body></html>";
"<html><body><h3>You may close this tab.</h3></body></html>";
write(server, uint8(char(httpResponse)));
pause(0.2);
delete(server);
Expand All @@ -93,17 +99,30 @@
authCode = "";
authState = "";
authScope = "";
authError = "";
authErrorDesc = "";
for i = 1:numel(queryParams)
if queryParams(i).Name == "code"
authCode = string(queryParams(i).Value);
elseif queryParams(i).Name == "state"
authState = string(queryParams(i).Value);
elseif queryParams(i).Name == "scope"
authScope = string(queryParams(i).Value);
elseif queryParams(i).Name == "error"
authError = string(queryParams(i).Value);
elseif queryParams(i).Name == "error_description"
authErrorDesc = urldecode(string(queryParams(i).Value));
end
end
end

% The proxy forwards provider errors (e.g. access_denied when the user
% cancels consent) instead of a code
if authError == "access_denied"
error("Sign-in was cancelled or consent was not granted. %s", authErrorDesc);
elseif authError ~= ""
error("Authorization failed (%s). %s", authError, authErrorDesc);
end
if authCode == ""
error("No authorization code found in callback.");
end
Expand Down
Loading