forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

conventions.md10.7 KiBHistoryRawDownload

Code conventions

These rules are the same in im, in and iz (the file is copied into each repo). They are taken from forge (~/Documents/Code/Rust/forge, see its docs/architecture.md), which is the reference implementation: when a rule here is unclear, read how forge does it and do the same.

1. Workspace

  • Edition 2024, resolver 3, unsafe_code = "forbid" in [workspace.lints.rust], every member ends with [lints] workspace = true and publish = false.
  • Every dependency version lives in the root [workspace.dependencies], added with cargo add at its latest release (never copied from another project). Members write foo.workspace = true.
  • Topcoat 0.11 with default-features = false and an explicit feature list. Turso (latest stable) for the database.
  • Two crates per app: <app>-core (domain types, store, migrations, config, secrets, auth primitives, pure logic; no HTTP) and <app>-web (the binary named <app>: Topcoat UI, HTTP APIs, background workers, CLI). Add a crate only for a real boundary.
  • Dev profile: debug = "line-tables-only"; opt-level = 3 for argon2, sha2 and the turso crates, each with a one-line reason. Release: lto = true, codegen-units = 1.

2. Boot

main.rs dispatches on positional words: no word or serve runs the server, admin <cmd> runs the CLI. Config path: --config <path>, then <APP>_CONFIG, then config/<app>.toml. Exit 2 on usage errors, 1 on failure.

serve order: load and validate config → create data_dir (0700) → load or create <app>.key (32 bytes, 0600, O_EXCL) → open the store (pragmas, migrations) → layer stored UI overrides on the file config → spawn workers → build the router → bind → serve until SIGTERM/Ctrl-C, with one stop flag shared by every listener and worker.

Logging: tracing + tracing-subscriber (env-filter), stderr, default info, structured fields. Never log tokens, passwords, cookies, or secrets.

3. Config

  • config/<app>.example.toml is committed. config/<app>.toml is gitignored. A missing file is created from the example (dev defaults) on first run.
  • #[serde(deny_unknown_fields)] on every struct. One Config::validate() for cross-field rules, used at load and when a UI override is saved.
  • Secrets never live in the TOML. They are entered in the admin UI (sealed in the DB) or in a separate file readable only by the service user.
  • Runtime settings: a settings key/value table with precedence UI override → file → built-in default, and each field marked Live, Restart or ReadOnly (forge server_settings.rs).

4. Store

  • One writer connection behind a tokio Mutex, plus a pool of 4 PRAGMA query_only readers. Pure reads use a reader; writes, transactions and read-then-write sequences use the writer.
  • Pragmas on every connection: journal_mode=WAL, synchronous=FULL, foreign_keys=ON, busy timeout 5 s. Read them back and log them at boot.
  • Migrations: crates/<app>-core/migrations/NNNN_snake_name.sql, each starting with a comment that says what it does; listed in store/migrate.rs as (version, include_str!(...)); each applied in its own transaction with a schema_migrations row. Never edit an applied migration.
  • Ids are ULID text. Timestamps are UTC RFC 3339 with 9 fractional digits and Z (fixed width, so text order is time order) from time.rs (now_stamp(), stamp_after(d)). Booleans are INTEGER 0/1 with a CHECK.
  • Column lists are constants (USER_COLS) next to their map_user(row); SQL uses ?1, ?2; ownership goes in the WHERE (... WHERE id = ?1 AND owner_id = ?2).
  • Multi-statement writes: unchecked_transaction() + an async block returning Result + one finish(tx, outcome) helper that commits or rolls back.
  • Constraints live in the schema (NOT NULL, CHECK, UNIQUE, REFERENCES ... ON DELETE ...), not only in Rust.
  • Backups: snapshot_to(path) with VACUUM INTO on the writer, then checkpoint the copy so it is one self-contained file, then fsync. admin backup --out DIR writes the snapshot, the blob tree (where the app has one), a manifest.json with a sha256 per file and a manifest.mac: HMAC-SHA256 of the manifest bytes under a subkey of the instance key, which lives outside the backup. Verify and restore check the MAC first (constant time), then hashes, integrity_check and contiguous migrations. Never copy a live DB file.

