Skip to content

feat(core): let withAuth run signed out with allowAnonymous - #1519

Merged
xyos merged 3 commits into
aws:mainfrom
xyos:fix/core-with-auth-no-cookies
Nov 16, 2026
Merged

xyos merged 3 commits into
aws:mainfrom
xyos:fix/core-with-auth-no-cookies

Conversation

@xyos

@xyos xyos commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Problem

withAuth(fn, cookies) treats an explicit null or empty cookies argument the same as an omitted one: when neither an existing request context nor a cookie provider yields cookies, it throws a 401 ApiError ("No authentication cookies found ... or pass cookies explicitly as the second argument").

In a framework without a built-in provider, the documented call is:

await withAuth(() => api.listPosts(), request.headers.get('cookie'));

Headers.get('cookie') returns null for a visitor who has no cookies yet, so this call throws 401 for every anonymous visitor, even when listPosts is 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):

import { withAuth, clearCookieProviders } from '@aws-blocks/core/server';

clearCookieProviders();
await withAuth(async () => 'public', null); // throws ApiError 401, callback never runs

Issue #, if available:

Changes

  • packages/core/src/server/withAuth.ts: withAuth(fn, cookies?, options?) gets a third argument, WithAuthOptions ({ allowAnonymous?: boolean }, default false). 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:
    • without allowAnonymous: throws the 401 as before, for every cookies value (omitted, undefined, null, '', blank). The error message now also names the option.
    • with allowAnonymous: true: runs fn inside the request cookie store with an empty value, so the client attaches no Cookie header, like a signed-out browser call. Public methods work, and a method gated with auth.requireAuth answers its own 401. 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 own AsyncLocalStorage scope.
  • Because the option does not depend on the value of cookies, it works for every header API: Fetch headers.get('cookie') (null), Node req.headers.cookie, Express, Hono and h3 (undefined), and Next.js zero-arg detection (withAuth(fn, undefined, { allowAnonymous: true })).
  • WithAuthOptions is exported from @aws-blocks/core/server and @aws-blocks/blocks/server. The API reports do not cover the ./server entry point, so they are unchanged.
  • JSDoc (with examples) and the withAuth note in the core README describe the option.
  • Changeset: minor for @aws-blocks/core and @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 a 200, and their anonymous HTML can be edge-cached.

Behavior change

None without the option. A caller that relies on the 401 as a sign-in gate keeps it. Only callers that pass { allowAnonymous: true } run fn signed out.

Validation

  • Unit tests in packages/core/src/server/withAuth.test.ts:
    • without the option, undefined (Node headers), null, '' and a blank string throw 401 without running fn (main behavior);
    • with the option, the same four values run fn with the cookie store set to exactly '';
    • with the option, a provider that returns undefined (as Next.js does for a visitor without cookies) runs fn signed out;
    • with the option, explicit cookies, an existing context, and provider cookies still win;
    • concurrent signed-in and anonymous calls stay isolated;
    • a real client method called inside withAuth(fn, null, { allowAnonymous: true }), with fetch stubbed, sends no Cookie header (with a signed-in control call).
  • E2E in test-apps/comprehensive/test/with-auth-anonymous.test.ts: inside withAuth(..., null, { allowAnonymous: true }), protectedApi.ping() answers { ok: true } and protectedApi.whoAmI() answers 401 NotAuthenticated; without the option, withAuth(fn, null) throws 401 without calling fn.
  • Run locally on the new commits (4444a6058, 3d12f7954):
    • npm run build and npm run lint:deps: pass
    • npm run check:api: pass. The API reports do not change, because they do not cover the ./server entry point.
    • packages/core npm test: pass (2,986 tests, 0 failures, 1 skipped). With the option branch disabled, 7 of the new tests fail.
    • test-apps/comprehensive npm run test:e2e:local: pass (531 tests, 0 failures, 6 skipped), including the 3 new withAuth cases

Checklist

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

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

…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-bot

changeset-bot Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 3d12f79

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 26 packages
Name Type
@aws-blocks/core Minor
@aws-blocks/blocks Minor
@aws-blocks/bb-logger Patch
@aws-blocks/bb-kv-store Patch
@aws-blocks/bb-distributed-table Patch
@aws-blocks/auth-common Patch
@aws-blocks/bb-app-setting Patch
@aws-blocks/bb-secret Patch
@aws-blocks/bb-data Patch
@aws-blocks/bb-distributed-data Patch
@aws-blocks/bb-database Patch
@aws-blocks/bb-auth Patch
@aws-blocks/bb-realtime Patch
@aws-blocks/bb-async-job Patch
@aws-blocks/bb-dashboard Patch
@aws-blocks/bb-cron-job Patch
@aws-blocks/bb-file-bucket Patch
@aws-blocks/bb-agent Patch
@aws-blocks/bb-knowledge-base Patch
@aws-blocks/bb-email-client Patch
@aws-blocks/bb-tracer Patch
@aws-blocks/bb-metrics Patch
@aws-blocks/bb-lambda-compute Patch
@aws-blocks/bb-container-compute Patch
@aws-blocks/bb-compute Patch
@aws-blocks/create-blocks-app Minor

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

@xyos
xyos marked this pull request as ready for review November 16, 2026 11:29
@xyos
xyos requested a review from a team as a code owner November 16, 2026 11:29

@osama-rizk osama-rizk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 AsyncLocalStorage scope, the concurrent signed-in and anonymous test proves it, and the client sends no Cookie header 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 on main.
  • It doesn't weaken a real gate. The removed 401 only checked that some cookie string was present, never a valid session: withAuth(fn, 'x=1') already runs fn on main. Protected methods keep their own requireAuth.
  • No regression of earlier decisions: the withAuth body 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 forward Set-Cookie during 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

  1. 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?
  2. 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 returns undefined for zero cookies, so withAuth(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 withAuth README section, so expect a merge conflict on the note at packages/core/README.md:584.

Comment thread packages/core/src/server/withAuth.ts Resolved
xyos added 2 commits November 16, 2026 13:09
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.
@xyos xyos changed the title fix(core): run withAuth callback without cookies when cookies is explicitly null or empty feat(core): let withAuth run signed out with allowAnonymous Nov 16, 2026
@xyos

xyos commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Replies to the review summary:

@xyos
xyos requested a review from osama-rizk November 16, 2026 13:25

@osama-rizk osama-rizk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 for null, undefined, '' and blank values, including Node req.headers.cookie and Next.js zero-argument detection.
  • Resolved: a unit test now drives a real ApiNamespaceClient call with fetch stubbed (and a signed-in control), and the new with-auth-anonymous e2e 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 throw 401.
  • 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 withAuth inside an anonymous one still throws 401, explicit inner cookies still win, and allowAnonymous: false stays strict.
  • The unit tests pass (34/34 on Node 22), and the mutations I tried all fail them:
    • replacing store.run('', fn) with fn() 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.
  • In this head's Local E2E log, ping() answers { ok: true } and whoAmI() reaches the server and is refused by requireAuth with NotAuthenticated. So the e2e suite really goes through the server path.
  • The changeset (minor for core and blocks, plus the new WithAuthOptions export) 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.

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.

2 participants