254 lines
12 KiB
Python
254 lines
12 KiB
Python
"""
|
|
state_store.py — the small persistent "who was enabled before disabling" store.
|
|
|
|
Backs billing.py's rollback plan with a single shared SQLite file (path from
|
|
STATE_STORE_PATH) holding every tenant's data, scoped by tenant_slug on
|
|
every row — one file, not one file per tenant, since SQLite has no
|
|
meaningful per-tenant isolation benefit here and one file is simpler to
|
|
back up. SQLite is used instead of flat JSON specifically because writes
|
|
here gate whether re-enabling users later is safe — a single atomic
|
|
transaction per write avoids a half-written file if the container is killed
|
|
mid-write, at no added infrastructure cost.
|
|
|
|
Two tables, both keyed by tenant_slug so one tenant's data can never leak
|
|
into another's read — ENTERPRISE_STANDARDS.md's "enforce_tenant_scope
|
|
applied to every DB query for non-admin roles — no exceptions" rule,
|
|
applied here at the one place billing state actually persists:
|
|
snapshot — the current {username: {"roles": [...], "default_workspace":
|
|
...}} map to restore on payment success, per tenant. Always
|
|
fully replaced by save_snapshot() for that tenant, never
|
|
appended to — it represents one point-in-time fetch, not a
|
|
history.
|
|
action_log — append-only audit trail of every disable/enable attempt,
|
|
independent of snapshot's current contents, so "what did
|
|
this service actually do for this tenant" stays inspectable
|
|
after a snapshot has been cleared.
|
|
|
|
This file should be backed up daily to an off-server location — see
|
|
CLAUDE.md's Enterprise Standards Compliance section. That backup is a
|
|
deployment-level cron concern (e.g. `sqlite3 state.db ".backup"` + rsync)
|
|
outside this module's responsibility.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
from contextlib import contextmanager
|
|
from datetime import datetime, timezone
|
|
|
|
|
|
def _default_db_path():
|
|
"""Resolve the SQLite file path from STATE_STORE_PATH, defaulting to a local file for tests/dev."""
|
|
return os.environ.get("STATE_STORE_PATH", "state.db")
|
|
|
|
|
|
class StateStore:
|
|
"""
|
|
Wraps one SQLite file holding the current restore snapshot and an
|
|
append-only action log, scoped to exactly one tenant.
|
|
|
|
Data flow:
|
|
tenant_slug (str) — required; every method reads/writes only this
|
|
tenant's rows, so one tenant's billing state can
|
|
never be read or overwritten by another's
|
|
db_path (str) — filesystem path to the shared SQLite file;
|
|
created on first use
|
|
methods below — read/write the snapshot and action_log tables,
|
|
always filtered to self.tenant_slug
|
|
"""
|
|
|
|
def __init__(self, tenant_slug, db_path=None):
|
|
if not tenant_slug:
|
|
raise ValueError("tenant_slug is required — StateStore is never tenant-unscoped")
|
|
self.tenant_slug = tenant_slug
|
|
self.db_path = db_path or _default_db_path()
|
|
self._init_schema()
|
|
|
|
@contextmanager
|
|
def _connect(self):
|
|
"""Open a connection for one unit of work, committing on success and rolling back on error."""
|
|
conn = sqlite3.connect(self.db_path)
|
|
try:
|
|
yield conn
|
|
conn.commit()
|
|
except Exception:
|
|
conn.rollback()
|
|
raise
|
|
finally:
|
|
conn.close()
|
|
|
|
def _init_schema(self):
|
|
"""
|
|
Creates the snapshot and action_log tables if they don't already exist.
|
|
|
|
Steps:
|
|
1. Open a connection
|
|
2. Migrate away any pre-multi-tenant-refactor table still on disk
|
|
(see _migrate_pre_tenant_table) — "CREATE TABLE IF NOT EXISTS"
|
|
below is a silent no-op against an existing table with the old,
|
|
tenant_slug-less schema, which is exactly what caused this
|
|
method to leave stale tables in place after the multi-tenant
|
|
refactor shipped
|
|
3. Create the snapshot table (one row per stored username per tenant)
|
|
4. Create the action_log table (append-only, autoincrement id, per tenant)
|
|
"""
|
|
with self._connect() as conn:
|
|
# Step 2: guard against the exact silent-schema-mismatch bug described above
|
|
self._migrate_pre_tenant_table(conn, "snapshot")
|
|
self._migrate_pre_tenant_table(conn, "action_log")
|
|
self._migrate_missing_restore_state_column(conn)
|
|
# Step 3: snapshot rows are the current restore list per tenant, no history
|
|
conn.execute(
|
|
"CREATE TABLE IF NOT EXISTS snapshot ("
|
|
"tenant_slug TEXT NOT NULL, "
|
|
"username TEXT NOT NULL, "
|
|
"restore_state TEXT NOT NULL, "
|
|
"PRIMARY KEY (tenant_slug, username)"
|
|
")"
|
|
)
|
|
# Step 4: action_log rows are never updated or deleted
|
|
conn.execute(
|
|
"CREATE TABLE IF NOT EXISTS action_log ("
|
|
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
|
|
"tenant_slug TEXT NOT NULL, "
|
|
"timestamp TEXT NOT NULL, "
|
|
"trace_id TEXT NOT NULL, "
|
|
"action TEXT NOT NULL, "
|
|
"username TEXT, "
|
|
"status TEXT NOT NULL"
|
|
")"
|
|
)
|
|
|
|
@staticmethod
|
|
def _migrate_pre_tenant_table(conn, table_name):
|
|
"""
|
|
Drops `table_name` if it's a leftover from the pre-multi-tenant
|
|
schema (no tenant_slug column) and holds no rows — safe, since an
|
|
empty table carries nothing to lose either way, and the subsequent
|
|
CREATE TABLE IF NOT EXISTS then recreates it with the current
|
|
schema.
|
|
|
|
Refuses to touch a same-shaped table that actually holds rows: that
|
|
data belongs to a tenant we can no longer identify (the old schema
|
|
never recorded one), so guessing would risk misattributing or
|
|
silently dropping real billing state. Raises instead, naming the
|
|
table, so an operator migrates it by hand exactly once.
|
|
"""
|
|
row = conn.execute(
|
|
"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", (table_name,)
|
|
).fetchone()
|
|
if row is None:
|
|
return # table doesn't exist yet — nothing to migrate
|
|
columns = {col[1] for col in conn.execute(f"PRAGMA table_info({table_name})")}
|
|
if "tenant_slug" in columns:
|
|
return # already on the current schema
|
|
(row_count,) = conn.execute(f"SELECT COUNT(*) FROM {table_name}").fetchone()
|
|
if row_count > 0:
|
|
raise RuntimeError(
|
|
f"StateStore: '{table_name}' predates the multi-tenant schema and still holds "
|
|
f"{row_count} row(s) with no tenant_slug to attribute them to — refusing to guess. "
|
|
"Migrate this table by hand (back it up, then either assign every existing row to "
|
|
"the one tenant it actually belongs to, or drop it if the data is no longer needed) "
|
|
"before this service will start."
|
|
)
|
|
conn.execute(f"DROP TABLE {table_name}")
|
|
|
|
@staticmethod
|
|
def _migrate_missing_restore_state_column(conn):
|
|
"""
|
|
Drops the `snapshot` table if it predates the current restore_state
|
|
column (this covers both the pre-role-swap "roles"-only schema and
|
|
the intermediate one that stored Roles but not default_workspace —
|
|
both lack `restore_state`) and holds no rows — safe, since CREATE
|
|
TABLE IF NOT EXISTS won't touch an already-existing table on its
|
|
own, and an empty table carries nothing to lose.
|
|
|
|
Refuses (loud RuntimeError) if that old-shaped table still holds
|
|
rows: those usernames have no recorded restore state, so guessing
|
|
would risk leaving a real client's staff permanently locked out.
|
|
"""
|
|
row = conn.execute(
|
|
"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'snapshot'"
|
|
).fetchone()
|
|
if row is None:
|
|
return # table doesn't exist yet — nothing to migrate
|
|
columns = {col[1] for col in conn.execute("PRAGMA table_info(snapshot)")}
|
|
if "restore_state" in columns:
|
|
return # already on the current schema
|
|
(row_count,) = conn.execute("SELECT COUNT(*) FROM snapshot").fetchone()
|
|
if row_count > 0:
|
|
raise RuntimeError(
|
|
"StateStore: 'snapshot' predates the current restore_state column and still holds "
|
|
f"{row_count} row(s) with no recorded restore state — refusing to guess. "
|
|
"Manually restore each listed username's real Roles/default_workspace in Frappe, "
|
|
"then clear this table, before this service will start."
|
|
)
|
|
conn.execute("DROP TABLE snapshot")
|
|
|
|
def save_snapshot(self, entries):
|
|
"""
|
|
Replaces this tenant's stored snapshot with exactly the given
|
|
{username: {"roles": [...], "default_workspace": ...}} map.
|
|
|
|
Data flow:
|
|
entries (dict[str, dict]) — every username about to be locked
|
|
out, mapped to their real restore
|
|
state right now, from billing.py's
|
|
Step 1
|
|
returns (None)
|
|
|
|
Steps:
|
|
1. Delete this tenant's existing snapshot rows (a snapshot is a
|
|
single point-in-time map, not something to accumulate)
|
|
2. Insert the new map, one row per username, restore state
|
|
JSON-encoded, tagged with this tenant's slug
|
|
"""
|
|
with self._connect() as conn:
|
|
# Step 1: clear this tenant's previous snapshot before writing the new one
|
|
conn.execute("DELETE FROM snapshot WHERE tenant_slug = ?", (self.tenant_slug,))
|
|
# Step 2: insert the fetched map as the new restore point, scoped to this tenant
|
|
conn.executemany(
|
|
"INSERT INTO snapshot (tenant_slug, username, restore_state) VALUES (?, ?, ?)",
|
|
[(self.tenant_slug, username, json.dumps(state)) for username, state in entries.items()],
|
|
)
|
|
|
|
def get_snapshot(self):
|
|
"""
|
|
Returns this tenant's currently stored restore map.
|
|
|
|
Data flow:
|
|
returns (dict[str, dict]) — {username: {"roles": [...], "default_workspace": ...}}
|
|
from this tenant's last
|
|
save_snapshot() call, or an empty
|
|
dict if none is stored
|
|
"""
|
|
with self._connect() as conn:
|
|
rows = conn.execute(
|
|
"SELECT username, restore_state FROM snapshot WHERE tenant_slug = ?", (self.tenant_slug,)
|
|
).fetchall()
|
|
return {username: json.loads(state_json) for username, state_json in rows}
|
|
|
|
def clear_snapshot(self):
|
|
"""Removes this tenant's stored snapshot — called once every listed user has been successfully re-enabled."""
|
|
with self._connect() as conn:
|
|
conn.execute("DELETE FROM snapshot WHERE tenant_slug = ?", (self.tenant_slug,))
|
|
|
|
def log_action(self, trace_id, action, status, username=None):
|
|
"""
|
|
Appends one row to this tenant's audit trail. Never updates or
|
|
deletes existing rows.
|
|
|
|
Data flow:
|
|
trace_id (str) — this request's trace id, for cross-referencing logs
|
|
action (str) — e.g. "snapshot_saved", "user_disabled", "user_reenabled"
|
|
status (str) — "success" or "failure"
|
|
username (str | None) — the affected username, if any
|
|
returns (None)
|
|
"""
|
|
with self._connect() as conn:
|
|
conn.execute(
|
|
"INSERT INTO action_log (tenant_slug, timestamp, trace_id, action, username, status) "
|
|
"VALUES (?, ?, ?, ?, ?, ?)",
|
|
(self.tenant_slug, datetime.now(timezone.utc).isoformat(), trace_id, action, username, status),
|
|
)
|