8000 fix(site): sanitize login redirect by coadler · Pull Request #15208 · coder/coder · GitHub
[go: up one dir, main page]

Skip to content

fix(site): sanitize login redirect #15208

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 10 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
fix: login redirect
  • Loading branch information
coadler committed Oct 23, 2024
commit cc25e09d343e04ff437285f5bc4ec253d7ca6794
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -256,5 +256,8 @@

"[css][html][markdown][yaml]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "biomejs.biome"
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"storybook": "pnpm run -C site/ storybook"
},
"devDependencies": {
"@biomejs/biome": "1.9.4",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

biome extension doesn't work in vscode unless you have dep in root dir 😢

"prettier": "3.3.3"
}
}
91 changes: 91 additions & 0 deletions pnpm-lock.yaml

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

14 changes: 14 additions & 0 deletions site/src/api/queries/regions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { API } from "api/api";
import type { Region } from "api/typesGenerated";
import type { MetadataState } from "hooks/useEmbeddedMetadata";
import { cachedQuery } from "./util";

const regionsKey = ["regions"] as const;

export const regions = (metadata: MetadataState<readonly Region[]>) => {
return cachedQuery({
metadata,
queryKey: regionsKey,
queryFn: () => API.getWorkspaceProxyRegions(),
});
};
95 changes: 60 additions & 35 deletions site/src/pages/LoginPage/LoginPage.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { buildInfo } from "api/queries/buildInfo";
import { regions } from "api/queries/regions";
import { authMethods } from "api/queries/users";
import { useAuthContext } from "contexts/auth/AuthProvider";
import { useEmbeddedMetadata } from "hooks/useEmbeddedMetadata";
import { type FC, useEffect } from "react";
import { type FC, useEffect, useState } from "react";
import { Helmet } from "react-helmet-async";
import { useQuery } from "react-query";
import { Navigate, useLocation, useNavigate } from "react-router-dom";
Expand All @@ -28,6 +29,20 @@ export const LoginPage: FC = () => {
const navigate = useNavigate();
const { metadata } = useEmbeddedMetadata();
const buildInfoQuery = useQuery(buildInfo(metadata["build-info"]));
const regionsQuery = useQuery(regions(metadata.regions));
const [redirectError, setRedirectError] = useState<Error | null>(null);
let redirectUrl: URL | null = null;
try {
redirectUrl = new URL(redirectTo);
} catch (err) {
// Do nothing
}

const isApiRoute = redirectTo.startsWith("/api/v2");
const isLocalRedirect =
(!redirectUrl ||
(redirectUrl && redirectUrl.host === window.location.host)) &&
!isApiRoute;

useEffect(() => {
if (!buildInfoQuery.data || isSignedIn) {
Expand All @@ -41,42 +56,50 @@ export const LoginPage: FC = () => {
});
}, [isSignedIn, buildInfoQuery.data, user?.id]);

if (isSignedIn) {
if (buildInfoQuery.data) {
// This uses `navigator.sendBeacon`, so window.href
// will not stop the request from being sent!
sendDeploymentEvent(buildInfoQuery.data, {
type: "deployment_login",
user_id: user?.id,
});
useEffect(() => {
if (!isSignedIn || !regionsQuery.data || isLocalRedirect) {
return;
}

// If the redirect is going to a workspace application, and we
// are missing authentication, then we need to change the href location
// to trigger a HTTP request. This allows the BE to generate the auth
// cookie required. Similarly for the OAuth2 exchange as the authorization
// page is served by the backend.
// If no redirect is present, then ignore this branched logic.
if (redirectTo !== "" && redirectTo !== "/") {
try {
// This catches any absolute redirects. Relative redirects
// will fail the try/catch. Subdomain apps are absolute redirects.
const redirectURL = new URL(redirectTo);
if (redirectURL.host !== window.location.host) {
window.location.href = redirectTo;
return null;
}
} catch {
// Do nothing
}
// Path based apps and OAuth2.
if (redirectTo.includes("/apps/") || redirectTo.includes("/oauth2/")) {
window.location.href = redirectTo;
return null;
}
const regions = regionsQuery.data.regions;
const pathUrls = regions
? regions
.map((region) => {
try {
return new URL(region.path_app_url);
} catch {
return null;
}
})
.filter((url) => url !== null)
: [];
const wildcardHostnames = regions
? regions
.map((region) => region.wildcard_hostname)
.filter((hostname) => hostname !== "")
// remove the leading '*' from the hostname
.map((hostname) => hostname.slice(1))
: [];

const allowed =
pathUrls.some((url) => url.host === window.location.host) ||
wildcardHostnames.some((wildcard) =>
window.location.host.endsWith(wildcard),
) ||
// api routes need to be manually set with href
isApiRoute;

if (allowed) {
window.location.href = redirectTo;
} else {
setRedirectError(new Error("invalid redirect url"));
}
}, [isSignedIn, regionsQuery.data, redirectTo, isLocalRedirect, isApiRoute]);

return <Navigate to={redirectTo} replace />;
if (isSignedIn && isLocalRedirect) {
return (
<Navigate to={redirectUrl ? redirectUrl.pathname : redirectTo} replace />
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I poked around a bit more of the code, and I'm just making sure: there's a second file that calls the retrieveRedirect function (LoginPageView.tsx). Do we need to update anything around that?

Because right now, the control flow is set up so that the component:

  1. Gets the redirectTo value from the search param's redirect param
  2. Passes it to the SignInForm
  3. Passes that to the OAuthSignInForm
  4. As long as GitHub is enabled as an auth method, a button shows up with an href that uses the raw redirectTo as a param

Not sure how the callback logic works, but would the updates to this file catch any issues from there?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, good find. This is being sent directly to the backend which handles approving the redirect URLs, so it doesn't need any validation from the frontend.

);
}

if (isConfiguringTheFirstUser) {
Expand All @@ -90,8 +113,10 @@ export const LoginPage: FC = () => {
</Helmet>
<LoginPageView
authMethods={authMethodsQuery.data}
error={signInError}
isLoading={isLoading || authMethodsQuery.isLoading}
error={redirectError ?? signInError}
isLoading={
isLoading || authMethodsQuery.isLoading || regionsQuery.isLoading
}
buildInfo={buildInfoQuery.data}
isSigningIn={isSigningIn}
onSignIn={async ({ email, password }) => {
Expand Down
2 changes: 1 addition & 1 deletion site/src/utils/redirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ export const retrieveRedirect = (search: string): string => {
const defaultRedirect = "/";
const searchParams = new URLSearchParams(search);
const redirect = searchParams.get("redirect");
return redirect ? redirect : defaultRedirect;
return redirect ?? defaultRedirect;
};
Loading
0