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

fix(adapter-nextjs): wrong cookie attributes get set sometimes #14169

Open
wants to merge 3 commits into
base: feat/server-auth/main
Choose a base branch
from

Conversation

HuiSF
Copy link
Member

@HuiSF HuiSF commented Jan 28, 2025

Description of changes

Change 1
Create a global context store on the server start (when createServerRunner gets called) for separated processes (the runWithAmplifyServerContext, and the runWithAmplifyServerContext used by the data server-side client factories) of the library, so they can look up flags and configurations as the following:

  1. isServerSideAuthEnabled (determined by whether the AMPLIFY_APP_ORIGIN env var is set as it's the prerequisite of enabling server-side auth)
  2. isSSLOrigin (determined by whether AMPLIFY_APP_ORIGIN contains a https non localhost origin)
  3. runtimeOptions (the runtimeOptions object passed in when calling createServerRunner)

At runtime, when some Amplify APIs are called within a closure created by a runWithAmplifyServerContext, globalRuntimeContext is used to retrieve relevant information from the above.

For example: when server side is enabled, runtimeOptions.cookies is always merged with { httpOnly: true } to enforce the token cookies are HTTP only.

Change 2

Instruct the cookie adapters created from Next.js server context that when server-side auth is enabled, when Amplify tokenStore interface attempts to set extra cookies, the adapters should ignore these cookies. (tradeoff of reusing the preexisting token store interface)

Issue #, if available

Description of how you validated changes

  • manual testing with sample apps
  • unit tests
  • E2E test pending to be added

Checklist

  • PR description included
  • yarn test passes
  • Unit Tests are changed or added
  • Relevant documentation is changed or added (and PR referenced)

Checklist for repo maintainers

  • Verify E2E tests for existing workflows are working as expected or add E2E tests for newly added workflows
  • New source file paths included in this PR have been added to CODEOWNERS, if appropriate

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

When server-side auth is enabled, only acessToken, idToken,
refreshToken and LastAuthUser cookies are set in cookie
store. When calling Amplify APIs with runWithAmplifyServerContext
then tokens need to be refreshed, the underlying tokenStore
interface sets extra cookies for the original client-side
use cases which is NOT ideal.
@HuiSF HuiSF changed the title feat(adapter-nextjs): add runtimeOptions.cookies to createServerRunner ( fix(adapter-nextjs): wrong cookie attributes get set sometimes Jan 28, 2025
isServerSideAuthEnabled() {
return isServerSideAuthEnabled;
},
enableServerSideAuth() {
Copy link
Member

Choose a reason for hiding this comment

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

I suspect the answer is no but is there a world where someone would want to freely flip this back and forth?

let isSSLOrigin = false;

export const globalSettings: NextServer.GlobalSettings = {
isServerSideAuthEnabled() {
Copy link
Member

Choose a reason for hiding this comment

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

Super nit: Group setters together and getters together, or keep them in the same order i.e. setter first then getter. Just to aid readability


const mergedSetCookieOptions = {
// default options when not specified
...DEFAULT_SERVER_SIDE_AUTH_SET_COOKIE_OPTIONS,
Copy link
Member

Choose a reason for hiding this comment

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

I think I'm a little thrown off by the naming - these are default setCookie options for server side auth - but it doesn't require isServerSideAuthEnabled to be true?


import { ensureEncodedForJSCookie, serializeCookie } from './cookie';

export const DATE_IN_THE_PAST = new Date(0);

export const createCookieStorageAdapterFromNextServerContext = async (
context: NextServer.Context,
ignoreNonServerSideCookies = false,
Copy link
Member

Choose a reason for hiding this comment

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

What kinds of cookies qualify as "non-server-side"?

Comment on lines +148 to +150
if (ignoreNonServerSideCookies && isServerSideAuthIgnoredCookie(name)) {
return;
}
Copy link
Member

Choose a reason for hiding this comment

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

Nit: Does this need to be in the try? Ditto below

Comment on lines +103 to +104
isServerSideAuthEnabled(): boolean;
enableServerSideAuth(): void;
Copy link
Member

Choose a reason for hiding this comment

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

Super nit: Switch so each grouping has setter first then getter just for ease of understanding

@@ -35,6 +36,15 @@ export const createServerRunner: NextServer.CreateServerRunner = ({
const amplifyConfig = parseAmplifyConfig(config);
const amplifyAppOrigin = process.env.AMPLIFY_APP_ORIGIN;

globalSettings.setRuntimeOptions(runtimeOptions || {});
Copy link
Member

Choose a reason for hiding this comment

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

Can runtimeOptions be falsy in a way that ?? wouldn't work?

@@ -35,6 +36,15 @@ export const createServerRunner: NextServer.CreateServerRunner = ({
const amplifyConfig = parseAmplifyConfig(config);
const amplifyAppOrigin = process.env.AMPLIFY_APP_ORIGIN;

globalSettings.setRuntimeOptions(runtimeOptions || {});

if (amplifyAppOrigin !== undefined && isValidOrigin(amplifyAppOrigin)) {
Copy link
Member

Choose a reason for hiding this comment

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

Nit: Would undefined ever be a valid origin? Or can isValidOrigin just encapsulate that guard/check?

Copy link
Member

Choose a reason for hiding this comment

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

+1 it seems as though isValidOrigin could be adapted to handle an undefined input.

if (amplifyAppOrigin !== undefined && isValidOrigin(amplifyAppOrigin)) {
globalSettings.setIsSSLOrigin(isSSLOrigin(amplifyAppOrigin));

// update the serverSideAuthEnabled flag that exists in the closure of createServerRunner() to true
Copy link
Member

Choose a reason for hiding this comment

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

Is this flag still only in the createServerRunner closure?

@@ -79,3 +82,8 @@ export const createTokenCookiesRemoveOptions = (
path: '/',
maxAge: REMOVE_COOKIE_MAX_AGE, // Expire immediately (remove the cookie)
});

export const isServerSideAuthIgnoredCookie = (cookieName: string) =>
Copy link
Member

Choose a reason for hiding this comment

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

Nit: Would it be more intuitive for this to be server side auth allowed cookie given that that's the list we have? This might be invalidated by a different comment I have below about possibly consolidating the function purpose

),
tokenValidator,
setCookieOptions,
mergedSetCookieOptions,
Copy link
Member

Choose a reason for hiding this comment

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

Nit: It's getting kind of difficult to track what the default set cookie options will be when server side auth is enabled vs disabled. We have defaults in the cookie storage adaptor and here in the runWithAmplifyServerContext factory. Is there a way we can unify or clarify this?

@@ -35,6 +36,15 @@ export const createServerRunner: NextServer.CreateServerRunner = ({
const amplifyConfig = parseAmplifyConfig(config);
const amplifyAppOrigin = process.env.AMPLIFY_APP_ORIGIN;

globalSettings.setRuntimeOptions(runtimeOptions || {});

if (amplifyAppOrigin !== undefined && isValidOrigin(amplifyAppOrigin)) {
Copy link
Member

Choose a reason for hiding this comment

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

+1 it seems as though isValidOrigin could be adapted to handle an undefined input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants