Skip to content

KotaPortal's Silent E2E Cleanup Leak and the 401 Nobody Read

Adityo Guni Waluyo

A cleanup sweep that ran in full still leaked: every request came back 401, fetch never rejected, and six demo entities stayed behind.

TL;DR

KotaPortal's E2E cleanup sweep silently failed because every DELETE got a 401, yet the hook passed since fetch resolves normally on non-2xx statuses. Playwright's storageState only saves cookies and LocalStorage, not Authorization headers, so requests went out unauthenticated. The fix: extract the token from state, attach it as a Bearer header, and fail hard when any response isn't okay.

The moment that gets misread as an SQL failure

The zero-check after the E2E suite runs on KotaPortal should return 0 / 0 / 0 / 0. What came out was different: six demo entities still hanging in the database. In the E2E Parity Doc, five or six rows marking the cleanup queue stayed red and never moved no matter how many times the suite was rerun.

My first guess was wrong. I suspected the cleanup hook ran out of time, like an old case I wrote about in the article on afterAll as a safety net: there the test really did touch the limit, the hook never got to run, and data leaked. The second alternative I suspected was that the delete query failed mid-loop because of the database connection. Both were wrong.

I turned on per-request logging on the sweep, then reran. The DELETE loop ran to the last row. Every request was sent, every request got a reply. What came back was status 401 for all six entities, and the cleanup code still closed the hook without an error. The sweep ran in full, only all its requests were rejected.

401 is a normal response, and fetch never rejects it

At that point I briefly blamed the server, assuming the Go API was "swallowing" something. That was wrong too. According to the HTTP specification, status 401 means the request was not applied because no valid credentials were included [1]. The MDN documentation spells out the same thing: the request failed because it lacked authentication credentials [2]. The KotaPortal server was being honest; it asked "who are you?" six times.

The silence has two layers. First layer, 401 is a valid HTTP response, not an exception, so nothing "explodes". Second layer, and the decisive one: fetch() only throws for network failures. Any HTTP status, including 401 or 500, still resolves the promise with a normal Response object [3]. A caller that never checks the status property on that object sees a failed request and a successful request as identical.

The cleanup loop checked nothing. Every response was thrown away immediately. That combination is what made the leak silent: the server rejects, the client does not listen, the database stays full.

The time budget context exists, but it is not the culprit. The beforeAll and afterAll hooks have their own timeout sized to follow the test timeout, shared with no test [4]; in the KotaPortal configuration the number is 120 seconds. The sweep finished well under that limit. The difference from the old article: there the hook never ran, here the hook ran in full and every one of its requests was rejected. The two articles complement each other, they do not overwrite each other.

The token has to be pulled from storageState yourself

The root cause sits in how credentials are carried. Playwright stores the login session through storageState, but the file only contains cookies and LocalStorage. Authorization headers are not recorded, so requests built on storageState still go out without an Authorization header. For a Bearer API like KotaPortal's, the token has to be extracted from the state manually.

This is the old leaking version, with paths and repo names already generalized:

// e2e/hooks/cleanup.ts — old version (leaky)
test.afterAll(async ({ request }) => {
  const ids = readDemoIdsFromState();
  for (const id of ids) {
    await request.delete(`/api/demo/entities/${id}`);
  }
});

The fix has two parts: fetch the token through the adminTokenFromState helper, then treat the sweep response as data that must be checked.

// e2e/hooks/cleanup.ts — version that carries credentials
test.afterAll(async ({ request }) => {
  const adminJwt = adminTokenFromState();
  const ids = readDemoIdsFromState();
  const failed = [];

  for (const id of ids) {
    const res = await request.delete(`/api/demo/entities/${id}`, {
      headers: { Authorization: `Bearer ${adminJwt}` },
    });
    if (!res.ok()) failed.push(`${id} -> ${res.status()}`);
  }

  if (failed.length > 0) {
    throw new Error(`sweep gagal untuk ${failed.length} entitas: ${failed.join(', ')}`);
  }
});

Rerun the suite after the patch, then prove it with the zero-check on the database. The query counting remaining demo entities must return 0 / 0 / 0 / 0; any non-zero number means the sweep is still leaving something behind. On KotaPortal, the rerun after the fix did produce zeros in all four columns.

The last line of defense is the principle, not the code: sweep responses are not noise. A "best-effort cleanup" pattern that never checks status is a ticking bomb; it always passes until one day the leak is too big to ignore. Request configuration slowly drifts, a token can expire mid-run, an account's permissions can be narrowed. The only way to catch those changes is to make the sweep fail hard when the server rejects it.

One nuance I missed when I first read the code: Playwright's APIRequestContext also does not throw on non-2xx status. The failOnStatusCode option is opt-in. Moving the sweep from fetch() to Playwright's built-in API helper therefore solves nothing as long as the status check is still absent.

Sources

[1] RFC 9110, HTTP Semantics — status 401 Unauthorized: rfc-editor.org

[2] MDN Web Docs — 401 Unauthorized: developer.mozilla.org

[3] MDN Web Docs — Window.fetch(): developer.mozilla.org

[4] Playwright — Timeouts: playwright.dev

Related articles

E2E Cleanup Leak: 401 Responses fetch() Never Rejects · Adityo GW