askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_session_lookup_cache.py · 12.3 KB · 303 lines
| 1 | """The parsed-session cache behind resolve_session_token. |
| 2 | |
| 3 | The cache stores parsed rows keyed on the sessions file's stat signature and |
| 4 | is dropped by every in-module write. It must never change what a lookup |
| 5 | returns, so the last test compares it with the pre-cache implementation from |
| 6 | git across randomized session files. |
| 7 | """ |
| 8 | |
| 9 | import importlib.util |
| 10 | import os |
| 11 | import random |
| 12 | import subprocess |
| 13 | import sys |
| 14 | from datetime import datetime, timedelta, timezone |
| 15 | from pathlib import Path |
| 16 | from types import SimpleNamespace |
| 17 | |
| 18 | import pytest |
| 19 | |
| 20 | import object_identity |
| 21 | |
| 22 | REPO = Path(__file__).resolve().parent.parent |
| 23 | NOW = datetime(2026, 1, 1, tzinfo=timezone.utc) |
| 24 | |
| 25 | |
| 26 | @pytest.fixture(autouse=True) |
| 27 | def _cache_everything(monkeypatch): |
| 28 | """Cache freshly written files (the racy-file guard is tested separately).""" |
| 29 | monkeypatch.setattr(object_identity, "_SESSION_CACHE_RACY_NS", 0) |
| 30 | object_identity._SESSION_CACHE.clear() |
| 31 | yield |
| 32 | object_identity._SESSION_CACHE.clear() |
| 33 | |
| 34 | |
| 35 | @pytest.fixture |
| 36 | def parse_count(monkeypatch): |
| 37 | calls = [] |
| 38 | real = object_identity._parse_sessions_file |
| 39 | |
| 40 | def counting(path): |
| 41 | calls.append(path) |
| 42 | return real(path) |
| 43 | |
| 44 | monkeypatch.setattr(object_identity, "_parse_sessions_file", counting) |
| 45 | return calls |
| 46 | |
| 47 | |
| 48 | def _make(tmp_path, user="u_1", ttl=3600, now=NOW): |
| 49 | return object_identity.create_session( |
| 50 | {"user_id": user, "ttl_seconds": ttl}, base_dir=tmp_path, now=now |
| 51 | ) |
| 52 | |
| 53 | |
| 54 | def _resolve(token, tmp_path, now=NOW): |
| 55 | return object_identity.resolve_session_token(token, base_dir=tmp_path, now=now) |
| 56 | |
| 57 | |
| 58 | def test_second_lookup_does_not_reparse(tmp_path, parse_count): |
| 59 | made = _make(tmp_path) |
| 60 | parse_count.clear() |
| 61 | for _ in range(5): |
| 62 | assert _resolve(made["token"], tmp_path).session_id == made["session"]["session_id"] |
| 63 | assert len(parse_count) == 1 |
| 64 | assert _resolve("unknown-token", tmp_path) is None |
| 65 | assert len(parse_count) == 1 |
| 66 | |
| 67 | |
| 68 | def test_session_created_after_cached_lookup_is_found(tmp_path, parse_count): |
| 69 | first = _make(tmp_path, "u_1") |
| 70 | assert _resolve(first["token"], tmp_path) is not None |
| 71 | second = _make(tmp_path, "u_2") |
| 72 | assert _resolve(second["token"], tmp_path).user_id == "u_2" |
| 73 | assert _resolve(first["token"], tmp_path).user_id == "u_1" |
| 74 | |
| 75 | |
| 76 | def test_revoked_session_stops_resolving_immediately(tmp_path): |
| 77 | made = _make(tmp_path) |
| 78 | assert _resolve(made["token"], tmp_path) is not None |
| 79 | object_identity.revoke_session(made["session"]["session_id"], base_dir=tmp_path, now=NOW) |
| 80 | assert _resolve(made["token"], tmp_path) is None |
| 81 | |
| 82 | |
| 83 | def test_revoke_user_sessions_stops_resolving_immediately(tmp_path): |
| 84 | a, b = _make(tmp_path, "u_1"), _make(tmp_path, "u_1") |
| 85 | keep = _make(tmp_path, "u_2") |
| 86 | for made in (a, b, keep): |
| 87 | assert _resolve(made["token"], tmp_path) is not None |
| 88 | assert object_identity.revoke_user_sessions("u_1", base_dir=tmp_path, now=NOW) == 2 |
| 89 | assert _resolve(a["token"], tmp_path) is None |
| 90 | assert _resolve(b["token"], tmp_path) is None |
| 91 | assert _resolve(keep["token"], tmp_path) is not None |
| 92 | |
| 93 | |
| 94 | def test_expiry_is_judged_against_now_without_file_change(tmp_path, parse_count): |
| 95 | made = _make(tmp_path, ttl=60) |
| 96 | expires = datetime.fromisoformat(made["session"]["expires_at"].replace("Z", "+00:00")) |
| 97 | assert _resolve(made["token"], tmp_path, now=expires - timedelta(seconds=1)) is not None |
| 98 | parse_count.clear() |
| 99 | assert _resolve(made["token"], tmp_path, now=expires) is None |
| 100 | assert _resolve(made["token"], tmp_path, now=expires + timedelta(days=1)) is None |
| 101 | assert _resolve(made["token"], tmp_path, now=expires - timedelta(seconds=1)) is not None |
| 102 | assert len(parse_count) == 0 |
| 103 | |
| 104 | |
| 105 | def test_expired_first_match_wins_over_active_duplicate(tmp_path): |
| 106 | made = _make(tmp_path, ttl=60) |
| 107 | path = object_identity.sessions_path(tmp_path) |
| 108 | rows = object_identity._parse_sessions_file(path) |
| 109 | later = object_identity.replace( |
| 110 | rows[0], |
| 111 | session_id="11111111-1111-4111-8111-111111111111", |
| 112 | expires_at="2099-01-01T00:00:00Z", |
| 113 | ) |
| 114 | object_identity._write_sessions(path, [rows[0], later]) |
| 115 | after_expiry = NOW + timedelta(hours=2) |
| 116 | assert _resolve(made["token"], tmp_path, now=after_expiry) is None |
| 117 | |
| 118 | |
| 119 | def test_external_rewrite_is_picked_up(tmp_path, parse_count): |
| 120 | made = _make(tmp_path) |
| 121 | other = _make(tmp_path, "u_2") |
| 122 | path = object_identity.sessions_path(tmp_path) |
| 123 | assert _resolve(made["token"], tmp_path) is not None |
| 124 | original = path.read_text() |
| 125 | |
| 126 | # Another process truncates the file in place to a single session. |
| 127 | header, first, second = original.splitlines(keepends=True) |
| 128 | path.write_text(header + second) |
| 129 | assert _resolve(made["token"], tmp_path) is None |
| 130 | assert _resolve(other["token"], tmp_path) is not None |
| 131 | |
| 132 | |
| 133 | def test_external_same_size_rewrite_is_picked_up(tmp_path): |
| 134 | made = _make(tmp_path) |
| 135 | path = object_identity.sessions_path(tmp_path) |
| 136 | assert _resolve(made["token"], tmp_path) is not None |
| 137 | before = path.stat() |
| 138 | text = path.read_bytes() |
| 139 | # Same-length edit: swap one hex digit of the stored hash so it no longer |
| 140 | # matches, then restore mtime so only size/ino/ctime could tell. |
| 141 | marker = b"sha256:" |
| 142 | index = text.index(marker) + len(marker) |
| 143 | flipped = b"0" if text[index : index + 1] != b"0" else b"1" |
| 144 | path.write_bytes(text[:index] + flipped + text[index + 1 :]) |
| 145 | os.utime(path, ns=(before.st_atime_ns, before.st_mtime_ns)) |
| 146 | assert path.stat().st_size == before.st_size |
| 147 | assert path.stat().st_mtime_ns == before.st_mtime_ns |
| 148 | assert _resolve(made["token"], tmp_path) is None |
| 149 | |
| 150 | |
| 151 | def test_fresh_file_is_not_trusted_inside_racy_window(tmp_path, monkeypatch, parse_count): |
| 152 | monkeypatch.setattr(object_identity, "_SESSION_CACHE_RACY_NS", 10**18) |
| 153 | made = _make(tmp_path) |
| 154 | path = object_identity.sessions_path(tmp_path) |
| 155 | before = path.stat() |
| 156 | parse_count.clear() |
| 157 | assert _resolve(made["token"], tmp_path) is not None |
| 158 | assert _resolve(made["token"], tmp_path) is not None |
| 159 | assert len(parse_count) == 2 # never cached while the file is that young |
| 160 | text = path.read_bytes() |
| 161 | index = text.index(b"sha256:") + len(b"sha256:") |
| 162 | flipped = b"0" if text[index : index + 1] != b"0" else b"1" |
| 163 | path.write_bytes(text[:index] + flipped + text[index + 1 :]) |
| 164 | os.utime(path, ns=(before.st_atime_ns, before.st_mtime_ns)) |
| 165 | assert _resolve(made["token"], tmp_path) is None |
| 166 | |
| 167 | |
| 168 | def test_in_module_write_drops_entry_even_if_stat_is_identical(tmp_path, monkeypatch): |
| 169 | made = _make(tmp_path) |
| 170 | path = object_identity.sessions_path(tmp_path) |
| 171 | assert _resolve(made["token"], tmp_path) is not None |
| 172 | assert str(path) in object_identity._SESSION_CACHE |
| 173 | # Make the stat check blind, as it would be on a coarse-timestamp filesystem. |
| 174 | frozen = os.stat(path) |
| 175 | monkeypatch.setattr(object_identity, "os", SimpleNamespace(stat=lambda p: frozen)) |
| 176 | rows = object_identity._parse_sessions_file(path) |
| 177 | object_identity._write_sessions(path, [object_identity.replace(rows[0], revoked_at="2026-01-01T00:00:00Z")]) |
| 178 | assert str(path) not in object_identity._SESSION_CACHE |
| 179 | assert _resolve(made["token"], tmp_path) is None |
| 180 | |
| 181 | |
| 182 | def test_missing_file_and_deleted_file(tmp_path): |
| 183 | assert _resolve("anything", tmp_path) is None |
| 184 | made = _make(tmp_path) |
| 185 | assert _resolve(made["token"], tmp_path) is not None |
| 186 | object_identity.sessions_path(tmp_path).unlink() |
| 187 | assert _resolve(made["token"], tmp_path) is None |
| 188 | assert object_identity._read_sessions(object_identity.sessions_path(tmp_path)) == [] |
| 189 | |
| 190 | |
| 191 | def test_corrupt_rows_are_still_skipped(tmp_path): |
| 192 | made = _make(tmp_path) |
| 193 | path = object_identity.sessions_path(tmp_path) |
| 194 | with path.open("a") as handle: |
| 195 | handle.write("not-a-uuid\tsha256:" + "a" * 64 + "\tu_9\t\t[]\t[]\t\t2026-01-01T00:00:00Z\t2099-01-01T00:00:00Z\t\n") |
| 196 | handle.write("garbage line without tabs\n") |
| 197 | handle.write("\n") |
| 198 | assert _resolve(made["token"], tmp_path) is not None |
| 199 | assert len(object_identity._read_sessions(path)) == 1 |
| 200 | assert len(object_identity.list_sessions(base_dir=tmp_path)) == 1 |
| 201 | |
| 202 | |
| 203 | def test_mutating_returned_list_does_not_change_lookups(tmp_path): |
| 204 | made = _make(tmp_path) |
| 205 | path = object_identity.sessions_path(tmp_path) |
| 206 | assert _resolve(made["token"], tmp_path) is not None |
| 207 | returned = object_identity._read_sessions(path) |
| 208 | returned.clear() |
| 209 | assert _resolve(made["token"], tmp_path) is not None |
| 210 | again = object_identity._read_sessions(path) |
| 211 | assert again is not returned and len(again) == 1 |
| 212 | again.append(again[0]) |
| 213 | assert len(object_identity._read_sessions(path)) == 1 |
| 214 | |
| 215 | |
| 216 | def test_cache_holds_one_entry_per_path_and_is_bounded(tmp_path, monkeypatch): |
| 217 | monkeypatch.setattr(object_identity, "_SESSION_CACHE_MAX_PATHS", 3) |
| 218 | for index in range(8): |
| 219 | base = tmp_path / f"b{index}" |
| 220 | made = _make(base) |
| 221 | assert _resolve(made["token"], base) is not None |
| 222 | assert _resolve(made["token"], base) is not None |
| 223 | assert len(object_identity._SESSION_CACHE) <= 3 |
| 224 | |
| 225 | |
| 226 | # --- equivalence with the pre-cache implementation ------------------------- |
| 227 | |
| 228 | |
| 229 | def _load_original(scratch): |
| 230 | source = subprocess.run( |
| 231 | ["git", "show", "HEAD:object_identity.py"], |
| 232 | cwd=REPO, capture_output=True, text=True, check=True, |
| 233 | ).stdout |
| 234 | tmp = scratch / "original_object_identity.py" # never written into the checkout |
| 235 | try: |
| 236 | tmp.write_text(source) |
| 237 | spec = importlib.util.spec_from_file_location("object_identity_original", tmp) |
| 238 | module = importlib.util.module_from_spec(spec) |
| 239 | sys.modules["object_identity_original"] = module |
| 240 | spec.loader.exec_module(module) |
| 241 | finally: |
| 242 | tmp.unlink(missing_ok=True) |
| 243 | return module |
| 244 | |
| 245 | |
| 246 | def test_equivalent_to_original_implementation(tmp_path): |
| 247 | try: |
| 248 | original = _load_original(tmp_path) |
| 249 | except (subprocess.CalledProcessError, FileNotFoundError): |
| 250 | pytest.skip("git history for object_identity.py is unavailable") |
| 251 | if not hasattr(original, "_read_sessions") or hasattr(original, "_parse_sessions_file"): |
| 252 | pytest.skip("HEAD already contains the cache; nothing to compare against") |
| 253 | |
| 254 | rng = random.Random(20260101) |
| 255 | cases = 0 |
| 256 | for trial in range(300): |
| 257 | base = tmp_path / f"t{trial}" |
| 258 | rows, tokens = [], [] |
| 259 | for n in range(rng.randint(0, 12)): |
| 260 | token = f"tok-{trial}-{n}" |
| 261 | kind = rng.choice(["active", "expired", "revoked", "dup"]) |
| 262 | created = NOW |
| 263 | expires = NOW + timedelta(hours=1 if kind != "expired" else -1) |
| 264 | if kind == "dup" and rows: |
| 265 | token = tokens[rng.randrange(len(tokens))] |
| 266 | expires = NOW + timedelta(hours=rng.choice([-1, 1])) |
| 267 | session = object_identity.IdentitySession( |
| 268 | session_id=str(__import__("uuid").UUID(int=rng.getrandbits(128), version=4)), |
| 269 | token_hash=object_identity.hash_token(token), |
| 270 | user_id=f"u_{n}", |
| 271 | account_id=None, |
| 272 | roles=("r",), |
| 273 | subscriptions=(), |
| 274 | label="", |
| 275 | created_at=object_identity._format_timestamp(created), |
| 276 | expires_at=object_identity._format_timestamp(expires), |
| 277 | revoked_at=object_identity._format_timestamp(NOW) if kind == "revoked" else None, |
| 278 | ) |
| 279 | rows.append(session) |
| 280 | tokens.append(token) |
| 281 | path = object_identity.sessions_path(base) |
| 282 | object_identity._write_sessions(path, rows) |
| 283 | with path.open("a") as handle: |
| 284 | for junk in rng.sample( |
| 285 | ["bad\trow\n", "\n", "x" * 36 + "\tsha256:zz\n", "not-uuid\t" + "sha256:" + "b" * 64 + "\n"], |
| 286 | k=rng.randint(0, 3), |
| 287 | ): |
| 288 | handle.write(junk) |
| 289 | probes = tokens + ["unknown", "", None, "tok-missing"] |
| 290 | for token in probes: |
| 291 | for now in (NOW, NOW + timedelta(hours=2), NOW - timedelta(hours=2)): |
| 292 | # Twice: the second call is served from the cache. |
| 293 | for _ in range(2): |
| 294 | old = original.resolve_session_token(token, base_dir=base, now=now) |
| 295 | new = object_identity.resolve_session_token(token, base_dir=base, now=now) |
| 296 | assert (old is None) == (new is None), (trial, token, now) |
| 297 | if old is not None: |
| 298 | assert old.session_id == new.session_id |
| 299 | assert old.token_hash == new.token_hash |
| 300 | assert old.expires_at == new.expires_at |
| 301 | assert old.revoked_at == new.revoked_at |
| 302 | cases += 1 |
| 303 | assert cases >= 1000 |