feat(backend): add an application-layer gate to the admin API (#63)

Authorization for the admin panel and the admin API has lived entirely in one auth_request regex in an Nginx Proxy Manager config outside this repository. That control is real and it works — nothing is publicly exposed today — but it is invisible from the code, untested here, and not reviewed when this code changes. Three things follow from that, and the first is the one worth the change.

An admin route added at a path the regex does not match is unprotected the moment it is written, and nothing in Express indicates that. Anything reaching the published container port directly bypasses authentik entirely. And locally there is no gate at all, so no developer ever sees the boundary being enforced.

requireAdminGate is attached to each admin router rather than to a path prefix, which is what makes it useful rather than merely redundant with the proxy. An admin router added later at some other path inherits the gate; because the proxy only injects the header on paths its regex matches, that router refuses on its first request instead of being quietly public. A 403 in that situation is the boundary reporting that it has drifted.

The gate is optional, and unset means exactly today's behaviour. That keeps local development and all 113 existing admin test call sites working untouched, and means shipping the image before configuring the proxy cannot take the admin panel down. What it does not do is stay silent about it: the server warns at boot when the gate is inactive, naming what is unprotected. This project has been bitten repeatedly by controls that report success while doing nothing, and an unconfigured gate should be a visible choice rather than an invisible one.

An empty value is treated as unset rather than as a secret, because enforcing an empty secret would admit any caller sending an empty header. Comparison is timing-safe over SHA-256 digests of both sides: timingSafeEqual throws on buffers of unequal length, so comparing raw values would turn a short header into a 500 rather than a 403, and a length check first would leak the secret's length.

Turning it on requires the secret in two places at once — the stack environment and a proxy_set_header line on the gated location in NPM. Setting only one gives 403s until the other catches up. That coupling, and the three consequences above, are now written into the README beside the deployment section, since none of it is visible from the code.

Verified over real HTTP as well as in tests. Booting without the secret logs the warning and serves admin normally; booting with it returns 403 for a missing header, 403 for a wrong one, 200 for the right one, and leaves the public storefront at 200 throughout, with each refusal logged distinguishably and without echoing the value it was sent. 8 new unit tests, 9 new integration tests covering every admin router separately — a correct middleware nobody mounted would pass the unit tests and protect nothing. 106 unit and 153 integration passing, lint 0 errors and 8 warnings unchanged.

Refs #63
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-21 13:44:15 -05:00
parent 105bf141f5
commit 89fc7c5c1b
6 changed files with 340 additions and 5 deletions
+11 -5
View File
@@ -15,6 +15,7 @@ import cartRouter from './routes/cart';
import shippingAddressesRouter from './routes/shippingAddresses';
import clientErrorsRouter from './routes/clientErrors';
import { attachCustomer } from './middleware/customerAuth';
import { requireAdminGate } from './middleware/adminGate';
import { asyncRoute } from './asyncRoute';
const app = express();
@@ -46,11 +47,16 @@ app.use('/api/items', itemsRouter);
app.use('/api/filters', filtersRouter);
app.use('/api/cart', cartRouter);
app.use('/api/checkout/cart', cartCheckoutRouter);
app.use('/api/admin/customers', adminCustomersRouter);
app.use('/api/admin/settings', adminSettingsRouter);
app.use('/api/admin/categories', adminCategoriesRouter);
app.use('/api/admin/tags', adminTagsRouter);
app.use('/api/admin', adminRouter);
// requireAdminGate is attached to each admin router rather than to a path
// prefix. Attached to the router, an admin router added later at some other
// path still inherits it — and since the proxy only injects the header on the
// paths its regex matches, that router refuses loudly on its first request
// instead of being quietly public. See middleware/adminGate.ts and #63.
app.use('/api/admin/customers', requireAdminGate, adminCustomersRouter);
app.use('/api/admin/settings', requireAdminGate, adminSettingsRouter);
app.use('/api/admin/categories', requireAdminGate, adminCategoriesRouter);
app.use('/api/admin/tags', requireAdminGate, adminTagsRouter);
app.use('/api/admin', requireAdminGate, adminRouter);
app.use('/api/customers/me/addresses', shippingAddressesRouter);
app.use('/api/customers', customersRouter);
app.use('/api/client-errors', clientErrorsRouter);
+61
View File
@@ -0,0 +1,61 @@
import { Request, Response, NextFunction } from 'express';
import crypto from 'crypto';
// The header Nginx Proxy Manager injects on the authentik-gated location. The
// name is not a secret and does not need to be — the value is.
export const ADMIN_GATE_HEADER = 'x-admin-gate';
// Hashed before comparing for two reasons. timingSafeEqual throws on buffers of
// unequal length, so comparing raw values would turn a short header into a 500
// instead of a 403; and a length check before comparing would leak the secret's
// length. Digests are always 32 bytes, so neither problem arises.
function digest(value: string): Buffer {
return crypto.createHash('sha256').update(value, 'utf8').digest();
}
/**
* Defence in depth for the admin API.
*
* Authorization for `/admin` and `/api/admin` lives entirely in one
* `auth_request` regex in an Nginx Proxy Manager config outside this
* repository. That control is real and it works, but it is invisible from the
* code, untested here, and bypassed completely by anything that reaches the
* published container port directly. See #63.
*
* With `ADMIN_GATE_SECRET` set, the proxy injects the matching header and this
* refuses anything that arrives without it.
*
* Unset — or empty, which cannot mean "enforce" without letting an empty header
* through — this is a no-op and the API is proxy-protected exactly as before.
* That keeps local development and the existing admin tests working untouched,
* and means shipping the image before configuring the proxy cannot take the
* admin panel down. `server.ts` warns at boot when it is inactive, so the
* inactive state is visible rather than silent.
*
* Mounted on the admin routers rather than on a path prefix, deliberately. An
* admin router added later at a path the proxy regex does not match will
* receive no header and refuse loudly on the first request, instead of being
* quietly public — which is the failure #63 was most concerned about.
*/
export function requireAdminGate(req: Request, res: Response, next: NextFunction): void {
const secret = process.env.ADMIN_GATE_SECRET;
if (!secret) {
next();
return;
}
const provided = req.get(ADMIN_GATE_HEADER);
if (typeof provided !== 'string' || !crypto.timingSafeEqual(digest(provided), digest(secret))) {
// Logged because a 403 from behind a proxy is otherwise very hard to
// diagnose — most often it means the proxy config and the stack's secret
// have drifted apart. The value sent is deliberately not echoed.
console.warn(
`[admin-gate] refused ${req.method} ${req.originalUrl}` +
`${provided === undefined ? 'no' : 'incorrect'} ${ADMIN_GATE_HEADER} header`
);
res.status(403).json({ error: 'forbidden' });
return;
}
next();
}
+13
View File
@@ -65,4 +65,17 @@ setInterval(() => void sweepExpiredCarts(), 5 * 60 * 1000);
cron.schedule('0 9 * * *', () => void sendCartReminders());
const PORT = parseInt(process.env.PORT || '3000', 10);
// Said at boot rather than left to be discovered. Without the secret the admin
// API is protected only by the reverse proxy's auth_request regex, which lives
// outside this repository and is bypassed entirely by anything reaching this
// container's published port directly. That is a defensible way to run — it is
// how this app has always run — but it should be a visible choice rather than a
// silent one. See middleware/adminGate.ts and #63.
if (!process.env.ADMIN_GATE_SECRET) {
console.warn(
'[admin-gate] ADMIN_GATE_SECRET is not set — /api/admin is protected only by the reverse ' +
'proxy. Anything able to reach this container directly can administer the store.'
);
}
app.listen(PORT, () => console.log(`redefined-designs listening on ${PORT}`));