Files
visa/src/journal.rs
T
grabowski 16e4cdc73d
CI / secret scan (push) Successful in 7s
CI / fmt, clippy, tests (push) Successful in 45s
CI / release (push) Skipped
The legal practice: clients, lawyers, contracts, papers, the journal
Lanna Desk's larger work is contracts, general ones and artists', for
clients who are Thai or foreign, people or organizations, with several
lawyers in the team. The back office gets a Legal section (phase 9 in
docs/PLAN.md):

- Lawyers: license number, contact, the login of one who uses the app
  (then "My contracts"), in the team or left.
- Clients, as record cards: person or organization, names in English and
  Thai, stage name or brand, a Thai ID number (checked), a passport or a
  registration number, the lawyer in charge.
- Contracts: code LD-<year>-<n>, the general kinds and the artist kinds
  (recording, management, publishing, performance, license,
  merchandise), other party, status, lawyer, dates and value; a contract
  in force shows its notice day and its end ahead. Filters: general or
  artists, a lawyer, mine, those over.
- Versions: a text kept here, a file (PDF or scan, encrypted as the
  client's document) or both. They never change: the database refuses
  UPDATE and DELETE, a version's file cannot be deleted and no document's
  checksum can change. Any version reads against the one before as a
  line diff.
- Paper copies: the id <code>-P<n> to write on the paper or print as a
  90 x 50 mm label with a QR code; where it lies, its state and holder,
  each move journaled; found again by its id.
- The journal: every change in words, in the change's transaction, each
  entry chained to the one before by SHA-256. The database refuses to
  change, delete or truncate it; /journal checks the chain and every
  version's text and fingerprints against its entry, shows the last hash
  and exports CSV.

The sidebar groups its sections: Legal, Visas and stays, Office. Demo data
(seed-demo) adds three lawyers, six clients and seven contracts with
versions, papers and moves. Documents take a third owner, the client
(migration 0009).

Checks: fmt, clippy, 115 unit and 62 integration tests (new: versions and
the journal, the database refusing changes, a change around the app
breaking the chain, paper ids and moves, the demo checking whole);
screenshots of the new pages in light, dark and on a phone.
2026-11-21 23:20:20 +07:00

356 lines
11 KiB
Rust

//! The journal of the legal practice: every change to its lawyers, clients,
//! contracts, contract versions and paper copies, in order, as a ledger.
//! Each entry names the SHA-256 of the entry before it and has its own, over
//! its place in the chain, its time, who made it, what it is about and the
//! hash before: an entry changed or taken out later no longer matches, and
//! `verify` says where. The database refuses to change or delete entries
//! (migration 0009); the chain also shows a change made around that, by
//! someone with the database's own rights.
//!
//! A version's entry names the fingerprints (SHA-256) of its text and file,
//! so a version changed in the database, even with a new fingerprint, no
//! longer matches its journal entry either.
use anyhow::Result;
use chrono::{DateTime, SecondsFormat, Timelike, Utc};
use serde::Serialize;
use sqlx::{PgConnection, PgPool};
use crate::files;
/// The hash before the first entry.
pub const GENESIS: &str = "0000000000000000000000000000000000000000000000000000000000000000";
/// The advisory lock that orders appends, so two never take the same place.
const LOCK: i64 = 0x6c64_6a72_6e6c; // "ldjrnl"
/// What happened, to be written.
#[derive(Debug)]
pub struct New<'a> {
pub actor: &'a str,
pub client: Option<i64>,
pub contract: Option<i64>,
/// "contract added", "version added", "paper moved" ...
pub event: &'a str,
pub detail: String,
}
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
pub struct Entry {
pub seq: i64,
pub at: DateTime<Utc>,
pub actor: String,
pub client_id: Option<i64>,
pub contract_id: Option<i64>,
pub event: String,
pub detail: String,
pub prev_hash: String,
pub hash: String,
}
/// Each part with its length before it, so no two entries read the same.
fn part(out: &mut String, s: &str) {
out.push_str(&s.len().to_string());
out.push(':');
out.push_str(s);
out.push('\n');
}
fn opt(id: Option<i64>) -> String {
id.map(|i| i.to_string()).unwrap_or_default()
}
/// The entry's hash, from everything it says and the hash before it.
#[allow(clippy::too_many_arguments)]
pub fn hash_of(
seq: i64,
at: DateTime<Utc>,
actor: &str,
client: Option<i64>,
contract: Option<i64>,
event: &str,
detail: &str,
prev: &str,
) -> String {
let mut s = String::from("lanna desk journal v1\n");
part(&mut s, &seq.to_string());
part(&mut s, &at.to_rfc3339_opts(SecondsFormat::Micros, true));
part(&mut s, actor);
part(&mut s, &opt(client));
part(&mut s, &opt(contract));
part(&mut s, event);
part(&mut s, detail);
part(&mut s, prev);
files::sha256_hex(s.as_bytes())
}
impl Entry {
pub fn computed(&self) -> String {
hash_of(
self.seq,
self.at,
&self.actor,
self.client_id,
self.contract_id,
&self.event,
&self.detail,
&self.prev_hash,
)
}
}
/// The time to the microsecond, as the database keeps it.
fn now() -> DateTime<Utc> {
let t = Utc::now();
t.with_nanosecond(t.nanosecond() / 1000 * 1000).unwrap_or(t)
}
/// Appends an entry; call it in the transaction of the change it records,
/// so both commit or neither.
pub async fn append(conn: &mut PgConnection, e: &New<'_>) -> Result<Entry> {
sqlx::query("SELECT pg_advisory_xact_lock($1)")
.bind(LOCK)
.execute(&mut *conn)
.await?;
let last: Option<(i64, String)> =
sqlx::query_as("SELECT seq, hash FROM journal ORDER BY seq DESC LIMIT 1")
.fetch_optional(&mut *conn)
.await?;
let (seq, prev) = match last {
Some((s, h)) => (s + 1, h),
None => (1, GENESIS.to_string()),
};
let at = now();
let hash = hash_of(
seq, at, e.actor, e.client, e.contract, e.event, &e.detail, &prev,
);
Ok(sqlx::query_as(
"INSERT INTO journal (seq, at, actor, client_id, contract_id, event, detail, prev_hash, hash) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *",
)
.bind(seq)
.bind(at)
.bind(e.actor)
.bind(e.client)
.bind(e.contract)
.bind(e.event)
.bind(&e.detail)
.bind(&prev)
.bind(&hash)
.fetch_one(conn)
.await?)
}
/// The newest entries first, of one client or one contract or all.
pub async fn list(
db: &PgPool,
client: Option<i64>,
contract: Option<i64>,
limit: i64,
) -> Result<Vec<Entry>> {
Ok(sqlx::query_as(
"SELECT * FROM journal WHERE ($1::bigint IS NULL OR client_id = $1) \
AND ($2::bigint IS NULL OR contract_id = $2) ORDER BY seq DESC LIMIT $3",
)
.bind(client)
.bind(contract)
.bind(limit)
.fetch_all(db)
.await?)
}
/// Every entry, oldest first: the CSV export.
pub async fn all(db: &PgPool) -> Result<Vec<Entry>> {
Ok(sqlx::query_as("SELECT * FROM journal ORDER BY seq")
.fetch_all(db)
.await?)
}
/// What `verify` found.
#[derive(Clone, Debug, Serialize)]
pub struct Check {
pub entries: i64,
/// The last entry's hash: written down or exported, it pins the whole
/// journal up to then.
pub head: String,
pub head_at: Option<DateTime<Utc>>,
/// The problems, the first of the chain first; empty when all is whole.
pub problems: Vec<String>,
}
impl Check {
pub fn whole(&self) -> bool {
self.problems.is_empty()
}
}
/// Checks the chain from the first entry, and every contract version's
/// text and fingerprints against its entry.
pub async fn verify(db: &PgPool) -> Result<Check> {
let entries = all(db).await?;
let mut problems = Vec::new();
let mut prev = GENESIS.to_string();
for (i, e) in entries.iter().enumerate() {
let want = i as i64 + 1;
if e.seq != want {
problems.push(format!("Entry {want} is missing; the next is {}.", e.seq));
}
if e.prev_hash != prev {
problems.push(format!(
"Entry {} does not name the hash of the entry before it.",
e.seq
));
}
if e.computed() != e.hash {
problems.push(format!(
"Entry {} was changed after it was written: its hash no longer matches.",
e.seq
));
}
prev = e.hash.clone();
}
// the versions against their entries
#[derive(sqlx::FromRow)]
struct Kept {
contract_id: i64,
code: String,
version: i32,
body: String,
body_sha256: Option<String>,
file_sha256: Option<String>,
}
let versions: Vec<Kept> = sqlx::query_as(
"SELECT v.contract_id, c.code, v.version, v.body, v.body_sha256, v.file_sha256 \
FROM contract_versions v JOIN contracts c ON c.id = v.contract_id \
ORDER BY v.id",
)
.fetch_all(db)
.await?;
for k in versions {
let (contract, code, n) = (k.contract_id, k.code, k.version);
let (body, body_sha, file_sha) = (k.body, k.body_sha256, k.file_sha256);
if let Some(h) = &body_sha
&& files::sha256_hex(body.as_bytes()) != *h
{
problems.push(format!(
"{code} version {n}: the text no longer matches its fingerprint."
));
}
let tag = version_tag(n);
let entry = entries.iter().find(|e| {
e.contract_id == Some(contract)
&& e.event == "version added"
&& e.detail.starts_with(&tag)
});
match entry {
None => problems.push(format!("{code} version {n} has no entry in the journal.")),
Some(e) => {
for h in [&body_sha, &file_sha].into_iter().flatten() {
if !e.detail.contains(h.as_str()) {
problems.push(format!(
"{code} version {n}: its fingerprint differs from the one in journal entry {}.",
e.seq
));
}
}
}
}
}
let last = entries.last();
Ok(Check {
entries: entries.len() as i64,
head: last
.map(|e| e.hash.clone())
.unwrap_or_else(|| GENESIS.to_string()),
head_at: last.map(|e| e.at),
problems,
})
}
/// How a version's entry starts: "Version 3." (the check finds it so).
pub fn version_tag(n: i32) -> String {
format!("Version {n}.")
}
/// The journal as CSV, oldest first, for a copy kept elsewhere.
pub fn csv(entries: &[Entry]) -> String {
fn cell(s: &str) -> String {
if s.contains([',', '"', '\n', '\r']) {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
}
let mut out = String::from("seq,at,actor,client_id,contract_id,event,detail,prev_hash,hash\n");
for e in entries {
let row = [
e.seq.to_string(),
e.at.to_rfc3339_opts(SecondsFormat::Micros, true),
e.actor.clone(),
opt(e.client_id),
opt(e.contract_id),
e.event.clone(),
e.detail.clone(),
e.prev_hash.clone(),
e.hash.clone(),
];
out.push_str(&row.iter().map(|c| cell(c)).collect::<Vec<_>>().join(","));
out.push('\n');
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
#[test]
fn a_hash_names_everything_in_the_entry() {
let at = Utc.with_ymd_and_hms(2026, 11, 21, 10, 0, 0).unwrap();
let h = hash_of(1, at, "alex", Some(1), None, "client added", "x", GENESIS);
assert_eq!(h.len(), 64);
// any part changed, a different hash
assert_ne!(
h,
hash_of(2, at, "alex", Some(1), None, "client added", "x", GENESIS)
);
assert_ne!(
h,
hash_of(1, at, "alexa", Some(1), None, "client added", "x", GENESIS)
);
assert_ne!(
h,
hash_of(1, at, "alex", None, Some(1), "client added", "x", GENESIS)
);
assert_ne!(
h,
hash_of(1, at, "alex", Some(1), None, "client added", "y", GENESIS)
);
// the lengths keep the parts apart
assert_ne!(
hash_of(1, at, "ab", None, None, "c", "", GENESIS),
hash_of(1, at, "a", None, None, "bc", "", GENESIS)
);
}
#[test]
fn the_csv_quotes_what_needs_it() {
let at = Utc.with_ymd_and_hms(2026, 11, 21, 10, 0, 0).unwrap();
let e = Entry {
seq: 1,
at,
actor: "alex".into(),
client_id: Some(2),
contract_id: None,
event: "client added".into(),
detail: "Name: \"Demo\", Records".into(),
prev_hash: GENESIS.into(),
hash: GENESIS.into(),
};
let c = csv(&[e]);
assert!(c.contains(",\"Name: \"\"Demo\"\", Records\","), "{c}");
assert!(c.starts_with("seq,at,"));
}
}