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

Merged

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

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?

Copy link
Member Author

@HuiSF HuiSF Jan 30, 2025

Choose a reason for hiding this comment

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

Oh good catch! sameSite: 'strict' should be the default value when server-side auth is enabled, but it can be overwrite by runtimeOptions.cookies.sameSite.


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 +39 to +51
export const DEFAULT_SERVER_SIDE_AUTH_SET_COOKIE_OPTIONS = {
sameSite: 'strict' as const,
};
export const ENFORCED_SERVER_SIDE_AUTH_SET_COOKIE_OPTIONS = {
httpOnly: true,
};

export const SERVER_AUTH_ALLOWED_AMPLIFY_AUTH_KEY_SUFFIX = [
'.accessToken',
'.idToken',
'.refreshToken',
'.LastAuthUser',
];
Copy link
Member

Choose a reason for hiding this comment

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

We should start to freeze the objects if they are const.

Copy link
Member Author

Choose a reason for hiding this comment

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

We have a corresponding unit test with hardcoded set as a guardrail from changing this set of suffixes freely.

@HuiSF HuiSF merged commit 79cccbc into feat/server-auth/main Jan 30, 2025
28 checks passed
@HuiSF HuiSF deleted the hui/fix/feat/server-auth/wrong-cookie-attrs branch January 30, 2025 23:07
HuiSF added a commit that referenced this pull request Feb 11, 2025
* feat(adapter-nextjs): add runtimeOptions.cookies to createServerRunner (#13788)

* feat(aws-amplify|adapter-nextjs): add runtimeOptions.cookies to createServerRunner

* chore: resolve comments

* chore(adapter-nextjs): adapt the latest impl. changes

* feat(adapter-nextjs): add createAuthRouteHandlers to createServerRunner (#13801)

* feat(aws-amplify|adapter-nextjs): add runtimeOptions.cookies to createServerRunner

* feat(adapter-nextjs): add createAuthRouteHandlers to createServerRunner

* chore(adapter-nextjs): resolve comments

* chore(adapter-nextjs): remove unnecessary check

* feat(adapter-nextjs): server-side auth flows integrating cognito hosted UI (#13827)

* chore(auth): export necessary utilities and types to support server-side auth

* chore(aws-amplify): export necessary utilities to support server-side auth

* feat(adapter-nextjs): server-side auth api route integrating cognito hosted ui

* chore(adapter-nextjs): resolve comments

* refactor(adapter-nextjs): remove redundant username fallback

* feat(adapter-nextjs): add user has signed in check before initiating sign-in and sign-up (#13839)

* feat(adapter-nextjs): add user has signed in check before initiating sign-in and sign-up

* chore(adapter-nextjs): rename hasUserSignedIn to hasActiveUserSession

* fix(adapter-nextjs): make createAuthRouteHandlers interface work in both App and Pages routers (#13840)

* feat(adapter-nextjs): set cookie secure: false with non-SSL domain (#13841)

* feat(adapter-nextjs): allow cookie secure: false with non-SSL domain

* fix(adapter-nextjs): wrong naming and impl. of isSSLOrigin

* chore(adapter-nextjs): resolve comment

* refactor(adapter-nextjs): use maxAge attribute to set cookie from server to avoid clock drift (#14103)

* fix(adapter-nextjs): wrong use of nullish coalescing (#14112)

* refactor(adapter-nextjs): remove redundant clockDrift cookie (#14114)

refactor(adapter-nextjs): remove redundant clockDrift cookie ⤵️

Reasons:
  1. token exachange is happening on a server - and production server rarely has wrong system time
  2. when setting token cookies from server, it uses Max-Age header which is relative to the client system time. Clock drift became irrelevant
  3. surely we can argue sever system time can go wrong too, however, a Next.js app API route can be executed on different servers (load balancing), there is no source of truth to generate a clock drift value

* chore: enable tag publishing for server-auth (#14115)

* fix(adapter-nextjs): wrong spot for checking app origin and auth config (#14119)

* fix(adapter-nextjs): not await params async API in Next.js 15 (#14125)

* feat(adapter-nextjs): surface redirect error and sign-in timeout error (#14116)

* feat(adapter-nextjs): surface redirect error and sign-in timeout error

* feat(adapter-nextjs): expose both error and errorDescription

* chore(adapter-nextjs): remove unnecessary undefined fallback

* chore(adapter-nextjs): add warning re: using http in production (#14134)

* fix(core): generateRandomString uses Math.random() (#14132)

* fix(core): generateRandomString uses Math.random()

* chore(core): use better test to test actual logic

* chore(aws-amplify/adapter-nextjs): remove extraneous deps (#14141)

* fix(adapter-nextjs): removing only tokens and LastAuthUser cookies (#14152)

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

* chore: add E2E tests for next.js server auth

* chore: disable tag release

* fix(aws-amplify|api): internals export paths
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.

4 participants