Skip to content
Open
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
5 changes: 1 addition & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,7 @@ return <h1>{t('Dashboard')}</h1>;

## Authentication & Environment

The app supports two auth providers via `AUTH_PROVIDER` env var:

- `OKTA` (default) - requires `OKTA_*` variables
- `API_OAUTH` - requires `API_OAUTH_*` variables
The app signs in with Okta (`AUTH_PROVIDER=OKTA`), which requires the `OKTA_*` variables.

Critical environment setup:

Expand Down
19 changes: 3 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ Note: there is a test account you can use. Get this from another developer if yo

### Cru specific secrets

- `AUTH_PROVIDER` - Name of auth provider used in application. Set to `OKTA` or `API_OAUTH`
- `AUTH_PROVIDER` - Name of auth provider used in application. Set to `OKTA`
- `ROLLBAR_ACCESS_TOKEN` - Optional token for sending error reports to Rollbar
- `ROLLBAR_SERVER_ACCESS_TOKEN` - Optional token for sending error reports on server pages to Rollbar
- `CROWDIN_API_TOKEN` - Secret key for uploading/downloading translations from CrowdIn
Expand All @@ -118,32 +118,19 @@ Note: there is a test account you can use. Get this from another developer if yo

#### Auth provider

MPDX has two auth providers, Okta (which is default) and our own API OAuth. You'll need to configure one.
MPDX signs in with Okta. You'll need to configure it.

```
AUTH_PROVIDER=OKTA
```

AUTH_PROVIDER can be changed to the following auth providers options: `OKTA` or `API_OAUTH`.

If you choose `OKTA`, you will also need to configure these environment variables.
You will also need to configure these environment variables.

- `OKTA_CLIENT_ID` - Okta Client ID for your Okta account
- `OKTA_CLIENT_SECRET` - Okta Client secret for your Okta account
- `OKTA_ISSUER` - Okta issuer web address
- `OKTA_SIGNOUT_REDIRECT_URL` - URL to send user after successful logout. Must match Default App Sign-In Custom Url on Okta's settings.

If you choose `API_OAUTH`, you will need to configure these environment variables.

- `API_OAUTH_CLIENT_ID` - Api OAuth Client ID
- `API_OAUTH_CLIENT_SECRET` - Api OAuth Client Secret
- `API_OAUTH_ISSUER_AUTHORIZATION_URL` - Api OAuth issuer authorization url
- `API_OAUTH_ISSUER_TOKEN_URL` - Api OAuth issuer token url
- `API_OAUTH_SCOPE` - Scope for Api OAuth
- `API_OAUTH_VISIBLE_NAME` - UI name for your OAuth, default is `SSO`.

_Also if you're viewing the next-auth code, you'll come across this file `pages/api/auth/apiOauthSignIn.ts`. `apiOauthSignIn.ts` is a Graphql generated file, but since the apiOauthSignIn Graphql isn't added to MPDX API Prod, only to MPDX API Staging for security reasons. We've added the generated file for apiOauthSignIn and not the GraphQl file since it will cause build errors on prod._

#### Favicon & Logo Env Vars

