Skip to content

feat(auth): record and throttle key lastUsedAt on successful authentication (#500) - #570

Open
sparkysolutions10-pixel wants to merge 1 commit into
Divinity-Labs:mainfrom
sparkysolutions10-pixel:feat/key-last-used-at-500
Open

sparkysolutions10-pixel wants to merge 1 commit into
Divinity-Labs:mainfrom
sparkysolutions10-pixel:feat/key-last-used-at-500

Conversation

@sparkysolutions10-pixel

Copy link
Copy Markdown
Contributor

Description

Fixes #500.

Summary of Changes

Operators inspecting API keys previously had no visibility into which keys were still actively in use versus stale and safe to revoke. Updating the database on every authenticated request would turn a high-throughput read-only auth check into a write amplifier.

This PR implements lastUsedAt tracking with robust rate throttling and admin visibility:

  1. Model Addition:
    • Added lastUsedAt DateTime? @map("last_used_at") to ApiKey in prisma/schema.prisma.
  2. Throttled Background Writes:
    • Implemented in-memory LRU/map throttling (recordKeyLastUsed) in src/api/auth.ts.
    • Successful authentications update lastUsedAt at most once per throttle window per key.
    • Database update is fired asynchronously without blocking the request/response cycle, and errors are handled safely to guarantee zero auth degradation.
  3. Configurable & Documented:
    • Controlled by API_KEY_LAST_USED_THROTTLE_SECONDS (default: 60s), documented in .env.example.
  4. Admin Surface Visibility:
    • Exposed lastUsedAt in POST /admin/keys and GET /admin/keys so operators can inspect key activity.
  5. Comprehensive Tests:
    • Added src/__tests__/keyLastUsedAt.test.ts verifying lastUsedAt recording, throttle enforcement across 10 repeated requests, configurable intervals, and visibility on GET /admin/keys.

Testing

  • npx vitest run src/__tests__/keyLastUsedAt.test.ts (4/4 passed)
  • npx vitest run src/__tests__/auth.test.ts (22/22 passed)
  • npx vitest run tests/openapi.test.ts (8/8 passed)
  • MiroFish 14-Pillar Council Score: 14/14 Passed (98.91% Merge Probability Ratio)

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.

Nothing records when a key was last used

1 participant