feat: add tests for import polling, login page, money utilities, and query keys
- Implemented tests for import polling functionality, ensuring correct behavior for active and terminal import statuses. - Created tests for the login page, validating user interactions and error handling. - Added unit tests for money utility functions, covering parsing, formatting, and summation of monetary values. - Developed tests for query keys, ensuring proper scoping and invalidation roots. chore: setup testing environment and configuration - Added setup file for testing with Vitest and Testing Library. - Configured TypeScript and Vite for the frontend project. - Created Docker and Nginx configurations for local development and production environments. - Established a PostgreSQL initialization script for setting up application roles. docs: add README and environment configuration for infra - Included README for the infra directory, detailing local development setup and service descriptions. - Created an example environment configuration file for local development with placeholders for sensitive information.
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
# ADR 0001: Financial space ownership and RLS
|
||||
|
||||
- **Status:** Accepted
|
||||
- **Date:** 2026-09-11
|
||||
- **Scope:** tenancy model, data isolation, authorization boundary
|
||||
|
||||
## Context
|
||||
|
||||
Every financial fact (accounts, operations, postings, budgets, categories, payees, imports) belongs to exactly one financial space. All members of a space see all of its data; there is no per-user row visibility in MVP. Support staff must not be able to browse financial content. PostgreSQL is the only datastore, with pooled connections shared by API processes and Celery workers, so a leaked tenant context is a critical failure mode.
|
||||
|
||||
## Decision
|
||||
|
||||
- `financial_spaces` is the single ownership boundary. Every financial table carries `space_id` from day one.
|
||||
- Membership links a user to a space with role `owner` or `member`; all members have full visibility inside the space. At least one owner must always remain.
|
||||
- Authorization is enforced twice:
|
||||
1. Application services check membership before any query.
|
||||
2. Inside the request/task transaction the service runs `SET LOCAL app.space_id`, and PostgreSQL RLS policies re-check every access. A missing context fails closed.
|
||||
- Workers receive IDs only, re-validate ownership, and set the same transaction-local RLS context.
|
||||
- Cross-space references are forbidden by composite foreign keys `(space_id, id)` between financial tables.
|
||||
- A bypass/owner role exists only for migrations and audited break-glass tooling; the API and worker roles are always RLS-restricted.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Retrofitting `space_id` + RLS onto existing tables is expensive, so this must hold from the first migration (hard to reverse).
|
||||
- Pooled connections must never leak context: settings are transaction-local only, and tenant-escape negative tests are mandatory.
|
||||
- Break-glass requires a separate role, a mandatory reason, short-lived grants, and append-only audit.
|
||||
|
||||
## Alternatives rejected
|
||||
|
||||
- Application-level filtering only — one missed filter leaks tenant data.
|
||||
- Database-per-tenant — operational cost unjustified at beta scale (≤ 100 users).
|
||||
- Per-user row visibility — contradicts the space ownership model.
|
||||
@@ -0,0 +1,29 @@
|
||||
# ADR 0002: Journal of operations/postings and budget reserves
|
||||
|
||||
- **Status:** Accepted
|
||||
- **Date:** 2026-09-11
|
||||
- **Scope:** ledger model, balance derivation, budget plan/funding separation
|
||||
|
||||
## Context
|
||||
|
||||
The product needs trustworthy account balances including credit-card debt, zero-based monthly budgeting where the plan is separate from actual funded money, carry-over savings envelopes, and permanent per-card credit reserves. History must remain auditable and deterministic: closed budget facts must never silently change.
|
||||
|
||||
## Decision
|
||||
|
||||
- The ledger is a journal of `operations` (`expense | income | transfer | refund`; `confirmed | voided`) and `postings` (one posting for external income/expense/refund; two equal and opposite postings for an internal transfer). Amounts are integer kopecks; no floats.
|
||||
- Balances are derived, never mutated directly: opening position plus confirmed, non-voided postings. Credit debt follows one documented sign convention.
|
||||
- This is **not** event sourcing and **not** full double-entry against the external world: the journal is just enough structure to make balances reconstructable and voiding explicit.
|
||||
- Budgeting splits plan from funding: `plan_assignments` express intent, `funding_movements` move actually received money from the general pool. Monthly categories fold their remainder into the pool at close; savings envelopes carry balances forward; each credit card has a permanent reserve.
|
||||
- Period closure writes an immutable snapshot. Changing or voiding an operation in a closed month requires an explicit cascade reopen of all subsequent periods; late refunds after closure credit the current pool and never rewrite the closed fact.
|
||||
|
||||
## Consequences
|
||||
|
||||
- All balance-affecting mutations must go through journal/budget services; direct updates are excluded by convention and tests.
|
||||
- Analytics for closed periods read from closure snapshots, not live aggregates.
|
||||
- Plan/funding separation and closure snapshots shape the write model permanently (hard to reverse once history exists).
|
||||
|
||||
## Alternatives rejected
|
||||
|
||||
- Event sourcing — complexity without a matching need at MVP scale.
|
||||
- Mutable stored balances without a journal — loses auditability and voiding semantics.
|
||||
- Folding envelopes/reserves into the pool — destroys carried-forward user intent.
|
||||
@@ -0,0 +1,30 @@
|
||||
# ADR 0003: Versioned statement imports
|
||||
|
||||
- **Status:** Accepted
|
||||
- **Date:** 2026-09-11
|
||||
- **Scope:** statement import pipeline, parse provenance, deduplication, apply/revert semantics
|
||||
|
||||
## Context
|
||||
|
||||
Five bank statement contracts must be parsed (Alfa debit/credit XLSX, Ozon debit/credit PDF, Rocketbank debit PDF). Bank layouts drift over time. Money facts must never change until the user has reviewed the parse; losing a real operation is worse than holding a duplicate for review. The HTTP process must not parse files.
|
||||
|
||||
## Decision
|
||||
|
||||
- An uploaded statement document is immutable: magic/MIME/size/hash checks, then storage encrypted per ADR 0004. Full extracted text is never persisted — only allowlisted statement fields plus page/row coordinates.
|
||||
- Every parse produces a versioned **parse run** (adapter + parser version) yielding immutable **source records** with document origin. A reparse creates a new run and diff; previous runs are never mutated.
|
||||
- State machine: `uploaded → queued → processing → review_required/ready → confirmed | failed`. Confirm applies the whole run atomically in a single DB transaction, creating only new operations/postings; existing duplicates only gain additional source links. Revert deletes exactly what that import created, with cascade reopen of affected periods.
|
||||
- Deduplication is conservative: auto-link only a stable bank identifier or a single unambiguous match; ambiguous candidates stay pending until the user decides.
|
||||
- Bank layout drift produces a **new parser version** with an explicit review diff — historical data is never silently reinterpreted. An adapter is beta-eligible only after the private fixture gate (see `docs/parsers/private-fixture-gate.md`).
|
||||
- Parsing runs in the Celery worker, isolated and resource-limited (memory, time, pages, rows, cells).
|
||||
|
||||
## Consequences
|
||||
|
||||
- No row influences the ledger before explicit confirm; this invariant is enforced by tests (import confirm/revert idempotence).
|
||||
- Parse runs and source records grow storage; acceptable at beta scale, trimmed only with the source file deletion workflow.
|
||||
- Adapter code must explicitly detect its layout; a mismatch fails with stable diagnostics instead of guessing.
|
||||
|
||||
## Alternatives rejected
|
||||
|
||||
- In-request synchronous parsing — blocks HTTP workers on untrusted files.
|
||||
- Mutable "latest parse" overwrites — destroys provenance and diffability.
|
||||
- Aggressive auto-dedup — risks dropping real operations.
|
||||
@@ -0,0 +1,29 @@
|
||||
# ADR 0004: Provider-neutral images and encrypted data boundary
|
||||
|
||||
- **Status:** Accepted
|
||||
- **Date:** 2026-09-11
|
||||
- **Scope:** deployment neutrality, data residency, object encryption, secret handling
|
||||
|
||||
## Context
|
||||
|
||||
Bank statement files are sensitive personal/financial data. Legal requirements (to be confirmed by qualified counsel before real invites) demand that hosting, database, object storage and backups reside in the Russian Federation. The hosting provider may change; no cloud-proprietary service may become load-bearing. External AI calls are out of MVP scope.
|
||||
|
||||
## Decision
|
||||
|
||||
- Backend and frontend ship as provider-neutral OCI images (`infra/docker/`), depending only on commodity services: PostgreSQL, Redis, S3-compatible object storage, SMTP, and a secret manager — all locatable in the RF. Nothing in the images references a specific cloud API.
|
||||
- Statement files are envelope-encrypted **before** storage: a random AES-256-GCM data-encryption key (DEK) per file, with the encrypted DEK and nonce stored in PostgreSQL and the key-encryption key (KEK) held only in the secret manager. Object keys are random and carry no PII. KEK rotation rewraps DEKs.
|
||||
- Deletion is crypto-shredded: space purge removes rows and objects and destroys DEKs, so restored backups cannot resurrect file contents (see `docs/operations/deletion-ledger.md`).
|
||||
- Secrets live only in the environment/secret manager. Nothing secret is committed to Git or compiled into `VITE_*` frontend variables; the frontend requires no secrets at all (same-origin `/api/v1`).
|
||||
- API/worker make no outbound AI or third-party calls in MVP; the worker additionally has no egress in production.
|
||||
- Observability is provider-neutral (health/readiness, queue depth, parser duration/failure per adapter version) and never carries financial payloads.
|
||||
|
||||
## Consequences
|
||||
|
||||
- The platform must supply managed PostgreSQL/Redis/S3/SMTP and a secret manager in the RF; KEK loss means permanent loss of stored statement files, so KEK backup is mandatory.
|
||||
- Envelope encryption is **not** zero-knowledge: a compromised running API/worker plus KEK can decrypt files, so break-glass isolation and audit remain necessary.
|
||||
- Provider neutrality is a hard architectural rule: reintroducing a cloud-specific dependency later would force a migration (treat as hard to reverse).
|
||||
|
||||
## Alternatives rejected
|
||||
|
||||
- Single-provider managed SDKs — vendor lock-in conflicts with RF-hosting flexibility.
|
||||
- Server-side (SSE) bucket encryption only — insufficient given the sensitivity of raw bank statements and the crypto-shred deletion requirement.
|
||||
@@ -0,0 +1,38 @@
|
||||
# Backup and Restore
|
||||
|
||||
> Status: **design/runbook**. The stack is not deployed yet; no restore has been
|
||||
> performed. Do not treat these targets as verified until a drill passes.
|
||||
|
||||
## Scope and targets (proposed)
|
||||
|
||||
| Item | Method | Retention | RPO target |
|
||||
| --- | --- | --- | --- |
|
||||
| PostgreSQL | Provider-native PITR if available; else nightly `pg_dump -Fc`, encrypted at rest | 30 days | ≤ 24 h |
|
||||
| Object storage (statement files) | Provider versioning/replication of the bucket | 30 days | ≤ 24 h |
|
||||
| KEK / secrets | Secret-manager backup per provider policy | indefinite | ~0 (loss = data loss) |
|
||||
| Redis | none — cache/queue only, rebuilt on restore | — | acceptable loss |
|
||||
| Container images | registry retained per release tag | last 10 releases | — |
|
||||
|
||||
Statement files are envelope-encrypted (ADR 0004): restoring PostgreSQL without
|
||||
the matching DEK rows **and** the KEK makes files permanently undecryptable. KEK
|
||||
backup is therefore mandatory and must be tested like a restore.
|
||||
|
||||
## Restore procedure (draft)
|
||||
|
||||
1. Provision replacement PostgreSQL/Redis/S3 endpoints in the RF region.
|
||||
2. Restore the latest PostgreSQL backup into the new instance; run `alembic upgrade head` to confirm schema state matches the deployed image.
|
||||
3. Restore the object bucket from versioning/replica.
|
||||
4. Restore secrets: KEK, `SESSION_SECRET`, DB/S3/SMTP credentials.
|
||||
5. Deploy the last known-good image tags (API, worker, frontend proxy) with the restored endpoints configured.
|
||||
6. **Re-apply the durable deletion ledger** for entries executed after the backup timestamp (see `deletion-ledger.md`): re-delete purged rows/objects and re-shred DEKs.
|
||||
7. Smoke test: `/healthz` on API, queue consumer alive, one synthetic import end-to-end, login with an invited test user.
|
||||
8. Reopen traffic at the edge.
|
||||
|
||||
## Restore drill
|
||||
|
||||
- Cadence: before beta launch, then quarterly.
|
||||
- Record in this file: date, backup age, result, defects found.
|
||||
- Drills performed: **none yet**.
|
||||
|
||||
A disaster test is a launch gate (plan §10): restore a backup, reapply the
|
||||
completed deletion ledger, and prove purged spaces/keys remain inaccessible.
|
||||
@@ -0,0 +1,40 @@
|
||||
# Beta Release Runbook (closed beta)
|
||||
|
||||
> Status: **template**. No release has been executed. Every unchecked item is
|
||||
> still open; do not check items from this document without doing them.
|
||||
|
||||
## Preconditions (launch gate)
|
||||
|
||||
- [ ] One-shot Alembic migration applied from an empty database on staging.
|
||||
- [ ] Provider-neutral images built and tagged (API/worker: `infra/docker/Dockerfile.backend`; frontend: `infra/docker/Dockerfile.frontend`) and pushed to the registry.
|
||||
- [ ] Same-origin reverse proxy live at the edge with TLS + HSTS; `/api/v1` verified end-to-end (login round-trip).
|
||||
- [ ] `/healthz` (API) and readiness probes wired to the platform; queue-depth and parser-failure metrics visible.
|
||||
- [ ] Backups configured and a **restore drill passed** (`backup-and-restore.md`).
|
||||
- [ ] KEK and secrets present in the secret manager; nothing secret in `VITE_*` or Git (ADR 0004).
|
||||
- [ ] Legal/privacy gate for RF data localization **signed by qualified counsel** — hard gate before any real invite.
|
||||
- [ ] Deletion workflow (30-day window, purge, ledger) reviewed against `deletion-ledger.md`.
|
||||
- [ ] Bank adapters enabled only per `docs/parsers/private-fixture-gate.md`; unsupported formats are not advertised.
|
||||
- [ ] Invites limited to an explicit allowlist; public registration stays off.
|
||||
|
||||
## Launch sequence
|
||||
|
||||
1. Deploy images; run migrations one-shot (`alembic upgrade head`), never on container start.
|
||||
2. Smoke test on production data (synthetic only): invite → register → create space/account → plan month → manual operation → import synthetic statement → review/confirm → close month → reports.
|
||||
3. Verify Mailpit-equivalent SMTP path against the production SMTP relay (invite email delivered).
|
||||
4. Enable email invites for the allowlist; monitor error rates, queue depth, parser failures for the first sessions.
|
||||
|
||||
## Rollback
|
||||
|
||||
- Redeploy previous image tags; migrations are **forward-fix preferred**.
|
||||
- Downgrade only where the migration is marked reversible in Alembic; otherwise restore from backup and re-apply the deletion ledger (see `backup-and-restore.md`).
|
||||
- Never roll forward a parser version without a review diff (ADR 0003).
|
||||
|
||||
## Incidents
|
||||
|
||||
- Financial-data suspected exposure: revoke sessions, rotate `SESSION_SECRET`, preserve audit events, follow the (to-be-written) privacy incident procedure.
|
||||
- Break-glass access: separate role, mandatory reason, short-lived grant, append-only audit — never through ordinary admin tooling.
|
||||
|
||||
## Post-launch
|
||||
|
||||
- Record adapter gate statuses and any layout-drift events.
|
||||
- Keep the restore drill quarterly; update `backup-and-restore.md` drill log.
|
||||
@@ -0,0 +1,36 @@
|
||||
# Deletion Ledger
|
||||
|
||||
> Status: **contract definition**. The hardening workstream (plan §9) implements
|
||||
> this; nothing here is verified in code yet.
|
||||
|
||||
## Purpose
|
||||
|
||||
Space deletion is final and must survive disaster restores. A backup restored
|
||||
after a purge would otherwise resurrect rows, objects and metadata of deleted
|
||||
spaces. The deletion ledger is an append-only record of completed deletions that
|
||||
any restore **must** replay before serving traffic.
|
||||
|
||||
## Lifecycle
|
||||
|
||||
1. **Request** — user requests space deletion. The space is locked immediately (no logins, writes or imports); a 30-day cancellation window starts.
|
||||
2. **Cancel** — within the window the owner may cancel; the lock is lifted, nothing is purged.
|
||||
3. **Purge** (after the window, via Celery worker):
|
||||
- hard-delete all space rows (financial tables, categories, payees, imports, memberships, users where applicable);
|
||||
- delete all S3 objects of the space and destroy the per-file DEK rows (crypto-shred, ADR 0004);
|
||||
- append one ledger entry **only after** all phases succeed.
|
||||
4. **Ledger entry** — append-only, minimal fields: `space_id`, `requested_at`, `purged_at`, `executed_by (job id)`, `phases_completed`, `integrity_hash` (chain hash over prior entry). No financial payloads.
|
||||
|
||||
## Replay after restore
|
||||
|
||||
On any disaster restore (see `backup-and-restore.md` step 6):
|
||||
|
||||
1. Load ledger entries with `purged_at` later than the restored backup timestamp.
|
||||
2. For each: re-delete the space's rows (restored backups may contain them again), re-delete its objects, re-destroy DEK rows.
|
||||
3. Verify: no row with `space_id` in any financial table; bucket prefix absent; decryption of the space's files impossible.
|
||||
4. Record the replay in the drill log.
|
||||
|
||||
## Implementation notes
|
||||
|
||||
- The ledger table itself is never purged by space deletion and is included in backups.
|
||||
- A purge job must be idempotent and resumable: each phase is committed separately and the ledger entry is written last, in the same transaction as the final phase marker.
|
||||
- Ledger integrity is checked on startup after restore (chain hash mismatch = manual escalation).
|
||||
@@ -0,0 +1,45 @@
|
||||
# Parser Private Fixture Gate
|
||||
|
||||
Real bank statements contain personal financial data and are **never committed**
|
||||
to Git (`.gitignore` at the repo root covers this; keep fixture directories
|
||||
outside the repository). CI runs synthetic fixtures only.
|
||||
|
||||
## Contract
|
||||
|
||||
- Synthetic parser inputs live with the backend tests and run in CI.
|
||||
- Real statement files stay in a local `PRIVATE_FIXTURES_DIR`, never in Git, never in shared storage without encryption.
|
||||
- The private suite runs explicitly, on the developer's machine:
|
||||
|
||||
```sh
|
||||
PRIVATE_FIXTURES_DIR=/secure/path/fixtures uv run pytest -m private_fixtures
|
||||
```
|
||||
|
||||
(Exact marker/task names are finalized by the backend workstream; the entry point contract is `PRIVATE_FIXTURES_DIR` + a dedicated pytest marker.)
|
||||
|
||||
## Beta gate per adapter/contract
|
||||
|
||||
An adapter may be declared beta-supported only when, against **private** fixtures:
|
||||
|
||||
- [ ] at least two complete real periods of its contract parse successfully;
|
||||
- [ ] malformed file fails with stable diagnostics (no crash, no partial state);
|
||||
- [ ] oversized file is rejected by quotas before parsing;
|
||||
- [ ] duplicate statements produce identical parse results (hash-idempotent enqueue/apply);
|
||||
- [ ] overlapping periods produce expected duplicate candidates for review, not silent merges;
|
||||
- [ ] wrong-bank/encrypted/scanned (no text layer) files are detected and refused.
|
||||
|
||||
Record the gate result per adapter version below. An adapter without a passed
|
||||
gate must not be enabled or advertised, even if synthetic tests pass (plan
|
||||
§"Основные риски и gates").
|
||||
|
||||
## Gate status
|
||||
|
||||
| Adapter / parser version | Private periods passed | Gate |
|
||||
| --- | --- | --- |
|
||||
| Alfa debit XLSX | — | **not passed** |
|
||||
| Alfa credit XLSX | — | **not passed** |
|
||||
| Ozon debit PDF | — | **not passed** |
|
||||
| Ozon credit PDF | — | **not passed** |
|
||||
| Rocketbank debit PDF | — | **not passed** |
|
||||
|
||||
No adapter is currently gated. Bank layout drift resets the gate: it must create
|
||||
a new parser version and a review diff, never reinterpret historical data.
|
||||
Reference in New Issue
Block a user