Skip to content

Fix dataset list --mine auth header - #462

Merged
neuromechanist merged 3 commits into
devfrom
feature/issue-447-list-mine-auth
May 14, 2026
Merged

neuromechanist merged 3 commits into
devfrom
feature/issue-447-list-mine-auth

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Closes #447.

What changed

nemar dataset list --mine failed with Authentication required to view your datasets for users who were logged in (isAuthenticated() returned true). The CLI sent the Authorization: Bearer <key> header, but the backend's optionalAuthMiddleware silently dropped it whenever the key didn't resolve to an approved user (revoked, expired, rotated, or matching a different env's DB). The route then saw user=null and bounced the caller with the generic "Authentication required" reply — indistinguishable from "no header sent" so the user has no hint to re-login.

Fix:

  • optionalAuthMiddleware now sets c.set("authAttempted", true) whenever the caller provided a Bearer header (regardless of whether the lookup succeeded). The flag distinguishes "no header" from "header sent but unresolvable".
  • GET /datasets?mine=true reads authAttempted when user is null and emits a token-specific 401 directing the user to nemar auth login (or regenerate-key if the original key was revoked). The "no header" branch keeps the original message for callers that never logged in.
  • Added a Variables.authAttempted: boolean field to the Hono context typing.

Why this is the root cause, not a band-aid

The CLI's isAuthenticated() is presence-only — it can only verify a key was stored, not that the backend still accepts it. We could try to revalidate the key on every command, but that doubles requests for every authenticated call. The cheaper fix is to make the backend's reply unambiguous: presence of an unresolvable Bearer token is a known signal that the caller's session is stale.

Test plan

  • Added three new integration tests in test/api.test.ts under GET /datasets:
    • no auth header -> 401 generic "Authentication required"
    • invalid bearer (32+ chars, won't hash-match) -> 401 with "rejected" + "nemar auth login" hint
    • valid user token -> 200 with datasets array
  • bun run typecheck passes for backend
  • bun run build for CLI succeeds
  • Verify in CI against deployed backend that the new error message appears for stale tokens

@github-actions

github-actions Bot commented May 14, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR462

Version: 0.8.14-PR462.2f445c3
Commit: 2f445c3


🤖 Updated on each push.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

PR #462 Code Review

Summary: The fix correctly distinguishes "no header" from "bad token" at the backend, addresses the root cause, and the new error message propagates correctly to the CLI user via ApiError.message. The approach is sound. Issues below range from important to nice-to-have.


Critical

None.


Important

1. authAttempted type declared as boolean but reads as boolean | undefined at runtime
backend/src/types/bindings.ts:120 — authAttempted: boolean is not marked optional, implying c.get("authAttempted") always returns a boolean. But on any route that reaches optionalAuthMiddleware via a path where the middleware isn't in the chain, or before the middleware fires, it is undefined. Hono's c.get() returns T | undefined. The if (attempted) in datasets.ts:462 works because undefined is falsy, but the type declaration is a lie that will cause confusion for the next person. Fix: declare as authAttempted?: boolean (optional).

2. GET /datasets/:id silently returns 404 for stale-token owners of private datasets — same bug class, not fixed
backend/src/routes/datasets.ts:939-940 — A user with a stale token trying to access nemar dataset status nm000XXX (a private dataset they own) gets {"error":"Dataset not found"} — identical to a truly missing dataset. The fix in this PR only covers GET /datasets?mine=true. The GET /datasets/:id, GET /datasets/:id/manifest, and GET /datasets/:id/manifest/:version routes all use optionalAuthMiddleware and all silently degrade on bad tokens with no hint to re-login. The --mine case is the most common user-facing trigger, so this is not a blocker, but it is an inconsistency that will produce another issue ticket.

3. Malformed Authorization header (non-Bearer) leaves authAttempted unset (undefined, not false)
backend/src/middleware/auth.ts:158-162 — The diff adds c.set("authAttempted", false) inside if (!authHeader || !authHeader.startsWith("Bearer ")). That branch handles both "no header" and "non-Bearer header" (e.g., Authorization: Basic ..., or a lowercase bearer token). Setting authAttempted=false for a non-Bearer header is correct, but it's worth noting explicitly in the comment that a lowercase bearer is treated as "no auth attempted." The CLI always sends Bearer (capital B, line 98 of src/lib/api.ts), so this is not a practical bug, but a future alternate client or proxy that lowercases headers will silently fall through.


Suggestions

4. c.set("authAttempted", true) is placed before the DB lookup in the happy path — intentional but worth a note
backend/src/middleware/auth.ts:169-170 (new line in diff) — authAttempted is set to true before hashApiKey() and the DB query. If the DB call throws (not a normal path but possible in transient D1 failures), the flag is set but user is null, so the route emits "token rejected" to the caller. That's defensively correct but might confuse users experiencing a DB outage. A comment acknowledging this would help.

5. GET /datasets/search uses optionalAuthMiddleware but authAttempted is never read
backend/src/routes/datasets.ts:789 — The search route doesn't gate anything on auth, so this is fine. But now that authAttempted is a known Variables field, a reader might wonder if it's intentionally ignored here. A one-line comment // auth is optional for search; stale tokens silently degrade to public results would prevent confusion.

6. Test for invalid bearer should also verify the response does NOT contain the generic "Authentication required" string
test/api.test.ts (new test at line ~492) — The test asserts data.error contains "rejected" and "nemar auth login", which is good. Adding a negative assertion expect(data.error).not.toContain("Authentication required") would make the regression boundary explicit and prevent the two code paths from converging in a future edit.


Nice-to-haves

7. GET /notices in backend/src/index.ts:96 also uses optionalAuthMiddleware — consider consistency
backend/src/index.ts:96 — Notices don't require auth and there's no auth-gated behavior, so authAttempted doesn't matter here. But if a caller with a stale token hits /notices, authAttempted is set on the context but ignored, which is fine. No action needed, just confirming this route is not affected.

8. Test comment says "32+ chars so authMiddleware does the DB lookup" — should say optionalAuthMiddleware
test/api.test.ts comment at the invalid-bearer test — Minor but the inline comment references "authMiddleware" (the strict version) when it means optionalAuthMiddleware. Worth correcting to avoid confusion when navigating between the two.


False positives / intentional design choices

  • Info disclosure: "token rejected" vs "no token" — Acceptable for this tool. The caller already knows they sent a token; the backend confirming "it was rejected" doesn't leak any information an attacker couldn't deduce from the presence of a 401. Not a concern here.
  • Client-side double-gate (isAuthenticated() check before the network call) — The CLI's pre-flight check at dataset.ts:2397 is presence-only and intentionally so (avoids an extra round-trip). The backend is the authority; the fix makes the backend's rejection actionable. No change needed client-side.
  • optionalAuthMiddleware SQL query omits expires_at check — Pre-existing. The strict authMiddleware checks expires_at; the optional one only checks revoked_at. Tokens that are past expiry but not revoked would still authenticate via the optional path. This is a pre-existing issue unrelated to this PR.

Verdict: Mergeable after addressing items 1 (type accuracy) and 2 (consider a follow-up issue for the /:id route family). Item 3 is low risk given the CLI always sends Bearer. Items 4-8 are polish.

- Mark authAttempted as optional in Variables type (was a lie)
- Extend stale-token 401 hint to GET /datasets/:id
- Note lowercase bearer fallthrough in middleware comment
- Fix test comment: authMiddleware -> optionalAuthMiddleware
- Add negative assertion and test for /:id stale-token path
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review findings addressed (commit 2f445c3)

Important #1 — authAttempted type accuracy
Fixed: authAttempted: boolean -> authAttempted?: boolean in Variables (backend/src/types/bindings.ts). Added comment noting routes without optionalAuthMiddleware never set it.

Important #2 — Same bug class on GET /datasets/:id
Addressed inline. Added stale-token 401 check with re-login hint inside the if (!isCollaborator) block, parallel to the --mine fix. Added a dedicated test (GET /datasets/:id with invalid bearer token returns 401 with re-login hint). The manifest routes (/:id/manifest, /:id/manifest/:version) already return 403 "Access denied" (not 404), which is already actionable; left those alone.

Important #3 — Lowercase bearer comment
Added a comment above the startsWith("Bearer ") check noting the case-sensitive behavior and the proxy implication.

Suggestion #6 — Negative assertion on the --mine stale-token test
Added expect(data.error).not.toContain("Authentication required") to lock in the regression boundary.

Suggestion #8 — Test comment said authMiddleware instead of optionalAuthMiddleware
Fixed.

Suggestions #4, #5, #7 deferred as polish-only per the review; no behavior change needed.

@neuromechanist
neuromechanist merged commit 279394a into dev May 14, 2026
2 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-447-list-mine-auth branch May 14, 2026 05:15

This branch was previously deployed

1 inactive deployment
npm — 25baa1e8 Deployed May 14, 2026 by neuromechanist via publish #832
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.

1 participant