forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

conventions.md172 lines, 10.9 KiBHistoryRawDownload
1# Code conventions
2
3These rules are the same in `im`, `in` and `iz` (the file is copied into each repo). They are taken from
4`forge` (`~/Documents/Code/Rust/forge`, see its `docs/architecture.md`), which is the reference
5implementation: when a rule here is unclear, read how forge does it and do the same.
6
7## 1. Workspace
8
9- Edition 2024, resolver 3, `unsafe_code = "forbid"` in `[workspace.lints.rust]`, every member ends with
10 `[lints] workspace = true` and `publish = false`.
11- Every dependency version lives in the root `[workspace.dependencies]`, added with `cargo add` at its latest
12 release (never copied from another project). Members write `foo.workspace = true`.
13- Topcoat 0.11 with `default-features = false` and an explicit feature list. Turso (latest stable) for the
14 database.
15- Two crates per app: `<app>-core` (domain types, store, migrations, config, secrets, auth primitives, pure
16 logic; no HTTP) and `<app>-web` (the binary named `<app>`: Topcoat UI, HTTP APIs, background workers, CLI).
17 Add a crate only for a real boundary.
18- Dev profile: `debug = "line-tables-only"`; `opt-level = 3` for `argon2`, `sha2` and the turso crates, each with
19 a one-line reason. Release: `lto = true`, `codegen-units = 1`.
20
21## 2. Boot
22
23`main.rs` dispatches on positional words: no word or `serve` runs the server, `admin <cmd>` runs the CLI.
24Config path: `--config <path>`, then `<APP>_CONFIG`, then `config/<app>.toml`. Exit 2 on usage errors, 1 on
25failure.
26
27`serve` order: load and validate config → create `data_dir` (0700) → load or create `<app>.key` (32 bytes, 0600,
28`O_EXCL`) → open the store (pragmas, migrations) → layer stored UI overrides on the file config → spawn
29workers → build the router → bind → serve until SIGTERM/Ctrl-C, with one stop flag shared by every listener and
30worker.
31
32Logging: `tracing` + `tracing-subscriber` (`env-filter`), stderr, default `info`, structured fields. Never log
33tokens, passwords, cookies, or secrets.
34
35## 3. Config
36
37- `config/<app>.example.toml` is committed. `config/<app>.toml` is gitignored. A missing file is created from
38 the example (dev defaults) on first run.
39- `#[serde(deny_unknown_fields)]` on every struct. One `Config::validate()` for cross-field rules, used at load
40 and when a UI override is saved.
41- Secrets never live in the TOML. They are entered in the admin UI (sealed in the DB) or in a separate file
42 readable only by the service user.
43- Runtime settings: a `settings` key/value table with precedence **UI override → file → built-in default**, and
44 each field marked `Live`, `Restart` or `ReadOnly` (forge `server_settings.rs`).
45
46## 4. Store
47
48- One writer connection behind a tokio `Mutex`, plus a pool of 4 `PRAGMA query_only` readers. Pure reads use a
49 reader; writes, transactions and read-then-write sequences use the writer.
50- Pragmas on every connection: `journal_mode=WAL`, `synchronous=FULL`, `foreign_keys=ON`, busy timeout 5 s.
51 Read them back and log them at boot.
52- Migrations: `crates/<app>-core/migrations/NNNN_snake_name.sql`, each starting with a comment that says what
53 it does; listed in `store/migrate.rs` as `(version, include_str!(...))`; each applied in its own transaction
54 with a `schema_migrations` row. Never edit an applied migration.
55- Ids are ULID text. Timestamps are UTC RFC 3339 with 9 fractional digits and `Z` (fixed width, so text order is
56 time order) from `time.rs` (`now_stamp()`, `stamp_after(d)`). Booleans are `INTEGER` 0/1 with a `CHECK`.
57- Column lists are constants (`USER_COLS`) next to their `map_user(row)`; SQL uses `?1, ?2`; ownership goes in
58 the `WHERE` (`... WHERE id = ?1 AND owner_id = ?2`).
59- Multi-statement writes: `unchecked_transaction()` + an async block returning `Result` + one `finish(tx,
60 outcome)` helper that commits or rolls back.
61- Constraints live in the schema (`NOT NULL`, `CHECK`, `UNIQUE`, `REFERENCES ... ON DELETE ...`), not only in Rust.
62- Backups: `snapshot_to(path)` with `VACUUM INTO` on the writer, then checkpoint the copy so it is one
63 self-contained file, then fsync. `admin backup --out DIR` writes the snapshot, the blob tree (where the app
64 has one), a `manifest.json` with a sha256 per file and a `manifest.mac`: HMAC-SHA256 of the manifest bytes
65 under a subkey of the instance key, which lives outside the backup. Verify and restore check the MAC first
66 (constant time), then hashes, `integrity_check` and contiguous migrations. Never copy a live DB file.
67
68## 5. HTTP and pages
69
70- Routes with `#[route(...)]` / `#[page(...)]` and `.discover()`. Anything that must not be public is
71 registered explicitly on a separate router.
72- Handler shape: (1) authenticate, (2) load and authorize, (3) build the view, (4) return it.
73- Forms: every field `#[serde(default)]`; every state-changing POST carries a `csrf` field checked in constant
74 time **before** any side effect (`require_csrf`). Pre-session forms use the `__Host-<app>_precsrf` cookie
75 (SameSite=Strict). Post/Redirect/Get with notices in the query string (`?notice=...`), not cookies.
76- Session cookie: `__Host-<app>_session`, random 32 bytes base64url; the DB stores only its SHA-256.
77 HttpOnly, Secure, SameSite=Lax, Path=/.
78- `safe_next()` for every return path: one leading `/`, not `//` or `/\`, no control characters, ≤2048 bytes.
79- One security-headers layer on `/`: `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`,
80 `Referrer-Policy: same-origin`, `Strict-Transport-Security` when the base URL is https, and
81 `Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self';
82 form-action 'self'; frame-ancestors 'none'; base-uri 'none'`. **No inline scripts or styles anywhere**; all JS
83 is in `assets/*.js`.
84- Styled 404 page for `Accept: text/html`; 404 for "missing" and for "exists but you may not see it".
85- Request bodies are capped per route (`BodyLimit`); upload routes stream.
86- Assets (CSS compiled from `style/*.scss` with `grass` in `build.rs`, JS, fonts) are embedded with
87 `include_str!`/`include_bytes!`, served by routes with `Cache-Control: public, max-age=31536000, immutable`,
88 and linked with a content-hash query (`/assets/main.css?v=<12 hex>`). Fonts are self-hosted. Nothing is
89 loaded from a third-party origin.
90
91## 6. Auth primitives
92
93- Passwords: argon2id (`Argon2::default()`), PHC strings, always on `spawn_blocking`. Unknown accounts verify
94 against a fixed dummy hash so timing does not reveal them.
95- Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once.
96- Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second
97 factors per user; checked before any lookup; `429` with `Retry-After`.
98- Secrets at rest: `seal`/`open` with XChaCha20-Poly1305, `v1:` + base64(nonce || ciphertext). The instance
99 key is never used directly: every use gets its own key, HMAC-SHA256(instance key, "<app> <use> v1"), and
100 each seal binds its purpose (a fixed label) as associated data, so a value sealed for one purpose cannot
101 be opened as another.
102- Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left.
103
104## 7. Authorization
105
106One pure function per app, `authz::authorize(actor, resource, role, action) -> Result<(), Denied>`, with
107`Denied::{NotFound, Forbidden}`. Every page, form handler, API route and live stream goes through it. It is
108unit-tested as a truth table.
109
110## 8. Live pages
111
112- `LiveHub` of `watch::Sender<u64>` per `Topic` (an enum keyed by what a page is about). Writes call
113 `live.bump(&topic)` after commit.
114- A page that updates live renders `data-live="<stream url>"`. The stream route authenticates and authorizes
115 first, then `stream_changes(cx, hub, topics, fingerprint)`: subscribe, read a fingerprint, and send a
116 data-less `event: changed` only when the fingerprint changes. `retry: 1000`, keep-alive every 30 s,
117 `X-Accel-Buffering: no`.
118- `GET /-/alive` is held by every page (anonymous-safe). It drives the "server restarting" bar and carries
119 `account` events (sign-out, preference change) for the viewer.
120- `assets/nav.js` (one file, progressive enhancement): soft navigation for same-origin links and forms
121 (`data-hard` opts out), keeps focus/scroll/typed input across swaps, opens one EventSource per distinct
122 `data-live` URL, re-fetches the page on `changed`, reconnects after 1/2/3 s, never re-sends a POST.
123 Pages work without JS.
124
125## 9. Errors
126
127- One `thiserror` enum per crate: `Io`, `Database`, `Migration`, `Config`, `Crypto`, `NotFound`,
128 `Conflict(String)`, `Forbidden(String)`, `Invalid(String)`.
129- `Invalid` and `Conflict` text is for the user (shown as an alert). Everything else is a 500 with a generic
130 page and a logged cause.
131- Security-sensitive answers are identical for "unknown" and "wrong".
132
133## 10. Audit
134
135Append-only `audit_log` (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data JSON). Written
136after the change commits; a failed audit write is logged and never fails the request. Never store secrets in
137`data`. Admin page with filters and keyset paging. Rows older than the retention window are removed by the sweeper; nothing else deletes them.
138
139## 11. i18n
140
141English and Turkish. `Lang::{En, Tr}`; resolution: the user's stored language, else `Accept-Language`, else
142English. Keys are enums per area with an exhaustive `match` on `(key, lang)`, so a missing translation does not
143compile. **Every** page, including sign-in, error and mail text, is translated. Sentences with values use small
144format helpers, not concatenation in views.
145
146## 12. Comments and naming
147
148- `//!` on every module: what it is, what it is not, the invariant it keeps. `///` on every public item and on
149 every policy constant (with its unit and reason). Inline comments explain why, in full sentences.
150- No commented-out code. No `TODO` without a line in `docs/backlog.md`.
151
152## 13. Tests
153
154Few and meaningful. Unit tests for pure logic that is easy to get wrong (authz truth table, token and CSRF
155compare, `safe_next`, parsers, time math, quota math), store tests on a real temp database (`tempfile`) for
156tricky queries and constraints, and one or two in-process router tests per security rule (CSRF refused,
157hidden resource is 404, admin page refuses members). No snapshot tests, no browser tests, no mocks of the
158database. Tests never write outside their temp dir.
159
160## 14. Deploy
161
162`deploy/<app>.service`: dedicated user, `ProtectSystem=strict`, `ReadWritePaths=` the data dir only,
163`ProtectHome=yes`, `PrivateTmp=yes`, `PrivateDevices=yes`, `NoNewPrivileges=yes`, `CapabilityBoundingSet=`,
164`RestrictNamespaces=yes`, `RestrictSUIDSGID=yes`, `LockPersonality=yes`, `MemoryDenyWriteExecute=yes`,
165`SystemCallArchitectures=native`, `SystemCallFilter=@system-service`, `UMask=0077`, `Restart=on-failure`.
166`/healthz` per contracts.md 4.1.
167
168## 15. Git
169
170Commit messages follow forge's style: gitmoji + type + description, for example
171`✨ feat: sign-in with TOTP and recovery codes`, `🐛 fix: ...`, `♻️ refactor: ...`, `📝 docs: ...`.
172No co-author or "generated with" lines.