Skip to content

feat: scoped API tokens, token rotation UI, per-org rate limits, PII redaction - #756

Merged
Ayinkx merged 6 commits into
AyinkxLab:mainfrom
awwaumuhammed-star:feat/phase11-token-scopes-limits
Nov 23, 2026
Merged

Ayinkx merged 6 commits into
AyinkxLab:mainfrom
awwaumuhammed-star:feat/phase11-token-scopes-limits

Conversation

@awwaumuhammed-star

Copy link
Copy Markdown
Contributor

Summary

Scoped personal API tokens with rotation and revocation, per-organization rate limits, and central PII redaction for logs and exports.

This branch also carries two preparatory commits that were needed to make the repo gate and migrations usable at all; they are listed separately at the end so they can be split out.

Closes #613
Closes #616
Closes #617
Closes #621

#616 — scoped API tokens

  • New ApiToken model (api_tokens table, migration c1d2e3f4a5b6): label, display prefix, SHA-256 of the secret, scopes, created/last-used/expiry/revoked timestamps. The secret itself is never stored, and to_dict is metadata-only.
  • app/services/api_tokens.py provides create/rotate/revoke/authenticate plus normalize_scopes, required_scope and token_allows. Scopes are ranked read < write < admin: safe methods need read, POST/PUT/PATCH need write, DELETE needs admin.
  • Authentication is an early before_request hook that sets the Flask-Login identity for the request without touching the session. Tokens are accepted on JSON API paths only; a token on an HTML route returns the structured unauthorized error.
  • Token-only requests (bearer header, no session) skip the session CSRF check in ApiTokenCSRFProtect; session-authenticated requests keep the normal check.
  • Docs: docs/api-tokens.md, docs/api-v1.md, README.

#617 — rotation and revocation UI

  • New app/tokens/ blueprint with a management page and JSON endpoints: list (metadata only), create, rotate, revoke.
  • The secret is returned exactly once from create and rotate and never appears in a list, detail, audit record, or log.
  • Rotation invalidates the previous secret immediately; a revoked token cannot be rotated; revocation keeps the row so audit history survives. Destructive actions require confirmation in the UI.
  • Audit actions api_token_created, api_token_rotated, api_token_revoked.
  • Docs: docs/api-token-management.md.

#621 — per-organization rate limits

  • app/services/ratelimit.py gains api_quota(family): per-organization and per-token budgets per endpoint family, standard X-RateLimit-* headers and Retry-After, and the catalog rate_limited error body.
  • Limiter state is bounded by RATE_LIMIT_MAX_KEYS (default 10,000) with oldest-key eviction under the existing lock.
  • Applied to every /api/v1 resource; legacy per_user_limit/ai_limit denials now return the same catalog body instead of ad-hoc JSON.
  • Docs: docs/api-rate-limits.md.

#613 — PII redaction for logs and exports

  • app/services/classification.py gains REDACT_FIELDS (derived from every pii entry in FIELD_LEVELS), recursive redaction across dicts, lists, tuples and sets, and email scrubbing inside otherwise allowed strings via redact_text / EMAIL_MARKER. redact is the generic entry point; redact_for_log keeps its name for existing callers.
  • Admin audit export rows now pass through redact(..., max_level=INTERNAL); SIEM forwarding and structured chat audit logs already used the same helper.
  • Docs: docs/data-classification.md.

Verification

python -m ruff check .                     -> All checks passed
python -m black --check .                  -> 581 files unchanged
python -m pytest <new files plus neighbours> -o addopts="" -q
python -m flask --app wsgi db heads        -> c1d2e3f4a5b6 (head)

Test run covers the four new test modules plus classification, audit export, API v1, API quota, rate-limit endpoints, API keys, the error catalog and docs links.

Limitations

  • Rate limiting is process-local; per-organization budgets are per worker until a shared store is introduced (pre-existing constraint, documented).
  • The CSRF bypass for token-only requests is only exercised with CSRF disabled in the test config; its session-present branch keeps the original check.
  • A bearer header that matches no token falls back to an existing login session (the quota limiter uses Authorization as a subject key); without a session it is 401.
  • PII redaction is applied to structured logs, SIEM forwarding and admin audit exports. Owner data exports and the access-review compliance report intentionally still include the account owner's email, since redacting them would defeat their purpose.
  • Token mutations and their audit rows commit separately, so a failed audit write can leave a token change without its audit row (the request then returns 500).
  • The token UI is covered at route and template level; the JavaScript is read through but not exercised in a real browser.
  • The migration was verified by the single-head command and SQLite create_all; no PostgreSQL upgrade/downgrade was run.

Preparatory commits riding along

  • chore: restore green lint, format and single alembic head — adds an empty merge revision a0b1c2d3e4f6 because main currently has two Alembic heads (idempotency keys and IP allowlists), which breaks flask db upgrade; plus ruff/black-only fixes in app/services/idempotency.py and three test files.
  • test(billing): keep per-user usage dashboard checks date-independent (#446) — tests/test_usage_dashboards.py anchored rows to a frozen date while the route queries the real clock, so the tests expired; now derived from datetime.now(UTC).

Both are independently reviewable and can be split into their own PR if you prefer.

Origin/main failed 'ruff check', 'black --check' and 'flask db heads': two Phase 11 branches (idempotency keys and IP allowlists) landed without a merge revision, and four recently merged files drifted from the configured formatters. Apply ruff/black fixes only; no behaviour change.
…yinkxLab#446)

The route tests built rows around a frozen 2026-10-20 anchor while the dashboard queries the real clock, so the owner-scoped totals, empty state and filter assertions expired after the window moved on. Anchor the fixture to 'now' and derive the expected daily labels instead of hard-coding them.
@vercel

vercel Bot commented Nov 23, 2026

Copy link
Copy Markdown

@awwaumuhammed-star is attempting to deploy a commit to the Ayinkx Team on Vercel.

A member of the Team first needs to authorize it.

@drips-wave

drips-wave Bot commented Nov 23, 2026

Copy link
Copy Markdown

@awwaumuhammed-star Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits


def hash_secret(secret: str) -> str:
"""Return the SHA-256 hex digest stored for ``secret``."""
return hashlib.sha256(secret.encode("utf-8")).hexdigest()

def redact_text(value: str) -> str:
"""Replace email addresses embedded in ``value`` with a bounded marker."""
return EMAIL_PATTERN.sub(EMAIL_MARKER, value)
@Ayinkx
Ayinkx merged commit 3f8dec9 into AyinkxLab:main Nov 23, 2026
12 of 19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants