Repository navigation
feat(core): let withAuth run signed out with allowAnonymous - #1519
Conversation
…icitly null or empty
withAuth(fn, cookies) treated an explicit null or empty cookies argument
like an omitted one: when neither an existing request context nor a
cookie provider yielded cookies, it threw a 401.
request.headers.get('cookie') is null for a visitor without cookies, so
the documented explicit form failed for every anonymous visitor,
including calls to public API methods during server rendering.
With an explicit null, empty or blank argument, detection runs as before
and detected cookies are still used. When nothing yields cookies, fn now
runs with an empty request cookie store value instead of the 401, so no
Cookie header is forwarded and the API decides, as for a signed-out
browser call. No call that works today changes. The 401 is unchanged
when the argument is omitted or undefined.
Validation: npm run build, npm run lint, npm run lint:deps,
npm test -w @aws-blocks/core (2979 tests, 0 failures, 1 skipped),
npm run check:api (no report changes) all pass. Full unit and e2e suites
left to CI.
🦋 Changeset detectedLatest commit: 3d12f79 The changes in this PR will be included in the next version bump. This PR includes changesets to release 26 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
osama-rizk
left a comment
There was a problem hiding this comment.
This changes withAuth(fn, cookies) so that an explicit null or empty cookies runs the callback signed out instead of throwing 401. On security it's sound: it doesn't open a hole. My one blocking item is the public contract the fix settles on, which still misses a large share of the callers it is meant to help.
What's good
- The new branch sits after the existing-context and provider checks, so every call that works today still uses the same cookies. I confirmed this by moving the branch ahead of detection: two of the new tests fail.
- Isolation holds. Each call gets its own
AsyncLocalStoragescope, the concurrent signed-in and anonymous test proves it, and the client sends noCookieheader for a falsy store value (client/index.ts:388). I found no way for one request's cookies to reach another that isn't already there onmain. - It doesn't weaken a real gate. The removed
401only checked that some cookie string was present, never a valid session:withAuth(fn, 'x=1')already runsfnonmain. Protected methods keep their ownrequireAuth. - No regression of earlier decisions: the
withAuthbody is unchanged since the initial commit, there was no previous anonymous mode, the cookies-on-errors change (#850) is in the RPC dispatcher's response path, which this doesn't touch, and the client doesn't forwardSet-Cookieduring SSR. - The tests are well targeted: reverting the fix fails 4 of them, and making only
''anonymous fails 2.
What needs work: 1 blocking · 1 should-fix · 1 nit. Details are inline.
Open questions
- Is a patch changeset right for a behavior change you flag yourself for maintainer review (a callback that does private work without calling a session-checking method now runs signed out)? Or should anonymous be opt-in, which also resolves the blocking item?
- Should Next.js users on the zero-argument form (built-in detection) get the anonymous path too, or is
withAuth(fn, null)the intended spelling there? The Next.js provider returnsundefinedfor zero cookies, sowithAuth(fn)still throws for every signed-out visitor.
Cross-cutting
- Pages that used to fail for signed-out visitors now render with a
200. The SSR cache rule (never edge-cache responses for credentialed or cookie-setting requests) still applies because the request had no cookies, but anonymous HTML that used to be an error may now be edge-cached. That's the intended result for public pages, and worth a line in the changeset. - The open docs PRs (#1498, #1509) edit the same
withAuthREADME section, so expect a merge conflict on the note atpackages/core/README.md:584.
Replace the value-based anonymous path with an opt-in third argument, { allowAnonymous: true }. Without it, withAuth throws the 401 for every cookies value, as before. With it, a missing, null, empty or blank cookies argument runs fn with an empty request cookie store when the context and providers find none, so Node-style headers and Next.js detection work too. Export WithAuthOptions.
|
Replies to the review summary:
|
osama-rizk
left a comment
There was a problem hiding this comment.
Since the last review: 3 resolved · 0 new · 0 still open
- Resolved: anonymous mode is now an explicit
{ allowAnonymous: true }opt-in, so it works fornull,undefined,''and blank values, including Nodereq.headers.cookieand Next.js zero-argument detection. - Resolved: a unit test now drives a real
ApiNamespaceClientcall withfetchstubbed (and a signed-in control), and the newwith-auth-anonymouse2e suite exercises the public and gated paths. - Resolved: the anonymous tests assert
captured === ''exactly.
Approving. The option is opt-in, and without it withAuth matches main.
What I verified on 3d12f795:
- Without the option, the code path is the same as on
main: the new branch only adds code after provider detection, before the throw.null,undefined,''and blank values still throw401. - With the option, the resolution order is unchanged: explicit cookies, then an existing context, then providers win before the anonymous fallback.
- The option doesn't leak through nesting. A strict
withAuthinside an anonymous one still throws401, explicit inner cookies still win, andallowAnonymous: falsestays strict. - The unit tests pass (34/34 on Node 22), and the mutations I tried all fail them:
- replacing
store.run('', fn)withfn()fails 6 tests; - ignoring the option fails 7;
- making it on by default fails 6;
- moving the fallback ahead of providers or the existing context fails 1 and 2.
- replacing
- In this head's Local E2E log,
ping()answers{ ok: true }andwhoAmI()reaches the server and is refused byrequireAuthwithNotAuthenticated. So the e2e suite really goes through the server path. - The changeset (minor for
coreandblocks, plus the newWithAuthOptionsexport) and the edge-caching note match the change.
No follow-ups from my side. The expected README rebase against the other withAuth note PRs is fine as you described.
Problem
withAuth(fn, cookies)treats an explicitnullor emptycookiesargument the same as an omitted one: when neither an existing request context nor a cookie provider yields cookies, it throws a401ApiError("No authentication cookies found ... or pass cookies explicitly as the second argument").In a framework without a built-in provider, the documented call is:
Headers.get('cookie')returnsnullfor a visitor who has no cookies yet, so this call throws401for every anonymous visitor, even whenlistPostsis a public method. Any page that calls a public API method while rendering on the server fails for signed-out users, and with streaming rendering the failure arrives after the response has already started.Minimal reproduction (no provider yields cookies):
Issue #, if available:
Changes
packages/core/src/server/withAuth.ts:withAuth(fn, cookies?, options?)gets a third argument,WithAuthOptions({ allowAnonymous?: boolean }, defaultfalse). The resolution order is unchanged: non-empty explicit cookies, then an existing request context, then the registered providers (Next.js and Nuxt built in). When none of these yields cookies:allowAnonymous: throws the401as before, for everycookiesvalue (omitted,undefined,null,'', blank). The error message now also names the option.allowAnonymous: true: runsfninside the request cookie store with an empty value, so the client attaches noCookieheader, like a signed-out browser call. Public methods work, and a method gated withauth.requireAuthanswers its own401. The API dispatcher already runs handlers with an empty store value for requests without cookies, so this is an existing state of the store, and each call has its ownAsyncLocalStoragescope.cookies, it works for every header API: Fetchheaders.get('cookie')(null), Nodereq.headers.cookie, Express, Hono and h3 (undefined), and Next.js zero-arg detection (withAuth(fn, undefined, { allowAnonymous: true })).WithAuthOptionsis exported from@aws-blocks/core/serverand@aws-blocks/blocks/server. The API reports do not cover the./serverentry point, so they are unchanged.withAuthnote in the core README describe the option.minorfor@aws-blocks/coreand@aws-blocks/blocks(additive public option). It notes that pages using the option, which used to answer an error for signed-out visitors, now render with a200, and their anonymous HTML can be edge-cached.Behavior change
None without the option. A caller that relies on the
401as a sign-in gate keeps it. Only callers that pass{ allowAnonymous: true }runfnsigned out.Validation
packages/core/src/server/withAuth.test.ts:undefined(Node headers),null,''and a blank string throw401without runningfn(mainbehavior);fnwith the cookie store set to exactly'';undefined(as Next.js does for a visitor without cookies) runsfnsigned out;withAuth(fn, null, { allowAnonymous: true }), withfetchstubbed, sends noCookieheader (with a signed-in control call).test-apps/comprehensive/test/with-auth-anonymous.test.ts: insidewithAuth(..., null, { allowAnonymous: true }),protectedApi.ping()answers{ ok: true }andprotectedApi.whoAmI()answers401 NotAuthenticated; without the option,withAuth(fn, null)throws401without callingfn.4444a6058,3d12f7954):npm run buildandnpm run lint:deps: passnpm run check:api: pass. The API reports do not change, because they do not cover the./serverentry point.packages/corenpm test: pass (2,986 tests, 0 failures, 1 skipped). With the option branch disabled, 7 of the new tests fail.test-apps/comprehensivenpm run test:e2e:local: pass (531 tests, 0 failures, 6 skipped), including the 3 newwithAuthcasesChecklist
By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.