5. HTTP and pages

  • Routes with #[route(...)] / #[page(...)] and .discover(). Anything that must not be public is registered explicitly on a separate router.
  • Handler shape: (1) authenticate, (2) load and authorize, (3) build the view, (4) return it.
  • Forms: every field #[serde(default)]; every state-changing POST carries a csrf field checked in constant time before any side effect (require_csrf). Pre-session forms use the __Host-<app>_precsrf cookie (SameSite=Strict). Post/Redirect/Get with notices in the query string (?notice=...), not cookies.
  • Session cookie: __Host-<app>_session, random 32 bytes base64url; the DB stores only its SHA-256. HttpOnly, Secure, SameSite=Lax, Path=/.
  • safe_next() for every return path: one leading /, not // or /\, no control characters, ≤2048 bytes.
  • One security-headers layer on /: X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: same-origin, Strict-Transport-Security when the base URL is https, and Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'. No inline scripts or styles anywhere; all JS is in assets/*.js.
  • Styled 404 page for Accept: text/html; 404 for "missing" and for "exists but you may not see it".
  • Request bodies are capped per route (BodyLimit); upload routes stream.
  • Assets (CSS compiled from style/*.scss with grass in build.rs, JS, fonts) are embedded with include_str!/include_bytes!, served by routes with Cache-Control: public, max-age=31536000, immutable, and linked with a content-hash query (/assets/main.css?v=<12 hex>). Fonts are self-hosted. Nothing is loaded from a third-party origin.

6. Auth primitives

  • Passwords: iz holds none. People sign in at im, which owns passwords, second factors and their throttles.
  • Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with subtle; shown once.
  • Secrets at rest: seal/open with XChaCha20-Poly1305, v1: + base64(nonce || ciphertext). The instance key is never used directly: every use gets its own key, HMAC-SHA256(instance key, "
  • Client IP: none is read. iz ignores X-Forwarded-For; trusted_proxies is accepted, has no effect, and boot warns when it is set.

7. Authorization

One pure function per app, authz::authorize(actor, resource, role, action) -> Result<(), Denied>, with Denied::{NotFound, Forbidden}. Every page, form handler, API route and live stream goes through it. It is unit-tested as a truth table.

8. Live pages

  • LiveHub of watch::Sender<u64> per Topic (an enum keyed by what a page is about). Writes call live.bump(&topic) after commit.
  • A page that updates live renders data-live="<stream url>". The stream route authenticates and authorizes first, then stream_changes(cx, hub, topics, fingerprint): subscribe, read a fingerprint, and send a data-less event: changed only when the fingerprint changes. retry: 1000, keep-alive every 30 s, X-Accel-Buffering: no.
  • GET /-/alive is held by every page (anonymous-safe). It drives the "server restarting" bar and carries account events (sign-out, preference change) for the viewer.
  • assets/nav.js (one file, progressive enhancement): soft navigation for same-origin links and forms (data-hard opts out), keeps focus/scroll/typed input across swaps, opens one EventSource per distinct data-live URL, re-fetches the page on changed, reconnects after 1/2/3 s, never re-sends a POST. Pages work without JS.

9. Errors

  • One thiserror enum per crate: Io, Database, Migration, Config, Crypto, NotFound, Conflict(String), Forbidden(String), Invalid(String).
  • Invalid and Conflict text is for the user (shown as an alert). Everything else is a 500 with a generic page and a logged cause.
  • Security-sensitive answers are identical for "unknown" and "wrong".

10. Audit

Append-only audit_log (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data JSON). Written after the change commits; a failed audit write is logged and never fails the request. Never store secrets in data. Admin page with filters and keyset paging. Rows older than the retention window are removed by the sweeper; nothing else deletes them.

11. i18n

English and Turkish. Lang::{En, Tr}; resolution: the user's stored language, else Accept-Language, else English. Keys are enums per area with an exhaustive match on (key, lang), so a missing translation does not compile. Every page, including sign-in, error and mail text, is translated. Sentences with values use small format helpers, not concatenation in views.

12. Comments and naming

  • //! on every module: what it is, what it is not, the invariant it keeps. /// on every public item and on every policy constant (with its unit and reason). Inline comments explain why, in full sentences.
  • No commented-out code. No TODO without a line in docs/backlog.md.

13. Tests

Few and meaningful. Unit tests for pure logic that is easy to get wrong (authz truth table, token and CSRF compare, safe_next, parsers, time math, quota math), store tests on a real temp database (tempfile) for tricky queries and constraints, and one or two in-process router tests per security rule (CSRF refused, hidden resource is 404, admin page refuses members). No snapshot tests, no browser tests, no mocks of the database. Tests never write outside their temp dir.

14. Deploy

deploy/<app>.service: dedicated user, ProtectSystem=strict, ReadWritePaths= the data dir only, ProtectHome=yes, PrivateTmp=yes, PrivateDevices=yes, NoNewPrivileges=yes, CapabilityBoundingSet=, RestrictNamespaces=yes, RestrictSUIDSGID=yes, LockPersonality=yes, MemoryDenyWriteExecute=yes, SystemCallArchitectures=native, SystemCallFilter=@system-service, UMask=0077, Restart=on-failure. /healthz per contracts.md 4.1.

15. Git

Commit messages follow forge's style: gitmoji + type + description, for example ✨ feat: sign-in with TOTP and recovery codes, 🐛 fix: ..., ♻️ refactor: ..., 📝 docs: .... No co-author or "generated with" lines.