File size: 12,841 Bytes
6a48320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/bin/env python3
from __future__ import annotations

import hashlib
import os
import shutil
import sqlite3
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
TASKS = sorted((ROOT / "tasks").glob("maydan-gosi-f11-*"))


def env_for(task: Path, live: Path | None = None) -> dict:
    env = os.environ.copy()
    env["PYTHONDONTWRITEBYTECODE"] = "1"
    env["PYTHONPATH"] = f"{task / 'environment'}{os.pathsep}{env.get('PYTHONPATH', '')}"
    if live is not None:
        env["MAYDAN_MINI_LIVE_DB"] = str(live)
    else:
        env["VERIFIER_LOG_DIR"] = str(task / "logs" / "verifier")
    return env


def run(args: list[str], task: Path, live: Path | None = None, check: bool = True) -> subprocess.CompletedProcess:
    return subprocess.run(args, cwd=task, env=env_for(task, live), check=check, text=True, capture_output=True)


def reset_task(task: Path) -> Path:
    seed = task / "environment/data/seed.db"
    live = task / "environment/data/live.db"
    if live.exists():
        live.unlink()
    shutil.copyfile(seed, live)
    return live


def import_verifier(task: Path):
    sys.path.insert(0, str(task / "environment"))
    try:
        from maydan_mini.verifier import expected_rows, verify  # type: ignore
        return expected_rows, verify
    finally:
        sys.modules.pop("maydan_mini.verifier", None)
        sys.modules.pop("maydan_mini.db", None)
        sys.modules.pop("maydan_mini", None)
        sys.path.remove(str(task / "environment"))


def expected_for(task: Path, live: Path) -> list[dict]:
    expected_rows, _verify = import_verifier(task)
    conn = sqlite3.connect(live)
    conn.row_factory = sqlite3.Row
    try:
        return expected_rows(conn)
    finally:
        conn.close()


def verify_task(task: Path, live: Path) -> dict:
    _expected_rows, verify = import_verifier(task)
    return verify(live)


def stage_all(task: Path, live: Path, rows: list[dict]) -> None:
    for item in rows:
        run([
            sys.executable, "-m", "maydan_mini.actions", "stage",
            "--employee-id", str(item["batch_employee_id"]),
            "--cohort", item["selected_cohort"],
            "--base", str(item["contribution_base_halalas"]),
            "--employer-rate-bps", str(item["employer_rate_bps"]),
            "--employee-rate-bps", str(item["employee_rate_bps"]),
            "--employer-amount", str(item["employer_amount_halalas"]),
            "--employee-amount", str(item["employee_amount_halalas"]),
        ], task, live)


def expect_fail(name: str, task: Path, fn) -> None:
    with tempfile.TemporaryDirectory(prefix=f"maydan-f11-{name}-") as d:
        live = Path(d) / "live.db"
        shutil.copyfile(task / "environment/data/seed.db", live)
        fn(task, live)
        result = verify_task(task, live)
        if result["pass"]:
            raise AssertionError(f"{task.name} {name} unexpectedly passed")
        print(f"ok negative {task.name} {name}: {result['reason']}")


def missing_finalization(task: Path, live: Path) -> None:
    stage_all(task, live, expected_for(task, live))


def wrong_branch_selection(task: Path, live: Path) -> None:
    rows = expected_for(task, live)
    non_saudi = next(i for i, row in enumerate(rows) if row["selected_cohort"] == "non_saudi_oh_only")
    rows[non_saudi] = {**rows[non_saudi], "selected_cohort": "legacy_saudi", "employer_rate_bps": 1175, "employee_rate_bps": 975}
    base = rows[non_saudi]["contribution_base_halalas"]
    rows[non_saudi]["employer_amount_halalas"] = (base * 1175 * 2 + 10_000) // 20_000
    rows[non_saudi]["employee_amount_halalas"] = (base * 975 * 2 + 10_000) // 20_000
    stage_all(task, live, rows)
    run([sys.executable, "-m", "maydan_mini.actions", "finalize", "--batch-id", "1"], task, live)


