infrasynth-backend-kit/README.md
jcv-dev 551b42eab5 feat: production-hardening pass across the kit
Close the gaps between the documented contract (API-STANDARD, TENANCY,
ENTITLEMENTS) and the implementation, and remove committed build artifacts.

Security:
- verify + process inbound webhooks (HMAC/handler verify, size limit,
  timestamp tolerance, idempotency via InboundEvent.external_id)
- real 2FA login flow (pre-auth challenge; tokens only after verify/recovery)
- wire HybridPermission into security/audit views; add API-key rotate and
  users/<id>/permissions|roles endpoints
- tenant-scoped throttling on by default; webhook replay protection
- verify MercadoPago webhook signatures
- login brute-force guard, configurable password policy, real ALTCHA PoW

Correctness:
- apply verified billing webhooks idempotently (subscription/entitlement/
  invoice/PaymentTransaction); scheduled payment lifecycle jobs
- capture audit update diffs automatically; add audit retention purge
- working notification retries, per-channel rate limits, log retention
- pluggable virus scanner, upload-size limit, pipeline toggle
- feature rollout %/environment targeting; settings-driven registrations
- workflow guards (instance cap, route depth, self-assignment, clone on re-entry)
- wire every previously-dead INFRASYNTH_* setting; drop truly dead ones

Delivery:
- README + CHANGELOG; CI format check + coverage gate
- keep test media out of the tree; untrack .coverage, __pycache__,
  egg-info, docs/ and invoice artifacts
2026-09-24 10:41:21 -05:00

90 lines
4.3 KiB
Markdown

# InfraSynth Base
Reusable, multi-tenant Django infrastructure kit — the one shared package every InfraSynth app depends on.
```bash
pip install -e ".[dev]" # install the kit + dev tooling
docker compose up -d db redis # postgres + redis
python manage.py migrate # create the schema
python manage.py runserver # http://localhost:8000/api/v1/schema/docs/
```
Then `pytest` (single-command test suite), `ruff check .`, and `mypy infrasynth/`.
---
## What this is
One pip package (`infrasynth-base`) providing ten Django apps so no app ever reimplements auth, tenancy, entitlements, audit, files, notifications, webhooks, workflows, scheduling, or the API envelope:
| Module | Responsibility |
|---|---|
| `infrasynth.shared` | Zero-Django primitives: protocols, enums, `Result`, Fernet crypto, settings helper |
| `infrasynth.api` | DRF envelope, camelCase, cursor pagination, request-id, exceptions, throttling, idempotency, webhook hardening |
| `infrasynth.tenancy` | `Tenant`, membership, invitations, platform staff, `current_tenant`, scoped managers, middleware |
| `infrasynth.security` | JWT cookie + API-key auth, roles/grants/revokes, 2FA (TOTP), ALTCHA, login brute-force guard, password policy |
| `infrasynth.audit` | Passive create/update/delete tracking, API interaction log, security events, retention purge |
| `infrasynth.features` | Operational feature flags with tenant/user/group overrides, rollout %, environment targeting |
| `infrasynth.billing` | App catalog, plans, entitlements, subscriptions, invoices, gateways, entitlement lifecycle jobs |
| `infrasynth.files` | Storage abstraction (S3/GCS/local/Cloudinary), signed URLs, processing pipelines, pluggable virus scanning |
| `infrasynth.notifications` | Multi-channel delivery with failover, retries, rate limits, and log retention |
| `infrasynth.webhooks` | Outbound delivery with HMAC + retry, verified inbound processing, event registry |
| `infrasynth.workflows` | State-machine engine, voting/approval strategies, validators |
| `infrasynth.scheduler` | Celery job dashboard + on-demand execution |
**Every app is multi-tenant.** One deployment, one schema, row-level isolation via a non-null `tenant_id`, a fail-closed `TenantManager`, and cross-tenant access that returns `404`. See `../TENANCY.md` (binding).
**There is no license server.** Access is an in-process *entitlement* (`is_entitled` / `check_limit`), enforced server-side. See `../ENTITLEMENTS.md` (binding).
---
## Configuration
Every knob is a namespaced dict with a safe default, read through `infrasynth.shared.settings_utils.get_setting`:
```python
INFRASYNTH_SECURITY = {"COOKIE_SECURE": True, "IP_BLACKLIST_THRESHOLD": 100}
INFRASYNTH_TENANCY = {"REQUIRE_TENANT_BY_DEFAULT": True, "TENANT_CLAIM": "tenant"}
INFRASYNTH_BILLING = {"GRACE_PERIOD_DAYS": 5, "DEFAULT_CURRENCY": "USD"}
INFRASYNTH_NOTIFICATIONS = {"CHANNELS": {"email": {"primary": "myapp.channels.SlackChannel"}}}
```
The full, commented reference lives in `config/settings/base.py`. Real settings files **never** live in this package — apps supply their own and pin the kit.
---
## Extending without forking
Integrate through settings, signals, registries, ABCs, and feature flags — never a local patch:
```python
# myapp/channels.py
from infrasynth.notifications.channels.base import BaseChannel
from infrasynth.shared.results import Result
class SlackChannel(BaseChannel):
channel_type = "slack"
def send(self, recipient, subject, body, is_html=True, attachments=None):
...
return Result.ok(True)
def health_check(self) -> bool:
return True
@classmethod
def from_config(cls, config): return cls(**config)
```
Registries are populated in `apps.py:ready()`: `FeatureRegistry`, `EventRegistry`, `VariableResolverRegistry`, `DataValidatorRegistry`.
---
## Scheduled work
`CELERY_BEAT_SCHEDULE` ships with the kit: notification retries/log purge, billing sync + lifecycle + renewal invoices, and audit retention. Run `celery -A config beat` and `celery -A config worker`.
---
## Quality bar
- `ruff check` + `ruff format --check` + `mypy infrasynth/` are CI gates.
- `pytest` runs the full suite; coverage is enforced in CI (see `pyproject.toml`).
- A change to kit behavior belongs **here**, then consuming apps bump their pin — see `../AGENTS.backend-packages.md` §9.