From 3442cd658c4c33118924eff8769954ed378477eb Mon Sep 17 00:00:00 2001 From: Mohammad Galib Date: Mon, 30 Nov 2026 21:34:25 +0530 Subject: [PATCH 1/4] feat: trust anchor - per-file sha256 in the API, risky-call lint, CODEOWNERS, security review ADR-010 Amendment 1, step 1. api/modules.json and api/courses.json carry files[{path,sha256}] and content_sha256 for everything Studio downloads. scripts/lint_cell_risk.py is a non-blocking reviewer aid (not a sandbox). CONTRIBUTING gains a Security review section. Co-Authored-By: Claude Opus 5.5 --- .github/CODEOWNERS | 4 + .github/workflows/checks.yml | 6 +- CHANGELOG.md | 7 ++ CONTRIBUTING.md | 18 ++- PROGRESS.md | 6 + api/README.md | 16 +++ api/courses.json | 51 ++++++++ api/modules.json | 99 ++++++++++++++-- scripts/build_api.py | 14 ++- scripts/lint_cell_risk.py | 224 +++++++++++++++++++++++++++++++++++ scripts/repo_lib.py | 26 ++++ tests/test_trust_anchor.py | 59 +++++++++ 12 files changed, 516 insertions(+), 14 deletions(-) create mode 100644 .github/CODEOWNERS create mode 100644 scripts/lint_cell_risk.py create mode 100644 tests/test_trust_anchor.py diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..674caf1 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,4 @@ +# Every change to this repository needs review by the owner. Studio runs the Python in modules/ on a +# learner's machine, so what is merged here is the safety control for that code (ADR-010, CONTRIBUTING +# "Security review"). Requiring code-owner review is a branch-ruleset setting the owner enables. +* @galib9690 diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 3ef42a6..08d0d15 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -42,7 +42,7 @@ jobs: - name: CSP and external-host check (only the Google Fonts hosts are allowed) run: python scripts/check_csp.py - - name: API files are current + - name: API files are current (includes the per-file sha256 of every module and course) run: python scripts/build_api.py --check - name: Python tests @@ -50,3 +50,7 @@ jobs: - name: Node tests run: node --test tests/js/*.test.js + + - name: Risky-call lint of lesson cells (warnings for the reviewer, not a sandbox) + continue-on-error: true + run: python scripts/lint_cell_risk.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b8d64df..5baf06e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes to the learning modules. Versions are per module (`manifest.json` and the manifest embedded in `module.html` carry the same number). +## 2026-11-30 — Trust anchor (ADR-010 Amendment 1, step 1) + +No lesson content changed; module versions are unchanged. +- `api/modules.json` and `api/courses.json`: every entry carries `files` (path + sha256 of each file Studio downloads: `module.html`; for a course `course.json` plus each member's `module.html`) and `content_sha256`. Schema in `api/README.md`. Generated by `scripts/build_api.py`; `tests/test_trust_anchor.py` checks the committed hashes equal the files. +- `scripts/lint_cell_risk.py`: reviewer aid listing risky calls in cell code (warnings, not a sandbox). Non-blocking PR step. Today: 1 finding (the optional NWIS cell of real-streamflow-data imports `dataretrieval`, as documented in the lesson). +- `.github/CODEOWNERS` (`@galib9690`) and a "Security review" section in CONTRIBUTING.md, including that `trustLevel` is a publisher label, not a scientific review. + ## 2026-11-24 — Light theme fast-track (shared theme tokens, two pilot lessons) Owner approved the fast-track of docs/vision-2040/findings/module-theme-study-2026-11-24.md. Text, numbers and claims are unchanged; only colours and styles moved. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 91dc0fa..7a706f1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -130,7 +130,8 @@ python scripts/render_static_outputs.py --check # a cell's pre-rendered output python scripts/gen_docs.py --check # README table and course page match the manifests python scripts/validate_manifests.py # manifests valid; embedded block agrees; course graph valid python scripts/check_csp.py # no external hosts except Google Fonts, no eval/fetch/WebSocket -python scripts/build_api.py --check # api/*.json are current +python scripts/build_api.py --check # api/*.json are current (including the per-file sha256) +python scripts/lint_cell_risk.py # reviewer aid: risky calls in cell code (warnings; not a sandbox) python -m pytest tests -q # use /opt/miniconda3/bin/python -s -E locally in the AI-Hydro workspace node --test tests/js/*.test.js ``` @@ -140,3 +141,18 @@ Regenerate instead of editing by hand: `build_modules.py`, `render_static_output ## PR review Automated: the checks above. Human review checks branding compliance, accuracy of the hydrology, and originality. The API's `certification.metadata_complete` only says the manifest is complete; `certification.scientific_review` stays `null` until a reviewer records a review. + +## Security review + +A module is Python that AI-Hydro Studio runs **on the learner's computer, with the learner's permissions**. Merging a pull request here is therefore the safety control for that code; there is no sandbox behind it. `.github/CODEOWNERS` names the owner who must review every change. + +Reviewers, in addition to branding, hydrology and originality: + +1. **Read what each Python cell does**, not only what the prose says it does. Run `python scripts/lint_cell_risk.py` (the PR check runs it too and shows warnings). It flags `subprocess`, `os.system`, `socket`, `requests`/`urllib`/`http.client`, `shutil.rmtree`, `eval`/`exec`, environment reads, and writes to absolute, `~` or `..` paths. It is a pointer for human reading: it misses obfuscated code and flags harmless code, so a clean run is not approval. +2. **No network, no subprocess, no file writes outside the working directory** unless the lesson has a stated teaching reason, written in the PR description and in the cell's own description line. Today the one flagged cell is the optional NWIS request in `real-streamflow-data`, which says it needs the internet. A cell may read its own bundled `data/` and compute. +3. **Check the diff of `module.html`, not the sources alone.** Studio downloads the built `module.html`, so review that file (the `build_modules.py --check` gate keeps it equal to the sources). +4. **Regenerate the API in the same PR** (`python scripts/build_api.py`). The index carries a sha256 of every file Studio downloads for each module and course (see `api/README.md`); the PR check fails if they do not match the files. + +What Studio does with this: it verifies the published sha256 of what it downloads before running it (ADR-010), and asks the learner again when a module's content changes. A merged change therefore reaches learners only after they accept it. + +**`trustLevel` is a publisher label, not a scientific review.** A course marked `official` was published by the AI-Hydro maintainers; it does not mean the hydrology was independently reviewed. Studio shows such content as "Draft — AI-assisted review only" unless `certification.scientific_review` records a human review. diff --git a/PROGRESS.md b/PROGRESS.md index 4af8470..a36e483 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -39,3 +39,9 @@ Not done: rendering the three new lessons inside the installed AI-Hydro build; o Branch `feat/light-theme-fasttrack`. Shared `theme.css`/`theme.js`; reading-a-hydrograph 0.5.0 and watershed-runoff 0.5.0 on the tokens; evapotranspiration-budyko 0.1.1 axis contrast fix; course 0.4.2; catalog regenerated. Tests: T1 (tokens), T2 (ratchet), T3 (HydroTheme) added; the existing suites pass (see the PR for the commands and counts). Not done: the other eight lessons; the extension side that sets `data-aihydro-theme` (separate PR); a check in the installed AI-Hydro build (owner's T5); a light stage for the Fish River scene. +## 2026-11-30 — Trust anchor (ADR-010 Amendment 1, step 1) + +Added per-file sha256 and `content_sha256` to the generated API, the risky-call lint, CODEOWNERS and the CONTRIBUTING security-review section (see CHANGELOG.md). +Verification: `/opt/miniconda3/bin/python -s -E -m pytest tests`, `node --test tests/js/*.test.js` and the scripts of the PR workflow. +Not done: the ruleset's required-review rule (owner setting; blocked by the `build-api.yml` push to `main`), and Studio-side verification of the hashes (step 2, extension repository). + diff --git a/api/README.md b/api/README.md index 69c3dea..70ea546 100644 --- a/api/README.md +++ b/api/README.md @@ -14,6 +14,7 @@ An array, one entry per `modules//manifest.json`, sorted by module id. Every | `updatedAt` | **author date of the last git commit that touched `modules//`** (not the build date; without history it keeps the previous value) | | `downloadCount`, `githubReactions`, `discussionUrl` | kept from the previous file; reactions are refreshed from GitHub Discussions by the workflow | | `certification` | see below | +| `files`, `content_sha256` | the trust anchor, see below | ### `certification` @@ -31,6 +32,21 @@ An array, one entry per `modules//manifest.json`, sorted by module id. Every The old `certified` / `certified_at` fields are gone: a "certified" badge implied a scientific validity the check never established. +### `files` and `content_sha256` (trust anchor) + +```json +"files": [{"path": "modules/dem-to-twi/module.html", "sha256": "<64 hex>"}], +"content_sha256": "<64 hex>" +``` + +- `files` lists every file Studio downloads and runs for the module, sorted by `path`. Today that is one file: `module.html` (shared code, data and static outputs are inlined into it by `build_modules.py`; `installModule` fetches only `downloadUrl`). `path` is relative to the repository root, so the file is served at `https://raw.githubusercontent.com/AI-Hydro/Modules/main/`. +- `sha256` is the SHA-256 of the file's exact bytes (the repository bytes; raw.githubusercontent.com does not transform them). +- `content_sha256` is the SHA-256 of the text made of one line `" \n"` per file, in `files` order (the `sha256sum` format). From the repository root: `sha256sum | sha256sum`. +- A client that verifies the download compares the bytes it received with `sha256`; a change of `content_sha256` between two reads of the index means the module's content changed. +- This index is itself a file on `main` (and GitHub Pages), so the hashes protect against a changed file with an unchanged index, not against a compromised `main`. Review of what is merged (CONTRIBUTING "Security review") is the control for that. + ## `courses.json` An array, one entry per `courses//course.json`. Fields: `courseId`, `title`, `abstract`, `version`, `license`, `estimatedHours`, `topic`, `tags`, `trustLevel`, `citation`, `citationUrl`, `isFeatured` and the author fields come from `course.json`; `contributors` is its `authors`; `modules` lists `{moduleId, title, estimatedMinutes, prerequisites?}` in course order; `level` is the common level of the course's modules (`mixed` if they differ); `manifestUrl` and `githubUrl` are derived from the course directory; `updatedAt` is the last git commit touching the course directory. + +Every course entry also has `files` and `content_sha256` in the same shape: `course.json` (the `manifestUrl`) plus the `module.html` of each member module (the files `installCourse` fetches). diff --git a/api/courses.json b/api/courses.json index 11ac120..6d31740 100644 --- a/api/courses.json +++ b/api/courses.json @@ -132,6 +132,57 @@ "isFeatured": true, "manifestUrl": "https://raw.githubusercontent.com/AI-Hydro/Modules/main/courses/intro-to-hydrology/course.json", "githubUrl": "https://github.com/AI-Hydro/Modules/tree/main/courses/intro-to-hydrology", + "files": [ + { + "path": "courses/intro-to-hydrology/course.json", + "sha256": "1aea2b433cf037c151546e252451448000485713788bc9b2ca81df9bc3ba699e" + }, + { + "path": "modules/baseflow-separation/module.html", + "sha256": "e703349a2d579a12052ac820e865df2cbe2e8c44b10b11cbe6e782d1adf408a0" + }, + { + "path": "modules/capstone-basin-story/module.html", + "sha256": "09e159bf1118efb9d11b480529d811e433fa33378ecdd7ef79faf3ed7c1627eb" + }, + { + "path": "modules/course-certificate/module.html", + "sha256": "76e846f47823ce82d4fb456c91faa18b950eded38f3c59cde32beb2e2772d375" + }, + { + "path": "modules/dem-to-twi/module.html", + "sha256": "8c01bf4c4f67057422ff192074049b92070bce402bf1c60c155eb8fae9fa2544" + }, + { + "path": "modules/evapotranspiration-budyko/module.html", + "sha256": "202b78b1a4e3ad7c773943659f5b486102279d5bf26c508dc25d12882dace274" + }, + { + "path": "modules/precipitation-point-to-basin/module.html", + "sha256": "c3a6ae247ec0e0be7ff9455052c7c6571139f22980d631ef91dfd1ad47c78638" + }, + { + "path": "modules/reading-a-hydrograph/module.html", + "sha256": "46a8eb909f0a4b6bd5ca064f62a0a8f773920935cc74c6d12590564dfb1e5159" + }, + { + "path": "modules/real-streamflow-data/module.html", + "sha256": "f45b28a9ccbf5d9681a66201b00e116905e742a53d4d873ec6d922ffc7dfc5ad" + }, + { + "path": "modules/runoff-generation/module.html", + "sha256": "e234bc866545daa37aba39439afd1dc4a7f86a05df6b9c119b867047df8890ad" + }, + { + "path": "modules/water-cycle-in-motion/module.html", + "sha256": "9040e72d333dfc2bc58ecc77bc3f176b4ee6c9a8c66033cb5027d96b0b207589" + }, + { + "path": "modules/watershed-runoff/module.html", + "sha256": "7aa0db1fce57748df698be6e5383cd0e1b7c19d8fbad28e28bf69f713b198a3a" + } + ], + "content_sha256": "8dda0cb91e8b594daee23dc997f2a12056c0c96d83804b2dafe315599dc89698", "updatedAt": "2026-11-24" } ] diff --git a/api/modules.json b/api/modules.json index 8fd4a5f..34f7b7c 100644 --- a/api/modules.json +++ b/api/modules.json @@ -50,7 +50,14 @@ ], "checks_failed": [], "scientific_review": null - } + }, + "files": [ + { + "path": "modules/baseflow-separation/module.html", + "sha256": "e703349a2d579a12052ac820e865df2cbe2e8c44b10b11cbe6e782d1adf408a0" + } + ], + "content_sha256": "52235308aed2f440e955d5cf47c04fe8bb22415386fd9fe2996c97ce25d5a5a5" }, { "moduleId": "capstone-basin-story", @@ -106,7 +113,14 @@ ], "checks_failed": [], "scientific_review": null - } + }, + "files": [ + { + "path": "modules/capstone-basin-story/module.html", + "sha256": "09e159bf1118efb9d11b480529d811e433fa33378ecdd7ef79faf3ed7c1627eb" + } + ], + "content_sha256": "aa4abc076aed85bdd89ebd155863894f4a6a8b97ab7b9cec373ca459a4fc52a8" }, { "moduleId": "course-certificate", @@ -150,7 +164,14 @@ ], "checks_failed": [], "scientific_review": null - } + }, + "files": [ + { + "path": "modules/course-certificate/module.html", + "sha256": "76e846f47823ce82d4fb456c91faa18b950eded38f3c59cde32beb2e2772d375" + } + ], + "content_sha256": "7da48be608c07428ee0f60e0a381e742a2496af4d026f39447afe68a9f8c6d45" }, { "moduleId": "dem-to-twi", @@ -204,7 +225,14 @@ ], "checks_failed": [], "scientific_review": null - } + }, + "files": [ + { + "path": "modules/dem-to-twi/module.html", + "sha256": "8c01bf4c4f67057422ff192074049b92070bce402bf1c60c155eb8fae9fa2544" + } + ], + "content_sha256": "bd65db8c9bad1db64f98ce03331c0a963fd5d0c08547c9314177cf980259fd6b" }, { "moduleId": "evapotranspiration-budyko", @@ -258,7 +286,14 @@ ], "checks_failed": [], "scientific_review": null - } + }, + "files": [ + { + "path": "modules/evapotranspiration-budyko/module.html", + "sha256": "202b78b1a4e3ad7c773943659f5b486102279d5bf26c508dc25d12882dace274" + } + ], + "content_sha256": "0b734b5ea4d4f6f702d9308713412b1b67b429ae174b2fbbb988f5492b35dd53" }, { "moduleId": "precipitation-point-to-basin", @@ -312,7 +347,14 @@ ], "checks_failed": [], "scientific_review": null - } + }, + "files": [ + { + "path": "modules/precipitation-point-to-basin/module.html", + "sha256": "c3a6ae247ec0e0be7ff9455052c7c6571139f22980d631ef91dfd1ad47c78638" + } + ], + "content_sha256": "cf8021a1d0481b74dd96571a01c25944c1ead624814bfae67debff541d762c7b" }, { "moduleId": "reading-a-hydrograph", @@ -365,7 +407,14 @@ ], "checks_failed": [], "scientific_review": null - } + }, + "files": [ + { + "path": "modules/reading-a-hydrograph/module.html", + "sha256": "46a8eb909f0a4b6bd5ca064f62a0a8f773920935cc74c6d12590564dfb1e5159" + } + ], + "content_sha256": "3617de32dfe273856d1796f71ed0c4b920e98cd40160a72e0e059003c6b6f298" }, { "moduleId": "real-streamflow-data", @@ -422,7 +471,14 @@ ], "checks_failed": [], "scientific_review": null - } + }, + "files": [ + { + "path": "modules/real-streamflow-data/module.html", + "sha256": "f45b28a9ccbf5d9681a66201b00e116905e742a53d4d873ec6d922ffc7dfc5ad" + } + ], + "content_sha256": "93061aeecc35dc80ca4a4399ec58ef0b56fb5ae52f5ad14f3e50171cf1dc5355" }, { "moduleId": "runoff-generation", @@ -474,7 +530,14 @@ ], "checks_failed": [], "scientific_review": null - } + }, + "files": [ + { + "path": "modules/runoff-generation/module.html", + "sha256": "e234bc866545daa37aba39439afd1dc4a7f86a05df6b9c119b867047df8890ad" + } + ], + "content_sha256": "ff9db17123c01431c6087d6cc2964997f3a841784309f4ee70f1d8cb8f5da421" }, { "moduleId": "water-cycle-in-motion", @@ -528,7 +591,14 @@ ], "checks_failed": [], "scientific_review": null - } + }, + "files": [ + { + "path": "modules/water-cycle-in-motion/module.html", + "sha256": "9040e72d333dfc2bc58ecc77bc3f176b4ee6c9a8c66033cb5027d96b0b207589" + } + ], + "content_sha256": "84df2d91c3c4352fdc2cfa3ff8cb39eac8565fece11af8da18e8d2f5cf1dc272" }, { "moduleId": "watershed-runoff", @@ -582,6 +652,13 @@ ], "checks_failed": [], "scientific_review": null - } + }, + "files": [ + { + "path": "modules/watershed-runoff/module.html", + "sha256": "7aa0db1fce57748df698be6e5383cd0e1b7c19d8fbad28e28bf69f713b198a3a" + } + ], + "content_sha256": "b89d1ac627a0480764a0d47c2057784147636a7c4471fe522f8191ca13fac771" } ] diff --git a/scripts/build_api.py b/scripts/build_api.py index 9ef1733..68bf01c 100644 --- a/scripts/build_api.py +++ b/scripts/build_api.py @@ -12,6 +12,10 @@ positive estimatedMinutes (checks_passed / checks_failed list them). It says NOTHING about whether the hydrology is right. scientific_review null until a human reviewer records one. Never set by this script. + * files / content_sha256 the trust anchor: sha256 of every file Studio downloads for the entry + (module: module.html; course: course.json plus each member's module.html), taken from + the repo bytes that raw.githubusercontent.com serves, and one digest over that list. + See api/README.md. api/courses.json is generated from courses//course.json (and the module manifests for level); it is never edited by hand. @@ -27,7 +31,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) -from repo_lib import RAW, ROOT, TREE, courses, git_date, manifests, read_json # noqa: E402 +from repo_lib import RAW, ROOT, TREE, courses, git_date, hashed_files, manifests, raw_path, read_json # noqa: E402 API = ROOT / "api" @@ -65,6 +69,9 @@ def build_modules(existing: dict[str, dict]) -> list[dict]: data.setdefault("discussionUrl", prev.get("discussionUrl", "")) data.setdefault("isFeatured", False) data["certification"] = certify(data) + # Trust anchor (ADR-010): installModule fetches only downloadUrl, and everything else the lesson + # needs (shared code, data, static outputs) is inlined in that one HTML file. + data.update(hashed_files([raw_path(data["downloadUrl"])])) items.append(data) return items @@ -103,6 +110,11 @@ def build_courses(existing: dict[str, dict]) -> list[dict]: "manifestUrl": f"{RAW}/{rel}/course.json", "githubUrl": f"{TREE}/{rel}", } + # installCourse fetches course.json (manifestUrl) and each member's downloadUrl. + member_urls = [] + for m in c["modules"]: + member_urls.append(m.get("downloadUrl") or f"{RAW}/modules/{m['id']}/module.html") + item.update(hashed_files([raw_path(item["manifestUrl"])] + [raw_path(u) for u in member_urls])) prev = existing.get(c["courseId"], {}) item["updatedAt"] = git_date(rel) or prev.get("updatedAt", "") out.append(item) diff --git a/scripts/lint_cell_risk.py b/scripts/lint_cell_risk.py new file mode 100644 index 0000000..19fe233 --- /dev/null +++ b/scripts/lint_cell_risk.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Reviewer aid: list risky calls in the Python cells of modules/*/module.html. + +IT IS NOT A SANDBOX AND NOT A SECURITY BOUNDARY. A cell runs with the learner's own permissions; +this script only points a human reviewer at the lines to read. It can be evaded (getattr, string +building, importlib) and it can flag harmless code. It never fails a build: findings are warnings +and the exit status is 0 unless a module cannot be read (use --strict to exit 1 on any finding). + +The cell sources are the ones the learner sees at the default settings (the same text +render_static_outputs.py runs), including cells whose source a page script fills in. Each source is +parsed with `ast`; a cell that does not parse is scanned line by line instead and says so. + +Flagged: + subprocess / os.system / os.popen / os.exec* / os.spawn* run another program + socket / requests / urllib / http.client / httpx / aiohttp / + ftplib / smtplib / telnetlib / websocket(s) / dataretrieval / pygeohydro / pynhd / + py3dep / pydaymet / ee network access + shutil.rmtree / os.remove / os.unlink / os.rmdir / os.removedirs / Path.unlink / .rmdir deletion + eval / exec / compile / __import__ / importlib.import_module dynamic code + ctypes / pickle / marshal / webbrowser native code, unsafe load, opens a browser + open(...) for writing, Path.write_text/write_bytes, savefig/to_csv/np.save... + when the target is an absolute path, "~", "..", or a name built from os.environ / expanduser + (a plain relative name is the working directory and is allowed) + os.environ / os.getenv reading the environment + +Usage: python scripts/lint_cell_risk.py all modules (needs node, like render_static_outputs.py) + python scripts/lint_cell_risk.py ... + python scripts/lint_cell_risk.py --strict exit 1 when anything is flagged +""" +from __future__ import annotations + +import argparse +import ast +import os +import re +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from repo_lib import ROOT # noqa: E402 + +NETWORK = {"socket", "requests", "urllib", "urllib3", "http", "httpx", "aiohttp", "ftplib", "smtplib", "telnetlib", + "websocket", "websockets", "xmlrpc", "dataretrieval", "pygeohydro", "pynhd", "py3dep", + "pydaymet", "ee", "geemap"} +NETWORK_DOTTED = {"http.client", "http.server", "urllib.request"} +OTHER_MODULES = {"subprocess": "subprocess", "ctypes": "native code (ctypes)", "pickle": "pickle (unsafe to load)", + "marshal": "marshal", "webbrowser": "opens a browser", "multiprocessing": "spawns processes", + "pty": "pty"} +CALLS = { + "os.system": "runs a shell command", "os.popen": "runs a shell command", + "shutil.rmtree": "deletes a directory tree", "os.remove": "deletes a file", "os.unlink": "deletes a file", + "os.rmdir": "deletes a directory", "os.removedirs": "deletes directories", "shutil.move": "moves files", + "os.rename": "renames files", "os.replace": "replaces files", "os.chmod": "changes permissions", + "importlib.import_module": "dynamic import", "__import__": "dynamic import", + "eval": "dynamic code (eval)", "exec": "dynamic code (exec)", "compile": "dynamic code (compile)", + "os.getenv": "reads the environment", "os.putenv": "changes the environment", +} +CALL_PREFIXES = {"os.exec": "replaces the process", "os.spawn": "runs another program", "subprocess.": "runs another program"} +METHODS_DELETE = {"unlink", "rmdir"} +WRITE_METHODS = {"write_text", "write_bytes"} +SAVE_FUNCS = {"savefig", "to_csv", "to_json", "to_parquet", "to_pickle", "to_excel", "save", "savez", "savez_compressed", "savetxt"} + + +def dotted(node: ast.AST) -> str: + parts = [] + while isinstance(node, ast.Attribute): + parts.append(node.attr) + node = node.value + if isinstance(node, ast.Name): + parts.append(node.id) + return ".".join(reversed(parts)) + return "" + + +def outside_cwd(node: ast.AST) -> str | None: + """Why this path expression is not plainly inside the working directory, or None.""" + if isinstance(node, ast.Constant) and isinstance(node.value, str): + v = node.value + if v.startswith(("/", "~", "\\")) or re.match(r"^[A-Za-z]:[\\/]", v): + return f"absolute or home path {v!r}" + if ".." in re.split(r"[\\/]", v): + return f"path with '..' {v!r}" + return None + for sub in ast.walk(node): + if isinstance(sub, ast.Call) and dotted(sub.func).endswith(("expanduser", "gettempdir", "home", "getcwd")): + return "path built from " + dotted(sub.func) + if isinstance(sub, ast.Attribute) and dotted(sub) in ("os.environ", "sys.argv"): + return "path built from " + dotted(sub) + if isinstance(sub, ast.Constant) and isinstance(sub.value, str) and sub.value.startswith(("/", "~")): + return f"absolute or home path {sub.value!r}" + return None # a variable: not detectable here + + +def write_mode(call: ast.Call) -> bool: + mode = None + if len(call.args) > 1: + mode = call.args[1] + for kw in call.keywords: + if kw.arg == "mode": + mode = kw.value + return isinstance(mode, ast.Constant) and isinstance(mode.value, str) and any(c in mode.value for c in "wax+") + + +def lint_ast(tree: ast.AST) -> list[tuple[int, str]]: + out: list[tuple[int, str]] = [] + + def add(node: ast.AST, msg: str) -> None: + out.append((getattr(node, "lineno", 0), msg)) + + for node in ast.walk(tree): + if isinstance(node, (ast.Import, ast.ImportFrom)): + names = [a.name for a in node.names] if isinstance(node, ast.Import) else [node.module or ""] + for n in names: + top = n.split(".")[0] + if top in NETWORK or n in NETWORK_DOTTED: + add(node, f"imports {n}: network access") + elif top in OTHER_MODULES: + add(node, f"imports {n}: {OTHER_MODULES[top]}") + if isinstance(node, ast.ImportFrom) and (node.module or "") == "os": + for a in node.names: + if a.name in ("system", "popen", "remove", "unlink", "rmdir", "environ", "getenv") or a.name.startswith(("exec", "spawn")): + add(node, f"imports os.{a.name}") + if isinstance(node, ast.ImportFrom) and (node.module or "") == "shutil": + for a in node.names: + if a.name in ("rmtree", "move"): + add(node, f"imports shutil.{a.name}") + elif isinstance(node, ast.Call): + name = dotted(node.func) + if name in CALLS: + add(node, f"{name}(): {CALLS[name]}") + else: + for pre, why in CALL_PREFIXES.items(): + if name.startswith(pre): + add(node, f"{name}(): {why}") + break + if name == "open" or name.endswith(".open") and name.split(".")[0] in ("io", "codecs", "gzip", "bz2", "lzma", "tarfile", "zipfile"): + if write_mode(node) and node.args: + why = outside_cwd(node.args[0]) + if why: + add(node, f"{name}() for writing, {why}") + if isinstance(node.func, ast.Attribute): + meth = node.func.attr + if meth in METHODS_DELETE and not name.startswith(("os.",)): + add(node, f".{meth}(): deletes a path") + if meth in WRITE_METHODS: + why = outside_cwd(node.func.value) + if why: + add(node, f".{meth}(), {why}") + if meth in SAVE_FUNCS and node.args: + why = outside_cwd(node.args[0]) + if why: + add(node, f".{meth}() writes, {why}") + elif isinstance(node, ast.Attribute) and dotted(node) == "os.environ": + add(node, "os.environ: reads the environment") + return sorted(set(out)) + + +LINE_RULES = [ + (re.compile(r"\b(?:import|from)\s+(?:subprocess|socket|requests|urllib|http\.client|httpx|aiohttp|ctypes|pickle|webbrowser)\b"), "risky import"), + (re.compile(r"\bos\.(?:system|popen|remove|unlink|rmdir|environ|getenv|exec\w*|spawn\w*)\b"), "risky os call"), + (re.compile(r"\bshutil\.rmtree\b"), "shutil.rmtree"), + (re.compile(r"(? list[tuple[int, str]]: + out = [] + for i, line in enumerate(src.splitlines(), 1): + code = line.split("#", 1)[0] + for rx, why in LINE_RULES: + if rx.search(code): + out.append((i, f"{why} (line scan, cell did not parse)")) + return out + + +def lint_source(src: str) -> tuple[list[tuple[int, str]], bool]: + """(findings, parsed). Notebook magics and shell escapes are flagged and blanked before parsing.""" + out: list[tuple[int, str]] = [] + cleaned = [] + for i, line in enumerate(src.splitlines(), 1): + s = line.lstrip() + if s.startswith("!") or s.startswith("%"): + out.append((i, f"notebook shell/magic line: {s[:40]!r}")) + cleaned.append("") + else: + cleaned.append(line) + try: + tree = ast.parse("\n".join(cleaned)) + except SyntaxError: + return sorted(set(out + lint_lines(src))), False + return sorted(set(out + lint_ast(tree))), True + + +def module_ids() -> list[str]: + return sorted(p.parent.name for p in (ROOT / "modules").glob("*/module.html")) + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("modules", nargs="*") + ap.add_argument("--strict", action="store_true", help="exit 1 when anything is flagged") + a = ap.parse_args() + import render_static_outputs as rso # reuses its cell-source extraction (needs node) + + ids = a.modules or module_ids() + total = ncells = 0 + for mod in ids: + for cell in rso.cells_of(mod): + ncells += 1 + findings, parsed = lint_source(cell["source"]) + for line, msg in findings: + total += 1 + print(f"WARN {mod}/{cell['id']}:{line}: {msg}") + if os.environ.get("GITHUB_ACTIONS"): # shows up on the PR's checks page + print(f"::warning title=Risky call in a lesson cell::{mod}/{cell['id']}:{line}: {msg}") + if not parsed: + print(f"NOTE {mod}/{cell['id']}: source did not parse as Python; scanned line by line") + print(f"risky-call lint: {total} finding(s) in {ncells} cell(s) of {len(ids)} module(s). " + "Warnings for human review, not a sandbox: read the cell code itself.") + return 1 if (a.strict and total) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/repo_lib.py b/scripts/repo_lib.py index f2c0a46..d9b335d 100644 --- a/scripts/repo_lib.py +++ b/scripts/repo_lib.py @@ -1,6 +1,7 @@ """Small helpers shared by the repository scripts (API build, docs generation, validation).""" from __future__ import annotations +import hashlib import json import subprocess from pathlib import Path @@ -40,3 +41,28 @@ def git_date(path: str, first: bool = False) -> str | None: if not lines: return None return lines[-1] if first else lines[0] + + +def sha256_file(path: Path) -> str: + """sha256 (hex) of the file's exact bytes, which are what raw.githubusercontent.com serves.""" + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def hashed_files(rels: list[str]) -> dict: + """The trust-anchor block of an API entry for the repo-relative `rels` (posix paths). + + {"files": [{"path", "sha256"}, ...] sorted by path, "content_sha256": ...} where content_sha256 is the + sha256 of the text " \\n" for each file in that order (`sha256sum` format, so it can be + reproduced with `sha256sum | sha256sum` run from the repo root). + """ + files = [{"path": r, "sha256": sha256_file(ROOT / r)} for r in sorted(set(rels))] + listing = "".join(f"{f['sha256']} {f['path']}\n" for f in files) + return {"files": files, "content_sha256": hashlib.sha256(listing.encode("utf-8")).hexdigest()} + + +def raw_path(url: str) -> str: + """Repo-relative path of a raw.githubusercontent.com URL under RAW; ValueError for anything else.""" + prefix = RAW + "/" + if not url.startswith(prefix) or len(url) == len(prefix): + raise ValueError(f"not a {prefix} URL: {url}") + return url[len(prefix):] diff --git a/tests/test_trust_anchor.py b/tests/test_trust_anchor.py new file mode 100644 index 0000000..3aecbb1 --- /dev/null +++ b/tests/test_trust_anchor.py @@ -0,0 +1,59 @@ +"""Trust anchor (ADR-010 Amendment 1): the committed API carries the sha256 of every file Studio +downloads, and the hashes equal the files; the risky-call lint flags what it should.""" +import hashlib +import json +import sys + +import pytest + +from helpers import ROOT + +sys.path.insert(0, str(ROOT / "scripts")) +import lint_cell_risk # noqa: E402 + +RAW = "https://raw.githubusercontent.com/AI-Hydro/Modules/main/" +MODULES_API = json.loads((ROOT / "api/modules.json").read_text(encoding="utf-8")) +COURSES_API = json.loads((ROOT / "api/courses.json").read_text(encoding="utf-8")) + + +def digest(files): + return hashlib.sha256("".join(f"{f['sha256']} {f['path']}\n" for f in files).encode()).hexdigest() + + +def check_entry(entry): + files = entry["files"] + assert files, entry + assert [f["path"] for f in files] == sorted({f["path"] for f in files}) + for f in files: + assert hashlib.sha256((ROOT / f["path"]).read_bytes()).hexdigest() == f["sha256"], f["path"] + assert entry["content_sha256"] == digest(files) + + +@pytest.mark.parametrize("entry", MODULES_API, ids=lambda e: e["moduleId"]) +def test_module_hashes_equal_the_files(entry): + check_entry(entry) + # exactly what installModule fetches: the downloadUrl + assert [RAW + f["path"] for f in entry["files"]] == [entry["downloadUrl"]] + + +@pytest.mark.parametrize("entry", COURSES_API, ids=lambda e: e["courseId"]) +def test_course_hashes_equal_the_files(entry): + check_entry(entry) + urls = {RAW + f["path"] for f in entry["files"]} + assert entry["manifestUrl"] in urls + for m in json.loads((ROOT / "courses/intro-to-hydrology/course.json").read_text())["modules"]: + assert m["downloadUrl"] in urls, m["id"] + + +def test_lint_flags_risky_calls_and_passes_plain_code(): + risky = ( + "import subprocess\nimport requests\nfrom urllib.request import urlopen\nimport os, shutil\n" + "os.system('ls')\neval('1')\nshutil.rmtree('d')\nopen('/tmp/x', 'w')\nplt.savefig('../a.png')\n" + "from pathlib import Path\nPath('~/a').write_text('x')\n" + ) + msgs = " | ".join(m for _, m in lint_cell_risk.lint_source(risky)[0]) + for needle in ("subprocess", "requests", "urllib.request", "os.system", "eval", "shutil.rmtree", + "absolute or home path '/tmp/x'", "'..'", "write_text"): + assert needle in msgs, needle + plain = "import numpy as np\nimport matplotlib.pyplot as plt\nx = np.arange(5)\nplt.plot(x)\nplt.savefig('fig.png')\nopen('out.txt','w')\n" + assert lint_cell_risk.lint_source(plain) == ([], True) From b947545fc55efbcf03f5fbe569cad0cb94c1d740 Mon Sep 17 00:00:00 2001 From: Mohammad Galib Date: Mon, 30 Nov 2026 21:40:13 +0530 Subject: [PATCH 2/4] fix: trust anchor review fixes - honest docs, push retry, required downloadUrl, lint aliases Co-Authored-By: Claude Opus 5.5 --- .github/CODEOWNERS | 2 +- .github/workflows/build-api.yml | 9 +++++- CONTRIBUTING.md | 6 ++-- api/README.md | 1 + scripts/build_api.py | 2 +- scripts/lint_cell_risk.py | 55 ++++++++++++++++++++++++++++----- scripts/validate_manifests.py | 9 +++++- tests/test_trust_anchor.py | 22 ++++++++++++- 8 files changed, 91 insertions(+), 15 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 674caf1..75763c1 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,4 +1,4 @@ # Every change to this repository needs review by the owner. Studio runs the Python in modules/ on a # learner's machine, so what is merged here is the safety control for that code (ADR-010, CONTRIBUTING -# "Security review"). Requiring code-owner review is a branch-ruleset setting the owner enables. +# "Security review"). This takes effect once the required-review rule of the `main` ruleset is enabled (pending). * @galib9690 diff --git a/.github/workflows/build-api.yml b/.github/workflows/build-api.yml index 47558e1..955307c 100644 --- a/.github/workflows/build-api.yml +++ b/.github/workflows/build-api.yml @@ -102,5 +102,12 @@ jobs: echo "No changes to the API files" else git commit -m "ci: rebuild api/modules.json and api/courses.json [skip ci]" - git push + # a concurrent push to main must not leave a stale index: rebase onto it and retry (3 tries) + for attempt in 1 2 3; do + git pull --rebase origin main && git push && exit 0 + echo "push attempt $attempt failed, retrying" + sleep $((attempt * 5)) + done + echo "could not push the rebuilt API after 3 attempts" >&2 + exit 1 fi diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7a706f1..c46b912 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -148,11 +148,13 @@ A module is Python that AI-Hydro Studio runs **on the learner's computer, with t Reviewers, in addition to branding, hydrology and originality: -1. **Read what each Python cell does**, not only what the prose says it does. Run `python scripts/lint_cell_risk.py` (the PR check runs it too and shows warnings). It flags `subprocess`, `os.system`, `socket`, `requests`/`urllib`/`http.client`, `shutil.rmtree`, `eval`/`exec`, environment reads, and writes to absolute, `~` or `..` paths. It is a pointer for human reading: it misses obfuscated code and flags harmless code, so a clean run is not approval. +1. **Read what each Python cell does**, not only what the prose says it does. Run `python scripts/lint_cell_risk.py` (the PR check runs it too and shows warnings). It flags `subprocess`, `os.system`, `socket`, `requests`/`urllib`/`http.client`, `shutil.rmtree`, `eval`/`exec`, environment reads, and writes to absolute, `~` or `..` paths. It lints only the Python cells (page JavaScript is covered by `check_csp.py`) and does not detect reads of absolute paths. It is a pointer for human reading: it misses obfuscated code and flags harmless code, so a clean run is not approval. 2. **No network, no subprocess, no file writes outside the working directory** unless the lesson has a stated teaching reason, written in the PR description and in the cell's own description line. Today the one flagged cell is the optional NWIS request in `real-streamflow-data`, which says it needs the internet. A cell may read its own bundled `data/` and compute. 3. **Check the diff of `module.html`, not the sources alone.** Studio downloads the built `module.html`, so review that file (the `build_modules.py --check` gate keeps it equal to the sources). 4. **Regenerate the API in the same PR** (`python scripts/build_api.py`). The index carries a sha256 of every file Studio downloads for each module and course (see `api/README.md`); the PR check fails if they do not match the files. -What Studio does with this: it verifies the published sha256 of what it downloads before running it (ADR-010), and asks the learner again when a module's content changes. A merged change therefore reaches learners only after they accept it. +What Studio is designed to do with this: verify the published sha256 of what it downloads before running it and ask the learner again when a module's content changes (ADR-010 Amendment 1, step 2). That is **not released yet: today nothing verifies the hash**, so review here is the only control. + +The owner is asked to review every change through `.github/CODEOWNERS`, which takes effect once the required-review rule of the `main` ruleset is enabled (pending). **`trustLevel` is a publisher label, not a scientific review.** A course marked `official` was published by the AI-Hydro maintainers; it does not mean the hydrology was independently reviewed. Studio shows such content as "Draft — AI-assisted review only" unless `certification.scientific_review` records a human review. diff --git a/api/README.md b/api/README.md index 70ea546..55562e6 100644 --- a/api/README.md +++ b/api/README.md @@ -44,6 +44,7 @@ The old `certified` / `certified_at` fields are gone: a "certified" badge implie - `content_sha256` is the SHA-256 of the text made of one line `" \n"` per file, in `files` order (the `sha256sum` format). From the repository root: `sha256sum | sha256sum`. - A client that verifies the download compares the bytes it received with `sha256`; a change of `content_sha256` between two reads of the index means the module's content changed. - This index is itself a file on `main` (and GitHub Pages), so the hashes protect against a changed file with an unchanged index, not against a compromised `main`. Review of what is merged (CONTRIBUTING "Security review") is the control for that. +- The `Build Modules API` bot re-hashes whatever is on `main`, so the hashes attest that the index and the files agree, not that anyone reviewed them. Branch protection and review are the real control. ## `courses.json` diff --git a/scripts/build_api.py b/scripts/build_api.py index 68bf01c..6e92357 100644 --- a/scripts/build_api.py +++ b/scripts/build_api.py @@ -113,7 +113,7 @@ def build_courses(existing: dict[str, dict]) -> list[dict]: # installCourse fetches course.json (manifestUrl) and each member's downloadUrl. member_urls = [] for m in c["modules"]: - member_urls.append(m.get("downloadUrl") or f"{RAW}/modules/{m['id']}/module.html") + member_urls.append(m["downloadUrl"]) # required by validate_manifests.py item.update(hashed_files([raw_path(item["manifestUrl"])] + [raw_path(u) for u in member_urls])) prev = existing.get(c["courseId"], {}) item["updatedAt"] = git_date(rel) or prev.get("updatedAt", "") diff --git a/scripts/lint_cell_risk.py b/scripts/lint_cell_risk.py index 19fe233..b745ca4 100644 --- a/scripts/lint_cell_risk.py +++ b/scripts/lint_cell_risk.py @@ -17,12 +17,16 @@ py3dep / pydaymet / ee network access shutil.rmtree / os.remove / os.unlink / os.rmdir / os.removedirs / Path.unlink / .rmdir deletion eval / exec / compile / __import__ / importlib.import_module dynamic code + asyncio.create_subprocess_* / os.kill run or signal a process + (import aliases are resolved: `import os as o; o.system(..)` is flagged) ctypes / pickle / marshal / webbrowser native code, unsafe load, opens a browser open(...) for writing, Path.write_text/write_bytes, savefig/to_csv/np.save... when the target is an absolute path, "~", "..", or a name built from os.environ / expanduser (a plain relative name is the working directory and is allowed) os.environ / os.getenv reading the environment +Not covered: page JavaScript (see check_csp.py) and reads of absolute paths. + Usage: python scripts/lint_cell_risk.py all modules (needs node, like render_static_outputs.py) python scripts/lint_cell_risk.py ... python scripts/lint_cell_risk.py --strict exit 1 when anything is flagged @@ -39,10 +43,11 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) from repo_lib import ROOT # noqa: E402 -NETWORK = {"socket", "requests", "urllib", "urllib3", "http", "httpx", "aiohttp", "ftplib", "smtplib", "telnetlib", - "websocket", "websockets", "xmlrpc", "dataretrieval", "pygeohydro", "pynhd", "py3dep", +# whole top-level modules that mean network access; urllib / http / xmlrpc are judged by submodule below +NETWORK = {"socket", "requests", "urllib3", "httpx", "aiohttp", "ftplib", "smtplib", "telnetlib", + "websocket", "websockets", "dataretrieval", "pygeohydro", "pynhd", "py3dep", "pydaymet", "ee", "geemap"} -NETWORK_DOTTED = {"http.client", "http.server", "urllib.request"} +NETWORK_DOTTED = ("http.client", "http.server", "urllib.request", "xmlrpc.client", "xmlrpc.server") OTHER_MODULES = {"subprocess": "subprocess", "ctypes": "native code (ctypes)", "pickle": "pickle (unsafe to load)", "marshal": "marshal", "webbrowser": "opens a browser", "multiprocessing": "spawns processes", "pty": "pty"} @@ -54,8 +59,11 @@ "importlib.import_module": "dynamic import", "__import__": "dynamic import", "eval": "dynamic code (eval)", "exec": "dynamic code (exec)", "compile": "dynamic code (compile)", "os.getenv": "reads the environment", "os.putenv": "changes the environment", + "os.kill": "signals a process", "os.killpg": "signals a process", + "builtins.exec": "dynamic code (exec)", "builtins.eval": "dynamic code (eval)", "builtins.compile": "dynamic code (compile)", } -CALL_PREFIXES = {"os.exec": "replaces the process", "os.spawn": "runs another program", "subprocess.": "runs another program"} +CALL_PREFIXES = {"os.exec": "replaces the process", "os.spawn": "runs another program", "subprocess.": "runs another program", + "asyncio.create_subprocess_": "runs another program"} METHODS_DELETE = {"unlink", "rmdir"} WRITE_METHODS = {"write_text", "write_bytes"} SAVE_FUNCS = {"savefig", "to_csv", "to_json", "to_parquet", "to_pickle", "to_excel", "save", "savez", "savez_compressed", "savetxt"} @@ -72,6 +80,31 @@ def dotted(node: ast.AST) -> str: return "" +def aliases_of(tree: ast.AST) -> dict[str, str]: + """local name -> what it stands for, from `import os as o`, `from os import system as s` and the plain forms.""" + out: dict[str, str] = {} + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for a in node.names: + out[a.asname or a.name.split(".")[0]] = a.name if a.asname else a.name.split(".")[0] + elif isinstance(node, ast.ImportFrom) and node.module and not node.level: + for a in node.names: + out[a.asname or a.name] = f"{node.module}.{a.name}" + return out + + +def resolve(name: str, aliases: dict[str, str]) -> str: + head, _, rest = name.partition(".") + full = aliases.get(head) + if full is None: + return name + return f"{full}.{rest}" if rest else full + + +def is_network(n: str) -> bool: + return n.split(".")[0] in NETWORK or any(n == d or n.startswith(d + ".") for d in NETWORK_DOTTED) + + def outside_cwd(node: ast.AST) -> str | None: """Why this path expression is not plainly inside the working directory, or None.""" if isinstance(node, ast.Constant) and isinstance(node.value, str): @@ -103,16 +136,20 @@ def write_mode(call: ast.Call) -> bool: def lint_ast(tree: ast.AST) -> list[tuple[int, str]]: out: list[tuple[int, str]] = [] + aliases = aliases_of(tree) def add(node: ast.AST, msg: str) -> None: out.append((getattr(node, "lineno", 0), msg)) for node in ast.walk(tree): if isinstance(node, (ast.Import, ast.ImportFrom)): - names = [a.name for a in node.names] if isinstance(node, ast.Import) else [node.module or ""] + if isinstance(node, ast.Import): + names = [a.name for a in node.names] + else: # `from urllib import request` is urllib.request; `from urllib import parse` is not network + names = [f"{node.module}.{a.name}" for a in node.names] if node.module and not node.level else [] for n in names: top = n.split(".")[0] - if top in NETWORK or n in NETWORK_DOTTED: + if is_network(n): add(node, f"imports {n}: network access") elif top in OTHER_MODULES: add(node, f"imports {n}: {OTHER_MODULES[top]}") @@ -125,7 +162,9 @@ def add(node: ast.AST, msg: str) -> None: if a.name in ("rmtree", "move"): add(node, f"imports shutil.{a.name}") elif isinstance(node, ast.Call): - name = dotted(node.func) + name = resolve(dotted(node.func), aliases) + if is_network(name) and name.split(".")[0] in ("urllib", "http", "xmlrpc"): + add(node, f"{name}(): network access") if name in CALLS: add(node, f"{name}(): {CALLS[name]}") else: @@ -150,7 +189,7 @@ def add(node: ast.AST, msg: str) -> None: why = outside_cwd(node.args[0]) if why: add(node, f".{meth}() writes, {why}") - elif isinstance(node, ast.Attribute) and dotted(node) == "os.environ": + elif isinstance(node, ast.Attribute) and resolve(dotted(node), aliases) == "os.environ": add(node, "os.environ: reads the environment") return sorted(set(out)) diff --git a/scripts/validate_manifests.py b/scripts/validate_manifests.py index 97a9a01..868bc49 100644 --- a/scripts/validate_manifests.py +++ b/scripts/validate_manifests.py @@ -22,7 +22,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) from build_modules import embedded_manifest # noqa: E402 -from repo_lib import ROOT, courses, read_json # noqa: E402 +from repo_lib import ROOT, courses, raw_path, read_json # noqa: E402 REQUIRED = ["moduleId", "title", "description", "version", "license", "author", "topic", "level", "estimatedMinutes", "tags", "requires"] LEVELS = {"intro", "intermediate", "advanced"} @@ -81,6 +81,13 @@ def check_course(path: Path, c: dict, ids: set[str]) -> list[str]: for m in mods: if m["id"] not in ids: errs.append(f"{name}: module {m['id']!r} has no modules/{m['id']}/") + # required: the API hashes the file this URL names, and the extension fetches exactly this URL + # (it would otherwise resolve `path` against the manifest URL, which this repo does not hash) + try: + if raw_path(m.get("downloadUrl", "")) != f"modules/{m['id']}/module.html": + errs.append(f"{name}: {m['id']} downloadUrl must be the raw URL of modules/{m['id']}/module.html") + except ValueError: + errs.append(f"{name}: {m['id']} needs a downloadUrl (raw.githubusercontent.com/AI-Hydro/Modules/main/...)") for p in m.get("prerequisites", []): if p not in order: errs.append(f"{name}: {m['id']} requires {p!r}, which is not in the course") diff --git a/tests/test_trust_anchor.py b/tests/test_trust_anchor.py index 3aecbb1..b0361a7 100644 --- a/tests/test_trust_anchor.py +++ b/tests/test_trust_anchor.py @@ -41,8 +41,11 @@ def test_course_hashes_equal_the_files(entry): check_entry(entry) urls = {RAW + f["path"] for f in entry["files"]} assert entry["manifestUrl"] in urls - for m in json.loads((ROOT / "courses/intro-to-hydrology/course.json").read_text())["modules"]: + course = next(json.loads(p.read_text()) for p in sorted((ROOT / "courses").glob("*/course.json")) + if json.loads(p.read_text())["courseId"] == entry["courseId"]) + for m in course["modules"]: assert m["downloadUrl"] in urls, m["id"] + assert len(entry["files"]) == len(course["modules"]) + 1 def test_lint_flags_risky_calls_and_passes_plain_code(): @@ -57,3 +60,20 @@ def test_lint_flags_risky_calls_and_passes_plain_code(): assert needle in msgs, needle plain = "import numpy as np\nimport matplotlib.pyplot as plt\nx = np.arange(5)\nplt.plot(x)\nplt.savefig('fig.png')\nopen('out.txt','w')\n" assert lint_cell_risk.lint_source(plain) == ([], True) + + +def lint_msgs(src): + return " | ".join(m for _, m in lint_cell_risk.lint_source(src)[0]) + + +def test_lint_resolves_aliases_and_new_calls(): + msgs = lint_msgs("import os as o\nimport shutil as sh\nfrom os import system as run\nimport builtins\nimport asyncio\n" + "o.system('x')\nsh.rmtree('d')\nrun('y')\no.kill(1, 9)\nbuiltins.exec('1')\nasyncio.create_subprocess_exec('ls')\n") + for needle in ("os.system(): runs", "shutil.rmtree", "os.system", "os.kill", "builtins.exec", "asyncio.create_subprocess_"): + assert needle in msgs, (needle, msgs) + + +def test_lint_urllib_only_network_submodules(): + assert lint_cell_risk.lint_source("from urllib import parse\nimport urllib.parse\nparse.quote('a')\n") == ([], True) + assert "network" in lint_msgs("from urllib import request\n") + assert "network" in lint_msgs("import urllib.request as ur\nur.urlopen('http://x')\n") From bea0b58cb392d021b6ed5421d88d111ebe4b58a7 Mon Sep 17 00:00:00 2001 From: Mohammad Galib Date: Mon, 30 Nov 2026 22:56:30 +0530 Subject: [PATCH 3/4] ci: build-api verifies main instead of committing to it; reaction refresh via reviewed branch Lets the main ruleset require review with no bot bypass (deploy keys are disabled for the organisation; GitHub refused a GitHub Actions bypass). ADR-010 Amendment 1. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build-api.yml | 55 +++++++++++++++++++-------------- CHANGELOG.md | 1 + api/README.md | 2 +- 3 files changed, 33 insertions(+), 25 deletions(-) diff --git a/.github/workflows/build-api.yml b/.github/workflows/build-api.yml index 955307c..a858010 100644 --- a/.github/workflows/build-api.yml +++ b/.github/workflows/build-api.yml @@ -1,9 +1,12 @@ name: Build Modules API -# Regenerates api/modules.json and api/courses.json with scripts/build_api.py (the same code a local -# run uses). Triggered by anything that can change what the API says: module sources and manifests, -# course definitions and the shared code that is inlined into modules. The daily run only refreshes -# GitHub reaction counts. +# ADR-010 trust anchor: nothing commits to main without review. +# - On every push to main that can change the API, `verify` checks that the committed api/*.json +# (including the per-file sha256 values) matches the files. PRs already have to commit the +# regenerated API (checks.yml runs build_api.py --check), so main never needs a bot commit. +# - Discussion reaction counts are cosmetic. `refresh-reactions` runs only on manual dispatch: it +# rebuilds the API, refreshes the counts and pushes a branch `bot/api-refresh-`; open a PR +# from it and merge it like any other change. on: push: branches: [main] @@ -11,26 +14,35 @@ on: - 'modules/**' - 'courses/**' - 'shared/**' - schedule: - # Refresh reaction counts daily at 06:00 UTC - - cron: '0 6 * * *' + - 'api/**' + - 'scripts/build_api.py' workflow_dispatch: -permissions: - contents: write - discussions: read - jobs: - build: + verify: + if: github.event_name == 'push' runs-on: ubuntu-latest + permissions: + contents: read steps: - uses: actions/checkout@v4 with: fetch-depth: 0 # updatedAt comes from the last git commit touching each module + - name: Committed API matches the files (hashes included) + run: python3 scripts/build_api.py --check + refresh-reactions: + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + permissions: + contents: write # pushes a bot/ branch only; main is protected by the repository ruleset + discussions: read + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Build api/modules.json and api/courses.json run: python3 scripts/build_api.py - - name: Scrape GitHub Discussion reactions env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -92,8 +104,7 @@ jobs: else: print("No reaction count changes") EOF - - - name: Commit updated API + - name: Push a refresh branch (open a PR from it) run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" @@ -101,13 +112,9 @@ jobs: if git diff --staged --quiet; then echo "No changes to the API files" else - git commit -m "ci: rebuild api/modules.json and api/courses.json [skip ci]" - # a concurrent push to main must not leave a stale index: rebase onto it and retry (3 tries) - for attempt in 1 2 3; do - git pull --rebase origin main && git push && exit 0 - echo "push attempt $attempt failed, retrying" - sleep $((attempt * 5)) - done - echo "could not push the rebuilt API after 3 attempts" >&2 - exit 1 + branch="bot/api-refresh-${{ github.run_id }}" + git switch -c "$branch" + git commit -m "ci: refresh API reaction counts" + git push origin "$branch" + echo "Open a PR: https://github.com/${{ github.repository }}/compare/main...$branch" fi diff --git a/CHANGELOG.md b/CHANGELOG.md index 5baf06e..6416c1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to the learning modules. Versions are per module (`manifest. No lesson content changed; module versions are unchanged. - `api/modules.json` and `api/courses.json`: every entry carries `files` (path + sha256 of each file Studio downloads: `module.html`; for a course `course.json` plus each member's `module.html`) and `content_sha256`. Schema in `api/README.md`. Generated by `scripts/build_api.py`; `tests/test_trust_anchor.py` checks the committed hashes equal the files. - `scripts/lint_cell_risk.py`: reviewer aid listing risky calls in cell code (warnings, not a sandbox). Non-blocking PR step. Today: 1 finding (the optional NWIS cell of real-streamflow-data imports `dataretrieval`, as documented in the lesson). +- `.github/workflows/build-api.yml` no longer commits to `main`: on push it only verifies the committed API (`build_api.py --check`); the cosmetic reaction-count refresh runs on manual dispatch and pushes a `bot/api-refresh-*` branch for a reviewed PR. This lets `main` require review with no bot bypass (deploy keys are disabled for the organisation and GitHub refused a GitHub Actions bypass). - `.github/CODEOWNERS` (`@galib9690`) and a "Security review" section in CONTRIBUTING.md, including that `trustLevel` is a publisher label, not a scientific review. ## 2026-11-24 — Light theme fast-track (shared theme tokens, two pilot lessons) diff --git a/api/README.md b/api/README.md index 55562e6..0f7c2a7 100644 --- a/api/README.md +++ b/api/README.md @@ -44,7 +44,7 @@ The old `certified` / `certified_at` fields are gone: a "certified" badge implie - `content_sha256` is the SHA-256 of the text made of one line `" \n"` per file, in `files` order (the `sha256sum` format). From the repository root: `sha256sum | sha256sum`. - A client that verifies the download compares the bytes it received with `sha256`; a change of `content_sha256` between two reads of the index means the module's content changed. - This index is itself a file on `main` (and GitHub Pages), so the hashes protect against a changed file with an unchanged index, not against a compromised `main`. Review of what is merged (CONTRIBUTING "Security review") is the control for that. -- The `Build Modules API` bot re-hashes whatever is on `main`, so the hashes attest that the index and the files agree, not that anyone reviewed them. Branch protection and review are the real control. +- Nothing regenerates the hashes on `main` automatically: every PR must commit the regenerated API (`build_api.py --check` in `checks.yml`), and the `Build Modules API` workflow only verifies `main` after a push. The hashes therefore attest that the index and the files agree; the required review on `main` (repository ruleset) is the real control. ## `courses.json` From 4884b483c2001e6af9f29ebfe5137e505a6d20f1 Mon Sep 17 00:00:00 2001 From: Mohammad Galib Date: Mon, 30 Nov 2026 22:57:48 +0530 Subject: [PATCH 4/4] test: build-api workflow verifies main and pushes refreshes to a branch Co-Authored-By: Claude Opus 5.5 --- tests/test_wave2_repo.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/test_wave2_repo.py b/tests/test_wave2_repo.py index 76da456..1d74e01 100644 --- a/tests/test_wave2_repo.py +++ b/tests/test_wave2_repo.py @@ -142,11 +142,16 @@ def load_yaml(name): def test_build_api_workflow_triggers_and_runs_the_script(): wf = load_yaml("build-api.yml") on = wf.get("on", wf.get(True)) - assert set(on["push"]["paths"]) == {"modules/**", "courses/**", "shared/**"} + assert {"modules/**", "courses/**", "shared/**"} <= set(on["push"]["paths"]) text = (ROOT / ".github/workflows/build-api.yml").read_text() assert "scripts/build_api.py" in text and "fetch-depth: 0" in text assert "api/courses.json" in text assert "datetime" not in text + # ADR-010: main is verified, never committed to by the bot; refreshes go to a reviewed branch + assert "scripts/build_api.py --check" in text + assert "git push origin \"$branch\"" in text + assert "schedule" not in on + assert "git push && exit 0" not in text def test_pr_workflow_runs_every_check():