# Fail closed or fail open

Fail closed when the code's job is to refuse: signature checks, authentication, anything destructive. Fail open when the code only observes a request that belongs to someone else. In one week I fixed a storefront whose webhook handlers accepted unsigned requests for 200 days, and shipped a crawler logger that does nothing when its configuration is missing. Both guards had the same shape. What the code is for decided the verdict.

Published: 2026-11-25
Canonical: https://umar.codes/fail-closed-or-fail-open

## Revisions

- 2026-11-25 — Created from the storefront repository's webhook commits of 2026-01-16 to 2026-08-04 and a run of its six verification tests that day (6 of 6 passing), this site's logger and drain code and specs, and a probe of both under missing configuration and failed writes.
- 2026-11-25 — Published on its Nov 25 slot; auto-drafted by the publishing run because no draft existed for the row.

---

Fail closed when the code's job is to refuse: authentication, signature
checks, anything destructive. Fail open when the code only observes a request
that belongs to someone else. In one week I fixed a storefront that accepted
unsigned webhooks for 200 days, and shipped a crawler logger that deliberately
does nothing when its configuration is missing.

## Two guards with the same shape and opposite verdicts

Here are two guards I had on my screen in the last week of July 2026. The
first is from a storefront's webhook handler, lightly trimmed:

```ts
if (webhookSecret && hmac) {
  const isValid = await verifyShopifyWebhook(rawBody, hmac, webhookSecret);
  if (!isValid) return data({error: 'Invalid signature'}, {status: 401});
}
// ...process the order
```

The second is from this site's crawler logger:

```ts
if (!url || !token) return;
// ...write the log entry
```

Both say the same thing: if the configuration is not there, skip the step and
carry on. I removed the first one as a security bug on 2026-07-31. I had
written the second one on purpose two days earlier, on 2026-07-29, and it is
still in production. Neither call was a matter of taste. The first guard
skipped the only thing that handler existed to do before it acted. The second
skipped an optional extra on a request that was never about logging.

## A webhook handler that skipped verification when the header was missing

The storefront is a production Shopify build with an agent checkout
integration: an AI agent can build a cart and check out, and the storefront
tells the agent what happened to the order afterwards. It learns that from
three Shopify webhooks: orders, fulfilments and refunds. All three routes
arrived in one commit on 2026-01-16, and all three carried the guard above.

Read the condition again. Verification runs only when the secret is
configured *and* the request carries an HMAC header. A request with no header
is not rejected. It is not checked at all. So the bypass did not need a
misconfigured environment: anyone who could reach the URL could post a JSON
body, leave the signature header off, and be processed as Shopify. The
environment type agreed with the code, and still does. It declares the secret
as an optional string, so a deploy with no secret would type-check and start, and
would then accept everything.

What "processed" means is the part that matters. The orders handler marks a
checkout session complete, creates an order record, and sends the agent an
`order.confirmed` notification signed with the storefront's own private key.
The refunds handler marks an order refunded and reports a refund amount that
it adds up from the request body. A forged request did not only write a bad
row. It made the storefront vouch, under its own signature, for an order or a
refund that Shopify never sent.

The guard was on the main branch for 200 days, from the commit of 2026-01-16
to the merge of 2026-08-04. I have no evidence that anyone used it, and the
repository cannot tell me either way. The fix was 5 files, 139 lines added and
38 removed. It replaced the three copies of the guard with one function:

```ts
export async function verifyShopifyWebhookRequest(
  rawBody: string,
  hmac: string | null,
  secret: string | undefined,
): Promise<ShopifyWebhookVerification> {
  if (!secret) return {ok: false, reason: 'missing-secret'};
  if (!hmac) return {ok: false, reason: 'missing-hmac'};
  const isValid = await verifyShopifyWebhook(rawBody, hmac, secret);
  return isValid ? {ok: true} : {ok: false, reason: 'invalid-signature'};
}
```

Six tests pin it: one accepted request, and five rejections (no secret, an
empty-string secret, no header, a signature from the wrong secret, a signature
for a different body). I ran them again on 2026-11-25: 6 of 6 pass. A second
commit, 52 minutes after the first, replaced `computed === signature` with a
constant-time comparison. The same file already had a constant-time loop for
the signatures the storefront sends out. The check on what came in had the
weaker comparison.

## A crawler logger that does nothing when its configuration is missing

This site is static. The one piece of code that runs on a request is a
[middleware that logs AI-crawler hits](/logging-ai-crawlers) to a Redis list.
Its spec has a line I wrote before any code: adding middleware to a fully
static site creates a new failure surface, so the middleware must fail open.
The shorter version is in the post about it: an observability feature must
never become an availability bug.

So the logger is built to lose. No Redis credentials: return. The write
throws: a `catch` swallows it. The whole handler sits in a `try` with an empty
`catch`, and the function always returns `undefined`, which tells the platform
to serve the page. I checked that with a probe on 2026-11-25, calling the
handler directly with a stubbed `fetch`:

| Case | Handler returned | Threw | Redis calls |
| --- | --- | --- | --- |
| Credentials present, write succeeds | `undefined` | no | 1 |
| Credentials missing | `undefined` | no | 0 |
| Network error on the write | `undefined` | no | 1 |
| Redis answers 500 | `undefined` | no | 1 |
| Human user agent | `undefined` | no | 0 |
| Malformed request object | `undefined` | no | 0 |

Six cases, six pages served, zero unhandled rejections. In three of them a log
line is lost and nobody is told. That is the design. The reader asked for an
essay; the crawler asked for a page. Neither of them asked to be logged, and
neither should get a 500 because my Redis token expired.

## The deciding question is what the code is for

"Is this security code?" is the wrong test. It gets the logger right and then
fails on the next case. The test that held up in both codebases is this: when
this code cannot do its job, who was depending on the job being done?

A signature check has one job, and the job is to say no. The caller of the
handler behind it is depending on that "no" as a precondition. If the check
cannot run, because the secret is missing or the header is absent, then the
precondition is not met, and proceeding is not a degraded mode. It is the
exact outcome the check exists to prevent. Absence of evidence has to count
as a failed check. That is fail closed.

A logger rides along on a request that belongs to someone else. Nobody
downstream of the response depends on the log line. If the logger cannot do
its job, the correct behaviour is to get out of the way, because the request's
owner is owed the page and is owed nothing else. That is fail open.

Put as a rule: a gate fails closed, a passenger fails open. The guard
`if (secret && hmac)` is a passenger's guard written into a gate.

## One system needs both: the destructive endpoint fails closed

The rule is per function, not per project. Eleven days after the logger
shipped I added a daily cron that drains the Redis
list into object storage. Draining pops records off the list, so it is
destructive, and the endpoint is a public URL. The same system that fails open
on every page request fails closed here:

```ts
const secret = process.env.CRON_SECRET;
if (!secret || request.headers.get("authorization") !== `Bearer ${secret}`) {
  return new Response("Unauthorized", { status: 401 });
}
```

The `!secret` is the whole point. Without it, an unset secret compares the
header against the string `Bearer undefined`, and anyone who sends that string
is in. The probe covers it: no secret and no header, no secret with
`Bearer undefined`, an empty secret with `Bearer `, a secret with no header,
and a secret with the wrong header. Five cases, five 401s, and zero Redis
calls in any of them.

## Each choice has a cost, and the cost has to be visible

Neither direction is free, and both fail quietly unless I make them loud.

Fail open costs data. Every lost write is a crawler hit missing from a dataset
I publish numbers from: 7,550 records in the export that
[the IP-verification post](/verify-ai-crawlers-by-ip) used. A logger that
drops lines in silence makes every count a lower bound of unknown slack. So
the middleware also prints one line per hit to the platform's own log, which
is separate infrastructure from Redis. The two counts can be compared, and the
loss rate becomes a number instead of a hope. Fail open is only honest if the
failures are counted somewhere else.

Fail closed costs availability, and the bill arrives from the other side.
Shopify treats any response outside the 200 range as a failed delivery. It
[retries 8 times over 4 hours](https://shopify.dev/docs/apps/build/webhooks/troubleshooting-webhooks),
and after 8 consecutive failures it deletes a subscription that was created
through the Admin API. So after the fix, a deploy that loses its webhook
secret does not process forged orders. It rejects every real one, and within
hours it can stop receiving them at all. That is the correct trade, in the
same way that [a 503 is the correct answer](/503-not-404) when an upstream
read fails. But it is why the new function returns a reason and the handler
logs it. `missing-secret` in the logs is a deploy problem. `invalid-signature`
is an attacker or a rotated key. The old code logged one message for a bad
signature and nothing for the two cases it let through.

## Test the missing-configuration case, because that is where the default hides

Both bugs I could have shipped live in the same place: the branch that runs
when configuration is absent. Nobody writes that branch on purpose. It falls
out of an `if`, and it is the one environment the happy-path test never
builds.

So I now write that test first, for anything that reads a secret. Pass
`undefined`. Pass the empty string, which is what an unset variable often
becomes. Leave the header off. Then read the result and ask which way it
fell. The answer itself is not what I check. I check that somebody chose it.
The storefront's guard was 200 days old when I found it, and I do not think
anyone ever decided that unsigned webhooks should be accepted. The code
decided, and for 200 days nothing asked it.
