# API Keys

**Last Updated:** 2025-01
**Confidence:** High

## Summary

API keys authenticate all requests to rdev (except health/docs). Keys have scopes, can be restricted to specific projects and IP ranges, and have expiration dates.

**Key Facts:**
- Header: `X-API-Key: <key>`
- Keys are hashed before storage (only prefix visible)
- Admin key via `RDEV_ADMIN_KEY` env var for bootstrap
- Scopes: `projects:read`, `projects:write`, `keys:read`, `keys:write`, `audit:read`
- Project restrictions: nil = all projects, or list of allowed project IDs
- IP restrictions: CIDR notation for allowed ranges

**File Pointers:**
- Service: `internal/auth/service.go`
- Middleware: `internal/auth/middleware.go`
- Handler: `internal/handlers/keys.go`
- Repository: `internal/adapter/postgres/apikey.go`

## Key Lifecycle

1. Create via `POST /keys` (admin only)
2. Key returned once (plaintext), stored hashed
3. Validate on each request via middleware
4. Revoke via `DELETE /keys/{id}`

## Scopes

| Scope | Allows |
|-------|--------|
| `projects:read` | List/get projects |
| `projects:write` | Execute commands |
| `keys:read` | List API keys |
| `keys:write` | Create/delete keys |
| `audit:read` | Query audit logs |

## Related Topics

- [Project Service](./project-service.md)
