Skip to content

feat: add scoped API key auth for service-to-service traffic - #153

Open
Victorjonah-prog wants to merge 2 commits into
NovaCoreLabs1:mainfrom
Victorjonah-prog:feat/api-key-auth
Open

feat: add scoped API key auth for service-to-service traffic#153
Victorjonah-prog wants to merge 2 commits into
NovaCoreLabs1:mainfrom
Victorjonah-prog:feat/api-key-auth

Conversation

@Victorjonah-prog

@Victorjonah-prog Victorjonah-prog commented Jul 16, 2026

Copy link
Copy Markdown

Summary
Implements scoped API key authentication for service-to-service and cron traffic, separate from the existing JwtAuthGuard.
Changes

entities/api-key.entity.ts — TypeORM entity with prefix, bcrypt hash, scopes, expiry, and revocation
entities/api-key-audit.entity.ts — Append-only audit log recording every key use by (key_id, endpoint, ip)
guards/api-key.guard.ts — Guard that validates X-API-Key header, checks hash, enforces scopes, expiry and revocation
decorators/required-scopes.decorator.ts — @RequiredScopes('write:invoices') decorator for route-level scope enforcement
services/api-key.service.ts — Creates bcrypt-hashed keys, supports revocation, never returns raw keys after creation
api-key.module.ts — Wires everything together
auth.module.ts — Updated to include new entities, guard and service

How it works

Keys are stored as prefix (8 chars) + bcrypt hash — prefix enables fast DB lookup without scanning hashes
X-API-Key header is extracted, prefix derived, row fetched, then bcrypt-compared
Revoked and expired keys return 401
Missing scopes return 403
Every successful auth is logged to api_key_audit_logs by (key_id, endpoint, ip)

Tests
9 tests passing covering all acceptance criteria

close #32

@Victorjonah-prog

Copy link
Copy Markdown
Author

Backend (NestJS) is passing — Lint, Build Check, and Test Suite failures are in the Rust contracts and are pre-existing issues unrelated to this PR.

@dzekojohn4 dzekojohn4 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix the CI

@Victorjonah-prog

Copy link
Copy Markdown
Author

The Build Check, Clippy Lint, and Test Suite failures are caused by a pre-existing bug in ethnum v1.5.2 inside the contracts/ folder — error[E0512]: cannot transmute between types of different sizes. This error exists on the main branch before my changes and is unrelated to this PR which only touches backend/src/auth/. The Backend (NestJS) CI job passes successfully with all 9 tests passing. @dzekojohn4

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.

Add scoped API key auth for service-to-service traffic

2 participants