Since we don't want accidental re-use of our logos by non-Cru organizations, the values of `NEXT_PUBLIC_MEDIA_LOGO` and `NEXT_PUBLIC_MEDIA_FAVICON` are not included in this README.
Expand Down
15 changes: 0 additions & 15 deletions next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@ if (process.env.secrets && process.env.secrets !== '{}') {
process.env.OKTA_CLIENT_SECRET = JSON.parse(
process.env.secrets,
).OKTA_CLIENT_SECRET;
process.env.API_OAUTH_CLIENT_SECRET = JSON.parse(
process.env.secrets,
).API_OAUTH_CLIENT_SECRET;
process.env.ROLLBAR_SERVER_ACCESS_TOKEN = JSON.parse(
process.env.secrets,
).ROLLBAR_SERVER_ACCESS_TOKEN;
Expand Down Expand Up @@ -43,18 +40,6 @@ const config: NextConfig = {
OKTA_ISSUER: process.env.OKTA_ISSUER ?? 'https://signon.okta.com',
OKTA_SIGNOUT_REDIRECT_URL:
process.env.OKTA_SIGNOUT_REDIRECT_URL ?? 'http://localhost:3000',
API_OAUTH_CLIENT_ID:
process.env.API_OAUTH_CLIENT_ID ??
'3nxoth_gyetHdpjKp2WYkND1PUQlvYcjXQHW9ZdDxq4',
API_OAUTH_CLIENT_SECRET: process.env.API_OAUTH_CLIENT_SECRET,
API_OAUTH_ISSUER_AUTHORIZATION_URL:
process.env.API_OAUTH_ISSUER_AUTHORIZATION_URL ??
'https://api.stage.mpdx.org/oauth/authorize',
API_OAUTH_ISSUER_TOKEN_URL:
process.env.API_OAUTH_ISSUER_TOKEN_URL ??
'https://api.stage.mpdx.org/oauth/token',
API_OAUTH_SCOPE: process.env.API_OAUTH_SCOPE ?? 'read write',
API_OAUTH_VISIBLE_NAME: process.env.API_OAUTH_VISIBLE_NAME ?? 'SSO',
GOOGLE_MAPS_API_KEY: process.env.GOOGLE_MAPS_API_KEY,
GOOGLE_TAG_MANAGER_CONTAINER_ID:
process.env.GOOGLE_TAG_MANAGER_CONTAINER_ID,
Expand Down
82 changes: 82 additions & 0 deletions pages/api/auth/[...nextauth].page.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// The real next-auth pulls in ESM-only dependencies that Jest cannot load, and the guards run
// before either export is used
jest.mock('next-auth', () => jest.fn());
jest.mock('next-auth/providers/okta', () => jest.fn(() => ({ id: 'okta' })));

describe('NextAuth startup guards', () => {
const originalEnv = process.env;

const loadAuth = () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('./[...nextauth].page');
};

beforeEach(() => {
jest.resetModules();
process.env = {
...originalEnv,
AUTH_PROVIDER: 'OKTA',
OKTA_CLIENT_ID: 'okta-client-id',
OKTA_CLIENT_SECRET: 'okta-client-secret',
OKTA_ISSUER: 'https://example.okta.com',
};
});

afterAll(() => {
process.env = originalEnv;
});

it('loads when AUTH_PROVIDER is OKTA and the Okta envs are set', () => {
expect(loadAuth).not.toThrow();
});

it.each(['API_OAUTH', 'okta', '', undefined])(
'throws when AUTH_PROVIDER is %p',
(authProvider) => {
process.env.AUTH_PROVIDER = authProvider;

expect(loadAuth).toThrow(
'AUTH_PROVIDER environment variable needs to equal "OKTA"',
);
},
);

it.each(['OKTA_CLIENT_ID', 'OKTA_CLIENT_SECRET', 'OKTA_ISSUER'])(
'throws when %s is missing',
(envName) => {
delete process.env[envName];

expect(loadAuth).toThrow(
'OKTA_CLIENT_ID, OKTA_CLIENT_SECRET or OKTA_ISSUER envs not defined',
);
},
);

describe('options', () => {
const getOptions = () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { default: Auth } = require('./[...nextauth].page');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const NextAuth = require('next-auth') as jest.Mock;
Auth({}, {});
return NextAuth.mock.calls[0][2];
};

it('configures only the Okta provider', () => {
expect(getOptions().providers).toEqual([{ id: 'okta' }]);
});

it('sends sign out to the Okta sign-out URL', () => {
process.env.OKTA_SIGNOUT_REDIRECT_URL = 'https://mpdx.org/login';

expect(
getOptions().callbacks.redirect({
url: 'signOut',
baseUrl: 'https://mpdx.org',
}),
).toBe(
'https://signon.okta.com/login/signout?fromURI=https%3A%2F%2Fmpdx.org%2Flogin',
);
});
});
});
126 changes: 16 additions & 110 deletions pages/api/auth/[...nextauth].page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,6 @@
GetUserAccessQueryVariables,
} from 'src/components/Shared/MultiPageLayout/MultiPageMenu/MultiPageMenuItems.generated';
import makeSsrClient from 'src/lib/apollo/ssrClient';
import {
ApiOauthSignInDocument,
ApiOauthSignInMutation,
ApiOauthSignInMutationVariables,
} from './apiOauthSignIn';
import { isJwtExpired, setUserInfo } from './helpers';
import {
OktaSignInDocument,
Expand Down Expand Up @@ -59,96 +54,28 @@
const AUTH_PROVIDER = process.env.AUTH_PROVIDER,
OKTA_CLIENT_ID = process.env.OKTA_CLIENT_ID,
OKTA_CLIENT_SECRET = process.env.OKTA_CLIENT_SECRET,
OKTA_ISSUER = process.env.OKTA_ISSUER,
API_OAUTH_CLIENT_ID = process.env.API_OAUTH_CLIENT_ID,
API_OAUTH_CLIENT_SECRET = process.env.API_OAUTH_CLIENT_SECRET,
API_OAUTH_ISSUER_AUTHORIZATION_URL =
process.env.API_OAUTH_ISSUER_AUTHORIZATION_URL,
API_OAUTH_ISSUER_TOKEN_URL = process.env.API_OAUTH_ISSUER_TOKEN_URL,
API_OAUTH_SCOPE = process.env.API_OAUTH_SCOPE;
OKTA_ISSUER = process.env.OKTA_ISSUER;

if (AUTH_PROVIDER !== 'OKTA' && AUTH_PROVIDER !== 'API_OAUTH') {
throw new Error(
'AUTH_PROVIDER environment variable needs to equal either "OKTA" or "API_OAUTH"',
);
if (AUTH_PROVIDER !== 'OKTA') {
throw new Error('AUTH_PROVIDER environment variable needs to equal "OKTA"');
}

if (
AUTH_PROVIDER === 'OKTA' &&
(!OKTA_CLIENT_ID || !OKTA_CLIENT_SECRET || !OKTA_ISSUER)
) {
if (!OKTA_CLIENT_ID || !OKTA_CLIENT_SECRET || !OKTA_ISSUER) {
throw new Error(
'OKTA_CLIENT_ID, OKTA_CLIENT_SECRET or OKTA_ISSUER envs not defined',
);
}
if (
AUTH_PROVIDER === 'API_OAUTH' &&
(!API_OAUTH_CLIENT_ID ||
!API_OAUTH_CLIENT_SECRET ||
!API_OAUTH_ISSUER_AUTHORIZATION_URL ||
!API_OAUTH_ISSUER_TOKEN_URL ||
!API_OAUTH_SCOPE)
) {
throw new Error(
'API_OAUTH_CLIENT_ID, API_OAUTH_CLIENT_SECRET, API_OAUTH_ISSUER_AUTHORIZATION_URL, API_OAUTH_ISSUER_TOKEN_URL or API_OAUTH_SCOPE envs not defined',
);
}

const providersArray: NextAuthOptions['providers'] = [];

if (AUTH_PROVIDER === 'OKTA') {
providersArray.push(
OktaProvider({
clientId: OKTA_CLIENT_ID ?? '',
clientSecret: OKTA_CLIENT_SECRET ?? '',
issuer: OKTA_ISSUER ?? '',
authorization: { params: { scope: 'openid email profile' } },
token: { params: { scope: 'openid email profile' } },
userinfo: { params: { scope: 'openid email profile' } },
}),
);
}

if (AUTH_PROVIDER === 'API_OAUTH') {
providersArray.push({
id: 'apioauth',
name: process.env.API_OAUTH_VISIBLE_NAME ?? 'SSO',
type: 'oauth',
clientId: API_OAUTH_CLIENT_ID ?? '',
clientSecret: API_OAUTH_CLIENT_SECRET ?? '',
authorization: {
url: API_OAUTH_ISSUER_AUTHORIZATION_URL ?? '',
params: { scope: API_OAUTH_SCOPE ?? '', response_type: 'code' },
},
token: {
url: API_OAUTH_ISSUER_TOKEN_URL ?? '',
params: { scope: API_OAUTH_SCOPE ?? '', response_type: 'code' },
},
userinfo: {
async request() {
// Our API doesn't use the auth/userInfo endpoint, but NextAuth requires it to get the access token.
// Since we pass the access_token to our API, which returns a JWT, user and authenticates via GraphQL
// We can just return a object with hardcoded info, as it doesn't get used anywhere.
return {
sub: '83692',
name: 'Alice Adams',
given_name: 'Alice',
family_name: 'Adams',
email: 'alice.adams@gmail.cpm',
picture: 'https://example.com/83692/photo.jpg',
};
},
},
idToken: false,
profile(profile) {
return {
id: profile?.sub,
email: profile?.email,
};
},
checks: ['pkce', 'state'],
});
}
const providersArray: NextAuthOptions['providers'] = [
OktaProvider({
clientId: OKTA_CLIENT_ID ?? '',
clientSecret: OKTA_CLIENT_SECRET ?? '',
issuer: OKTA_ISSUER ?? '',
authorization: { params: { scope: 'openid email profile' } },
token: { params: { scope: 'openid email profile' } },
userinfo: { params: { scope: 'openid email profile' } },
}),
];

const Auth = (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
const options: NextAuthOptions = {
Expand Down Expand Up @@ -184,30 +111,9 @@
}
};

// An API token is not required for the apiOauthSignIn or oktaSignIn mutations
// An API token is not required for the oktaSignIn mutation
const ssrClient = makeSsrClient(null);

Check notice on line 116 in pages/api/auth/[...nextauth].page.ts

View check run for this annotation

CodeScene Delta Analysis / CodeScene Code Health Review (main)

✅ No longer an issue: Complex Method

signIn is no longer above the threshold for cyclomatic complexity
if (account.provider === 'apioauth') {
const { data } = await ssrClient.mutate<
ApiOauthSignInMutation,
ApiOauthSignInMutationVariables
>({
mutation: ApiOauthSignInDocument,
variables: {
accessToken: access_token,
},
});

if (data?.apiOauthSignIn?.token && data?.apiOauthSignIn?.user) {
await handleSettingUserInfo(
data.apiOauthSignIn.token,
data.apiOauthSignIn.user.id,
);
return true;
}
throw new Error('apiOauthSignIn mutation failed to return a token');
}

const { data } = await ssrClient.mutate<
OktaSignInMutation,
OktaSignInMutationVariables
Expand Down Expand Up @@ -284,7 +190,7 @@
if (url.startsWith(baseUrl)) {
return url;
}
if (url === 'signOut' && AUTH_PROVIDER === 'OKTA') {
if (url === 'signOut') {
return `https://signon.okta.com/login/signout?fromURI=${encodeURIComponent(
process.env.OKTA_SIGNOUT_REDIRECT_URL ?? '',
)}`;
Expand Down
Loading
Loading