API authorization from the verified identity (and the holes it closes)
authorizationjwtidorprivacynotificationstokensaudit
The single most common security bug found in the TLDR API was the same pattern everywhere: a
route decided who you are from a username field in the request body or query string instead
of from the verified token. Fixing it route by route closed admin takeover, edit-anyone, and a
dozen IDORs. This article is the checklist that came out of a five-agent audit (v1.31.0, July
2026) and later bug hunts.
The rule
Authentication middleware verifies the JWT and puts the identity on the request
(authorized_username, authorized_role). Every authorization decision reads those attributes:
$me = $request->getAttribute('authorized_username') ?? '';
$role = $request->getAttribute('authorized_role', 'user');
A username in the body is only legitimate where it is the credential (login, register) or the
target of an action that is separately authorized (an admin acting on another user).
Holes this pattern produced (all real, all fixed)
- An admin "rollback" endpoint that swapped the production web symlink checked
isSuperUser($body['username']): any logged-in user could redeploy prod. - Edit post, edit/delete response had no ownership check at all. Now author or superuser, and a non-admin cannot reassign the author field.
- IDORs on notifications, drafts, polls, votes, reactions, flags, bookmarks, reminders, tag admin,
post metadata: each now adds
AND username = ?(JWT user) or an author-or-admin helper. - Path traversal in legacy file routes (
$dir . $namewith a raw name): reject/ \ .., thenbasename(). - UI-only gates are not gates. An audit of the AI feature found controls hidden in the app
(timeouts, forward-to-AI, a whole
/airoute) with no server check, a preferences endpoint with no key allowlist (users could self-grantai_danger_access), and a cancel endpoint with no ownership check. See Securing a shared AI agent that other users can drive.
Privacy belongs in the query, not in a response filter
When private posts leaked through a detail endpoint, a "response middleware that strips private
posts from all JSON" was proposed and rejected: it pattern-matches JSON shapes, sits at the wrong
layer, hides behavior, and cannot tell contexts apart. Instead each query carries the rule, e.g.
AND (p.privacy = 'public' OR p.username = :me), and detail endpoints 404 (not 403) on private
posts the caller cannot see. 404 avoids confirming that the id exists.
Every side channel needs the same check
Notifications and pushes that link to a post leaked private titles: a scheduled-post cron
notified all followers regardless of privacy, fork notifications told the source author about a
private fork, and reply @mentions never checked visibility. One inbox had 65 entries of which 61
could not be opened. The fix pattern:
- A single helper canView($postId, $user, $role), the code twin of the SQL visibility clause, plus
the admin bypass; deleted or missing posts return false.
- Call it before creating any notification or push that references a post.
- Also filter on read (GET /notifications joins the linked post and drops what the caller cannot
view), which hides historical bad rows without a risky delete.
Admin does not mean "sees everything" (posts #1882, #1883)
- Every read path needs the same visibility gate. On TLDR,
GET /posts/{id}/versionshad only the auth middleware, so any logged-in user could read the old titles and bodies of any post, private ones included; two response endpoints had no check at all. The app never called them, which is why nobody noticed. The fix calls one sharedcanView(post, user, role)before returning anything and answers 404. Audit for routes that check "logged in" but not "may read this object", especially ones your own client never uses. - Admins should not read other users' private content by default. The exceptions are content addressed to the admin by nature (bug and feature tracker posts, threads run on the admin's own AI). Keep that rule in one place (a list of admin-visible types plus a SQL clause builder) and use it on every read path: feed, single item, profile, responses, history.
- Impersonation must not widen access. When an admin views "as user X", show only what both may read.
- This is policy, not cryptography: the data is still plaintext in the database, and anyone with database access can read it. Say so when promising privacy. When the reason for an exception changes (for example, threads that run on a user's own agent), the exception must change too.
Tokens and secrets
- Security tokens (reset, verify, share links) come from a CSPRNG:
bin2hex(random_bytes(32)). The olduuid()built onmt_randis fine for ids, not for secrets. - Compare secrets with
hash_equals(constant time). - Validate before consuming. A reset-confirm route deleted the token before checking it, so a
bad request burned a good token. Order: look up, check expiry and
hash_equals, act, then delete. - A legacy page echoed the reset token into HTML. Never render a secret you only need to mail.
- Reset tokens should be keyed per user (primary key on username, upsert), or multiple requests stack tokens and an unordered SELECT returns the wrong one.
- JWTs are stateless: changing a password does not revoke tokens already issued on other devices. If that matters, add a per-user token version claim.
Where the token lives (no cookies)
TLDR keeps users signed in with a JWT rather than a cookie (post #1829):
- Stored with
shared_preferences(localStorage on web, private SharedPreferences on Android) and sent as-is in theAuthorizationheader, with noBearerprefix. - Tokens last 30 days. Any 401 signs that device out but keeps the DM key material; logout deletes the token locally even if the API call fails.
- Tradeoffs: CSRF is impossible because the browser never attaches the token on its own. But any script on the page can read localStorage, so an XSS bug can steal the token, which an
HttpOnlycookie would prevent. With no server-side deny-list, a stolen token works until it expires.
Gotchas
- Pin the JWT algorithm (HS256) and let the library enforce
exp; re-check that the account is still active on each request. - The client should only treat 401 as "logged out" for requests that sent a token, or a failed login attempt wipes local state.
- A client that calls an authenticated route without the token gets a 401 it may swallow, falling back to a stale default (an upload limit stuck at 2 MB for months). Grep server access logs for 401s from your app's user agent. See Debugging client-side bugs from the server's access log.
See also
- Migrating legacy password hashes to bcrypt on login
- Slim 4 PHP APIs (and migrating from Limonade)
- "Anyone with the link" share links (capability URLs)
Linked from
- "Anyone with the link" share links (capability URLs)
- Accepting and serving user uploads safely from a private bucket
- Changing a production MariaDB safely (schema, data fixes, id generation)
- Debugging client-side bugs from the server's access log
- Email sign-in links (one-time "magic links")
- FCM push notifications from a PHP backend to a Flutter app
- Migrating legacy password hashes to bcrypt on login
- Release-directory deploys with an atomic symlink swap
- Securing a shared AI agent that other users can drive
- Server-minted claim codes for in-game rewards (never ship the secret)
- Slim 4 PHP APIs (and migrating from Limonade)
- TLDR platform architecture (tldrnerd.com)