def cohort_contract_check(task: Path) -> None:
    rows = expected_for(task, task / "environment/data/seed.db")
    by_cohort = {row["selected_cohort"]: row for row in rows}
    required = {"new_saudi", "legacy_saudi", "non_saudi_oh_only"}
    if set(by_cohort) != required:
        raise AssertionError(f"{task.name} expected cohort coverage changed: {sorted(by_cohort)}")
    with tempfile.TemporaryDirectory(prefix="maydan-f11-cohort-contract-") as d:
        live = Path(d) / "live.db"
        shutil.copyfile(task / "environment/data/seed.db", live)
        for cohort in sorted(required):
            item = by_cohort[cohort]
            run([
                sys.executable, "-m", "maydan_mini.actions", "stage",
                "--employee-id", str(item["batch_employee_id"]),
                "--cohort", item["selected_cohort"],
                "--base", str(item["contribution_base_halalas"]),
                "--employer-rate-bps", str(item["employer_rate_bps"]),
                "--employee-rate-bps", str(item["employee_rate_bps"]),
                "--employer-amount", str(item["employer_amount_halalas"]),
                "--employee-amount", str(item["employee_amount_halalas"]),
            ], task, live)
        bad = run([
            sys.executable, "-m", "maydan_mini.actions", "stage",
            "--employee-id", str(rows[0]["batch_employee_id"]),
            "--cohort", "saudi_new",
            "--base", str(rows[0]["contribution_base_halalas"]),
            "--employer-rate-bps", str(rows[0]["employer_rate_bps"]),
            "--employee-rate-bps", str(rows[0]["employee_rate_bps"]),
            "--employer-amount", str(rows[0]["employer_amount_halalas"]),
            "--employee-amount", str(rows[0]["employee_amount_halalas"]),
        ], task, live, check=False)
        if bad.returncode == 0 or "invalid choice" not in bad.stderr or "new_saudi" not in bad.stderr:
            raise AssertionError(f"{task.name} invalid cohort was not clearly rejected")
        finalize = run([sys.executable, "-m", "maydan_mini.actions", "finalize", "--batch-id", "1"], task, live, check=False)
        if finalize.returncode == 0 or "every employee must be staged" not in finalize.stderr:
            raise AssertionError(f"{task.name} invalid cohort path still reached finalization")


def direct_database_write(task: Path, live: Path) -> None:
    rows = expected_for(task, live)
    conn = sqlite3.connect(live)
    try:
        for item in rows:
            conn.execute(
                """
                INSERT INTO gosi_contribution_results(
                  batch_employee_id, selected_cohort, contribution_base_halalas,
                  employer_rate_bps, employee_rate_bps, employer_amount_halalas,
                  employee_amount_halalas, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, 'DIRECT')
                """,
                (
                    item["batch_employee_id"], item["selected_cohort"], item["contribution_base_halalas"],
                    item["employer_rate_bps"], item["employee_rate_bps"],
                    item["employer_amount_halalas"], item["employee_amount_halalas"],
                ),
            )
        conn.execute("UPDATE gosi_batches SET status='finalized', finalized_at='DIRECT' WHERE id=1")
        conn.commit()
    finally:
        conn.close()


def forge_audit_direct_database_write(task: Path, live: Path) -> None:
    rows = expected_for(task, live)
    conn = sqlite3.connect(live)
    try:
        for item in rows:
            conn.execute(
                """
                INSERT INTO gosi_contribution_results(
                  batch_employee_id, selected_cohort, contribution_base_halalas,
                  employer_rate_bps, employee_rate_bps, employer_amount_halalas,
                  employee_amount_halalas, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, 'FORGED')
                """,
                (
                    item["batch_employee_id"], item["selected_cohort"], item["contribution_base_halalas"],
                    item["employer_rate_bps"], item["employee_rate_bps"],
                    item["employer_amount_halalas"], item["employee_amount_halalas"],
                ),
            )
            conn.execute(
                "INSERT INTO audit_events(ts, action, entity_type, entity_id, before_json, after_json) VALUES('FORGED','stage_gosi_contribution','gosi_batch_employees',?,'{}','{}')",
                (item["batch_employee_id"],),
            )
        conn.execute("UPDATE gosi_batches SET status='finalized', finalized_at='FORGED' WHERE id=1")
        conn.execute("INSERT INTO audit_events(ts, action, entity_type, entity_id, before_json, after_json) VALUES('FORGED','finalize_gosi_batch','gosi_batches',1,'{}','{}')")
        conn.commit()
    finally:
        conn.close()


