Skip to content
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

[Issue #2654] Next login flow backend #3182

Merged
merged 13 commits into from
Dec 16, 2024
Merged
24 changes: 14 additions & 10 deletions documentation/infra/environment-variables-and-secrets.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ Applications may need application specific configuration as environment variable

> ⚠️ Note: Do not put sensitive information such as credentials as regular environment variables. The method described in this section will embed the environment variables and their values in the ECS task definition's container definitions, so anyone with access to view the task definition will be able to see the values of the environment variables. For configuring secrets, see the section below on [Secrets](#secrets)

Environment variables are defined in the `app-config` module in the [environment-variables.tf file](/infra/app/app-config/env-config/environment-variables.tf). Modify the `default_extra_environment_variables` map to define extra environment variables specific to the application. Map keys define the environment variable name, and values define the default value for the variable across application environments. For example:
Environment variables are defined in the `app-config` module in the [environment_variables.tf file](/infra/app/app-config/env-config/environment_variables.tf). Modify the `default_extra_environment_variables` map to define extra environment variables specific to the application. Map keys define the environment variable name, and values define the default value for the variable across application environments. For example:

```terraform
# environment-variables.tf
# environment_variables.tf

locals {
default_extra_environment_variables = {
Expand Down Expand Up @@ -40,19 +40,23 @@ module "dev_config" {

Secrets are a specific category of environment variables that need to be handled sensitively. Examples of secrets are authentication credentials such as API keys for external services. Secrets first need to be stored in AWS SSM Parameter Store as a `SecureString`. This section then describes how to make those secrets accessible to the ECS task as environment variables through the `secrets` configuration in the container definition (see AWS documentation on [retrieving Secrets Manager secrets through environment variables](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/secrets-envvar-secrets-manager.html)).

Secrets are defined in the same file that non-sensitive environment variables are defined, in the `app-config` module in the [environment-variables.tf file](/infra/app/app-config/env-config/environment-variables.tf). Modify the `secrets` list to define the secrets that the application will have access to. For each secret, `name` defines the environment variable name, and `ssm_param_name` defines the SSM parameter name that stores the secret value. For example:
Secrets are defined in the same file that non-sensitive environment variables are defined, in the `app-config` module in the [environment_variables.tf file](/infra/app/app-config/env-config/environment_variables.tf). Modify the `secrets` map to define the secrets that the application will have access to. For each secret, the map key defines the environment variable name. The `manage_method` property, which can be set to `"generated"` or `"manual"`, defines whether or not to generate a random secret or to reference an existing secret that was manually created and stored into AWS SSM. The `secret_store_name` property defines the SSM parameter name that stores the secret value. If `manage_method = "generated"`, then `secret_store_name` is where terraform will store the secret. If `manage_method = "manual"`, then `secret_store_name` is where terraform will look for the existing secret. For example:

```terraform
# environment-variables.tf
# environment_variables.tf

locals {
secrets = [
{
name = "SOME_API_KEY"
ssm_param_name = "/${var.app_name}-${var.environment}/secret-sauce"
secrets = {
GENERATED_SECRET = {
manage_method = "generated"
secret_store_name = "/${var.app_name}-${var.environment}/generated-secret"
}
]
MANUALLY_CREATED_SECRET = {
manage_method = "manual"
secret_store_name = "/${var.app_name}-${var.environment}/manually-created-secret"
}
}
}
```

> ⚠️ Make sure you store the secret in SSM Parameter Store before you try to add secrets to your application service, or else the service won't be able to start since the ECS Task Executor won't be able to fetch the configured secret.
> ⚠️ For secrets with `manage_method = "manual"`, make sure you store the secret in SSM Parameter Store _before_ you try to add configure your application service with the secrets, or else the service won't be able to start since the ECS Task Executor won't be able to fetch the configured secret.
2 changes: 2 additions & 0 deletions frontend/.env.development
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ USE_SEARCH_MOCK_DATA=false
# DO NOT COMMIT THESE VALUES TO GITHUB
NEW_RELIC_APP_NAME=
NEW_RELIC_LICENSE_KEY=

SESSION_SECRET=extraSecretSessionSecretValueSssh
9 changes: 9 additions & 0 deletions frontend/package-lock.json

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

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"dayjs": "^1.11.13",
"focus-trap-react": "^10.2.3",
"isomorphic-dompurify": "^2.15.0",
"jose": "^5.9.6",
"js-cookie": "^3.0.5",
"lodash": "^4.17.21",
"newrelic": "^12.7.0",
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/app/[locale]/not-found.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default function NotFound() {
<>
<BetaAlert />
<GridContainer className="padding-y-1 tablet:padding-y-3 desktop-lg:padding-y-15 measure-2">
<h1 className="nj-h1">{t("title")}</h1>
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

looks like maybe a remnant from the nj ui project?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Good catch.

<h1>{t("title")}</h1>
<p className="margin-bottom-2">{t("message_content_1")}</p>
<Link className="usa-button" href="/" key="returnToHome">
{t("visit_homepage_button")}
Expand Down
10 changes: 2 additions & 8 deletions frontend/src/app/[locale]/search/error.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import QueryProvider from "src/app/[locale]/search/QueryProvider";
import { ServerSideSearchParams } from "src/types/searchRequestURLTypes";
import { Breakpoints } from "src/types/uiTypes";
import { Breakpoints, ErrorProps } from "src/types/uiTypes";
import { convertSearchParamsToProperTypes } from "src/utils/search/convertSearchParamsToProperTypes";

import { useTranslations } from "next-intl";
Expand All @@ -13,12 +13,6 @@ import SearchBar from "src/components/search/SearchBar";
import SearchFilters from "src/components/search/SearchFilters";
import ServerErrorAlert from "src/components/ServerErrorAlert";

interface ErrorProps {
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

as I removed the error page for User, this doesn't need to be moved at this point, but it's still good practice, I think, so we have it more widely available for future error pages.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Maybe we need to look a little more at error handling across the app.

// Next's error boundary also includes a reset function as a prop for retries,
// but it was not needed as users can retry with new inputs in the normal page flow.
error: Error & { digest?: string };
}

export interface ParsedError {
message: string;
searchInputs: ServerSideSearchParams;
Expand Down Expand Up @@ -54,7 +48,7 @@ function createBlankParsedError(): ParsedError {
};
}

export default function Error({ error }: ErrorProps) {
export default function SearchError({ error }: ErrorProps) {
const t = useTranslations("Search");

// The error message is passed as an object that's been stringified.
Expand Down
37 changes: 37 additions & 0 deletions frontend/src/app/[locale]/user/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Metadata } from "next";
import { LocalizedPageProps } from "src/types/intl";

import { getTranslations } from "next-intl/server";
import { GridContainer } from "@trussworks/react-uswds";

export async function generateMetadata({
params: { locale },
}: LocalizedPageProps) {
const t = await getTranslations({ locale });
const meta: Metadata = {
title: t("User.pageTitle"),
description: t("Index.meta_description"),
};
return meta;
}

// this is a placeholder page used as temporary landing page for login redirects.
// Note that this page only functions to display the message passed down in query params from
// the /api/auth/callback route, and it does not handle errors.
// How to handle errors or failures from the callback route in the UI will need to be revisited
// later on, but note that throwing to an error page won't be an option, as that produces a 500
// response in the client.
export default async function UserDisplay({
searchParams,
params: { locale },
}: LocalizedPageProps & { searchParams: { message?: string } }) {
const { message } = searchParams;

const t = await getTranslations({ locale, namespace: "User" });
return (
<GridContainer>
<h1>{t("heading")}</h1>
{message && <div>{message}</div>}
</GridContainer>
);
}
48 changes: 48 additions & 0 deletions frontend/src/app/api/auth/callback/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { createSession, getSession } from "src/services/auth/session";

import { redirect } from "next/navigation";
import { NextRequest } from "next/server";

const createSessionAndSetStatus = async (
token: string,
successStatus: string,
): Promise<string> => {
try {
await createSession(token);
return successStatus;
} catch (error) {
console.error("error in creating session", error);
return "error!";
}
};

/*
currently it looks like the API will send us a request with the params below, and we will be responsible
for directing the user accordingly. For now, we'll send them to generic success and error pages with cookie set on success

message: str ("success" or "error")
token: str | None
is_user_new: bool | None
error_description: str | None

TODOS:

- translating messages?
- ...
*/
export async function GET(request: NextRequest) {
const currentSession = await getSession();
if (currentSession && currentSession.token) {
const status = await createSessionAndSetStatus(
currentSession.token,
"already logged in",
);
return redirect(`/user?message=${status}`);
}
const token = request.nextUrl.searchParams.get("token");
if (!token) {
return redirect("/user?message=no token provided");
}
const status = await createSessionAndSetStatus(token, "created session");
return redirect(`/user?message=${status}`);
}
2 changes: 2 additions & 0 deletions frontend/src/constants/environments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const {
FEATURE_SEARCH_OFF = "false",
FEATURE_OPPORTUNITY_OFF = "false",
NEXT_BUILD = "false",
SESSION_SECRET = "",
} = process.env;

// home for all interpreted server side environment variables
Expand All @@ -31,4 +32,5 @@ export const environment: { [key: string]: string } = {
FEATURE_OPPORTUNITY_OFF,
FEATURE_SEARCH_OFF,
NEXT_BUILD,
SESSION_SECRET,
};
5 changes: 5 additions & 0 deletions frontend/src/i18n/messages/en/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -548,4 +548,9 @@ export const messages = {
signOff: "Thank you for your patience.",
pageTitle: "Simpler.Grants.gov - Maintenance",
},
User: {
heading: "User",
pageTitle: "User | Simpler.Grants.Gov",
errorHeading: "Error",
},
};
54 changes: 54 additions & 0 deletions frontend/src/services/auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# User Auth

### Notes

- Server components can't write cookies, but middleware, route handlers and server actions can.

### Login flow

- user clicks "login"
- client side component directs users to /api link
- user comes back with a simpler JWT to /auth/callback
- verifies JWT
- sets cookie
- useUser / UserProvider
- checks cookie / API (see diagram)

```mermaid
flowchart TD
checkCookie[Check cookie]
cookieExists{Cookie Exists?}
useUser/UserProvider --> checkCookie
cookieValid{Cookie is Valid}
redirectToLogin[redirect to login]

checkCookie --> cookieExists
cookieExists --> |Yes| cookieValid
cookieExists --> |No| redirectToLogin
cookieValid --> |Yes| d[Return User Data]
cookieValid --> |No| redirectToLogin

```

## Next step

```mermaid
flowchart TD
checkCookie[Check cookie]
cookieExists{Cookie Exists?}
useUser/UserProvider --> checkCookie
cookieValid{Cookie is Valid}
cookieIsCurrent{Cookie is Current}
redirectToLogin[redirect to login]

checkCookie --> cookieExists
cookieExists --> |Yes| cookieValid
cookieExists --> |No| redirectToLogin
cookieValid --> |Yes| cookieIsCurrent
cookieValid --> |No | redirectToLogin
cookieIsCurrent --> |Yes| d[Return User Data]
cookieIsCurrent --> |No| e{User exists with session from /api/user}
e --> |Yes| f[set cookie]
e --> |No| redirectToLogin

```
78 changes: 78 additions & 0 deletions frontend/src/services/auth/session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import "server-only";

import { JWTPayload, jwtVerify, SignJWT } from "jose";
import { environment } from "src/constants/environments";
import { SessionPayload, UserSession } from "src/services/auth/types";
import { encodeText } from "src/utils/generalUtils";

// note that cookies will be async in Next 15
import { cookies } from "next/headers";

const encodedKey = encodeText(environment.SESSION_SECRET);

// returns a new date 1 week from time of function call
export const newExpirationDate = () =>
new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);

export async function encrypt({
token,
expiresAt,
}: SessionPayload): Promise<string> {
const jwt = await new SignJWT({ token })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime(expiresAt)
.sign(encodedKey);
return jwt;
}

export async function decrypt(
sessionCookie: string | undefined = "",
): Promise<JWTPayload | null> {
try {
const { payload } = await jwtVerify(sessionCookie, encodedKey, {
algorithms: ["HS256"],
});
return payload;
} catch (error) {
console.error("Failed to decrypt session cookie", error);
return null;
}
}

// could try memoizing this function if it is a performance risk
export const getTokenFromCookie = async (
cookie: string,
): Promise<UserSession> => {
const decryptedSession = await decrypt(cookie);
if (!decryptedSession) return null;
const token = (decryptedSession.token as string) ?? null;
if (!token) return null;
return {
token,
};
};

// returns token decrypted from session cookie or null
export const getSession = async (): Promise<UserSession> => {
const cookie = cookies().get("session")?.value;
if (!cookie) return null;
return getTokenFromCookie(cookie);
};

export async function createSession(token: string) {
const expiresAt = newExpirationDate();
const session = await encrypt({ token, expiresAt });
cookies().set("session", session, {
httpOnly: true,
secure: true,
expires: expiresAt,
sameSite: "lax",
path: "/",
});
}

// currently unused, will be used in the future for logout
export function deleteSession() {
cookies().delete("session");
}
Loading