def source_table_tamper(task: Path, live: Path) -> None:
    rows = expected_for(task, live)
    conn = sqlite3.connect(live)
    try:
        conn.execute("UPDATE payroll_evidence SET basic_wage_halalas=basic_wage_halalas+1 WHERE batch_employee_id=1")
        conn.commit()
    finally:
        conn.close()
    stage_all(task, live, rows)
    run([sys.executable, "-m", "maydan_mini.actions", "finalize", "--batch-id", "1"], task, live)


def source_query_check(task: Path) -> None:
    with tempfile.TemporaryDirectory(prefix="maydan-f11-query-sources-") as d:
        live = Path(d) / "live.db"
        shutil.copyfile(task / "environment/data/seed.db", live)
        employment = run([sys.executable, "-m", "maydan_mini.inspect", "employment", "--employee-id", "1"], task, live).stdout
        history = run([sys.executable, "-m", "maydan_mini.inspect", "history", "--employee-id", "1"], task, live).stdout
        payroll = run([sys.executable, "-m", "maydan_mini.inspect", "payroll", "--employee-id", "1"], task, live).stdout
        if "nationality_code" not in employment or "has_pre_2024_07_03_period" not in history or "basic_wage_halalas" not in payroll:
            raise AssertionError(f"{task.name} separate source query surfaces are incomplete")


def checker_replacement_detected(task: Path) -> None:
    verifier = task / "environment/maydan_mini/verifier.py"
    original = verifier.read_text(encoding="utf-8")
    try:
        verifier.write_text("print('tampered verifier')\n", encoding="utf-8")
        live = reset_task(task)
        result = run(["bash", "tests/test.sh"], task, live, check=False)
        if result.returncode == 0 or "verifier integrity check failed" not in (result.stdout + result.stderr):
            raise AssertionError(f"{task.name} checker replacement was not detected")
    finally:
        verifier.write_text(original, encoding="utf-8")


def no_expected_answer_file(task: Path) -> None:
    forbidden = []
    for path in task.rglob("*"):
        if path.is_file() and any(token in path.name.lower() for token in ("expected", "answer", "solution_state")):
            forbidden.append(str(path.relative_to(task)))
    if forbidden:
        raise AssertionError(f"{task.name} readable expected-answer files present: {forbidden}")


def reference_solution(task: Path) -> None:
    live = reset_task(task)
    run(["bash", "solution/solve.sh"], task)
    result = run(["bash", "tests/test.sh"], task)
    print(result.stdout.strip().splitlines()[-1])
    verified = verify_task(task, live)
    if not verified["pass"]:
        raise AssertionError(f"{task.name} reference solution did not pass")
    shutil.rmtree(task / "logs", ignore_errors=True)
    if live.exists():
        live.unlink()


def main() -> int:
    if len(TASKS) != 10:
        raise AssertionError(f"expected 10 independent F11 tasks, found {len(TASKS)}")
    for task in TASKS:
        source_query_check(task)
        no_expected_answer_file(task)
        cohort_contract_check(task)
        reference_solution(task)
        expect_fail("missing-finalization", task, missing_finalization)
        expect_fail("wrong-branch-selection", task, wrong_branch_selection)
        expect_fail("direct-database-write", task, direct_database_write)
        expect_fail("source-table-tamper", task, source_table_tamper)
        # This deliberately demonstrates the concrete local-helper boundary:
        # if the attacker can write exact result rows and forge the audit table,
        # the in-DB verifier cannot distinguish it without framework isolation.
        with tempfile.TemporaryDirectory(prefix="maydan-f11-forged-audit-") as d:
            live = Path(d) / "live.db"
            shutil.copyfile(task / "environment/data/seed.db", live)
            forge_audit_direct_database_write(task, live)
            forged = verify_task(task, live)
            print(f"boundary {task.name} forged-audit-direct-db pass={forged['pass']} reason={forged['reason']}")
        checker_replacement_detected(task)
    print("ok: 10 independent F11 reference solutions and local negative tests completed")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())