From af401d6bc2c22726c99aa1e42a47a85abe33b2ac Mon Sep 17 00:00:00 2001 From: asimonson1125 Date: Fri, 25 Sep 2026 17:27:55 -0500 Subject: [PATCH] dev server uses admin login too: localhost shows the public view Drop open_access; run() prints a one-off PHYSCOM_ADMIN_TOKEN when none is set. Co-Authored-By: Claude --- CLAUDE.md | 4 ++-- IMPLEMENTATION_PLAN.md | 2 +- README.md | 4 ++-- src/physcom_web/app.py | 18 ++++++++++-------- src/physcom_web/templates/base.html | 2 -- tests/test_web_access.py | 21 ++++++++++----------- 6 files changed, 25 insertions(+), 26 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 79cfe1f..24365e1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,7 +12,7 @@ PhysCom (Physical Combinatorics) — innovation discovery engine that generates - **Tests (all)**: `python -m pytest tests/ -q` (~130 tests, ~2 min). Run after every change. - **Single test file**: `python -m pytest tests/test_scorer.py -q` - **Single test**: `python -m pytest tests/test_scorer.py::test_score_combination -q` -- **Web dev server**: `python -m physcom_web` (localhost, open access, debug only with `FLASK_DEBUG=1`) +- **Web dev server**: `python -m physcom_web` (localhost, public read-only view; log in at `/login` with `PHYSCOM_ADMIN_TOKEN` or the one-off token it prints; debug only with `FLASK_DEBUG=1`) - **CLI**: `python -m physcom` (or `physcom` if installed) - **Docker**: `docker compose up web` / `docker compose run cli physcom seed` - **Demo data**: `python -m physcom demo` seeds + runs passes 1-3 for every domain (~20s). The Docker image does this on first start (`--if-empty`). DB is `data/physcom.db` or `$PHYSCOM_DB`. @@ -58,7 +58,7 @@ tests/ # pytest, uses seeded_repo fixture from conftest.py - **`save_combination`** loads existing status/block_reason on dedup (important for resume). - **`ensure_metric`** backfills unit if the row already exists with an empty unit. - **MetricBound** carries `unit` — flows through seed → ensure_metric → metrics table → get_combination_scores → template display. -- **Read-only public mode**: `create_app()` locks every non-GET (except `results.explore`) and the admin/pipeline/new pages behind a session login with `PHYSCOM_ADMIN_TOKEN`. Only the dev server (`run()` → `create_app(open_access=True)`) is open, and only while no token is set. Templates use `is_admin()`; `body.readonly` hides every `form[method=post]` via CSS — a new write form needs no template guard, but a new public POST must be added to `PUBLIC_POST_ENDPOINTS`. +- **Read-only public mode**: `create_app()` locks every non-GET (except `results.explore`) and the admin/pipeline/new pages behind a session login with `PHYSCOM_ADMIN_TOKEN`. The dev server uses the same rules (it prints a one-off token if none is set). Templates use `is_admin()`; `body.readonly` hides every `form[method=post]` via CSS — a new write form needs no template guard, but a new public POST must be added to `PUBLIC_POST_ENDPOINTS`. - **HTMX polling**: `_run_status.html` partial polls every 2s while run is pending/running; stops polling when terminal. ## Data flow (pipeline passes) diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index 313f351..afcc963 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -60,7 +60,7 @@ Skipped until something forces them: | Item | Status | |------|--------| | 1.1 gunicorn, debug off | Done. Dev server debug only with `FLASK_DEBUG=1`. | -| 1.2 read-only public mode | Done. Deviation: an unset token means *nobody* can write under gunicorn, instead of "localhost can write", because behind a reverse proxy every request looks like localhost. The dev server stays open until a token is set. | +| 1.2 read-only public mode | Done. Deviation: an unset token means *nobody* can write under gunicorn, instead of "localhost can write", because behind a reverse proxy every request looks like localhost. The dev server uses the same login; without a token it prints a one-off one. | | 1.3 cookie hardening | Done. `Secure` is opt-in via `PHYSCOM_SECURE_COOKIES=1` so plain-HTTP local Docker can still log in. | | 1.4 explore | Done. Verified it never writes; it costs about 45 ms per call (measured over 168 combos). Non-finite inputs are now rejected. No app-level rate limit: add one at the proxy if needed. | | 1.5 secret key | Done differently: instead of refusing to start, an unset key is generated once and saved next to the DB. | diff --git a/README.md b/README.md index f8a3899..5125c7b 100644 --- a/README.md +++ b/README.md @@ -59,10 +59,10 @@ docker compose run --rm cli results urban_commuting --top 10 ```bash pip install -e ".[dev,web]" python -m physcom demo # seed + run passes 1-3 for every domain -python -m physcom_web # localhost-only dev server, no login needed +python -m physcom_web # localhost dev server, prints an admin login token ``` -Then open [http://localhost:5000](http://localhost:5000). Set `FLASK_DEBUG=1` for the Werkzeug debugger (never on a reachable host). +Then open [http://localhost:5000](http://localhost:5000). You see the public read-only view; log in at `/login` with the printed token (or your `PHYSCOM_ADMIN_TOKEN`) to edit. Set `FLASK_DEBUG=1` for the Werkzeug debugger (never on a reachable host). Run tests: diff --git a/src/physcom_web/app.py b/src/physcom_web/app.py index 97a26c6..564d5a1 100644 --- a/src/physcom_web/app.py +++ b/src/physcom_web/app.py @@ -44,7 +44,7 @@ def _secret_key() -> str: def is_admin() -> bool: from flask import current_app - return current_app.config["OPEN_ACCESS"] or session.get("admin", False) + return session.get("admin", False) def get_repo() -> Repository: @@ -61,16 +61,13 @@ def close_db(exc: BaseException | None = None) -> None: repo.conn.close() -def create_app(open_access: bool = False) -> Flask: - """open_access=True (the localhost dev server) skips the admin lock - unless PHYSCOM_ADMIN_TOKEN is set. Anything else -- gunicorn in Docker -- - is read-only to visitors; writes need a login with PHYSCOM_ADMIN_TOKEN +def create_app() -> Flask: + """Read-only to visitors; writes need a login with PHYSCOM_ADMIN_TOKEN (no token set = no one can write).""" app = Flask(__name__) app.secret_key = _secret_key() admin_token = os.environ.get("PHYSCOM_ADMIN_TOKEN", "") app.config.update( - OPEN_ACCESS=open_access and not admin_token, SESSION_COOKIE_SAMESITE="Lax", SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SECURE=os.environ.get("PHYSCOM_SECURE_COOKIES") == "1", @@ -153,8 +150,13 @@ def create_app(open_access: bool = False) -> Flask: def run() -> None: - """Entry point for `physcom-web` script.""" - app = create_app(open_access=True) + """Entry point for `physcom-web` script. Same access rules as production, + so localhost shows the public view; without PHYSCOM_ADMIN_TOKEN a one-off + token is generated and printed for /login.""" + if not os.environ.get("PHYSCOM_ADMIN_TOKEN"): + os.environ["PHYSCOM_ADMIN_TOKEN"] = secrets.token_urlsafe(16) + print(f" * Admin login token (this run only): {os.environ['PHYSCOM_ADMIN_TOKEN']}") + app = create_app() app.run( host=os.environ.get("HOST", "127.0.0.1"), debug=os.environ.get("FLASK_DEBUG") == "1", diff --git a/src/physcom_web/templates/base.html b/src/physcom_web/templates/base.html index af1087f..b7584c3 100644 --- a/src/physcom_web/templates/base.html +++ b/src/physcom_web/templates/base.html @@ -21,10 +21,8 @@ {% if is_admin() %}
  • Pipeline
  • Admin
  • - {% if not config.OPEN_ACCESS %}
  • {% endif %} - {% endif %} diff --git a/tests/test_web_access.py b/tests/test_web_access.py index 29c3eb7..42ab6cc 100644 --- a/tests/test_web_access.py +++ b/tests/test_web_access.py @@ -36,7 +36,7 @@ def db_file(tmp_path_factory): return path, ids -def _app(monkeypatch, db_file, token: str | None, open_access: bool = False): +def _app(monkeypatch, db_file, token: str | None): from physcom_web.app import create_app monkeypatch.setenv("PHYSCOM_DB", str(db_file[0])) monkeypatch.setenv("FLASK_SECRET_KEY", "test") @@ -44,7 +44,7 @@ def _app(monkeypatch, db_file, token: str | None, open_access: bool = False): monkeypatch.setenv("PHYSCOM_ADMIN_TOKEN", token) else: monkeypatch.delenv("PHYSCOM_ADMIN_TOKEN", raising=False) - return create_app(open_access=open_access) + return create_app() @pytest.fixture @@ -136,22 +136,21 @@ def test_admin_can_reach_everything(admin, db_file): assert 'class="readonly"' not in html -def test_open_access_dev_server(monkeypatch, db_file): - app = _app(monkeypatch, db_file, None, open_access=True) - assert app.test_client().get("/admin/").status_code == 200 - # Setting a token locks even the dev server. - app = _app(monkeypatch, db_file, TOKEN, open_access=True) - assert app.test_client().get("/admin/").status_code == 302 - - def test_debug_off_by_default(monkeypatch, db_file): import physcom_web.app as web seen = {} monkeypatch.delenv("FLASK_DEBUG", raising=False) + monkeypatch.delenv("PHYSCOM_ADMIN_TOKEN", raising=False) monkeypatch.setenv("PHYSCOM_DB", str(db_file[0])) - monkeypatch.setattr("flask.Flask.run", lambda self, **kw: seen.update(kw)) + monkeypatch.setattr("flask.Flask.run", lambda self, **kw: seen.update(kw, app=self)) web.run() assert seen["debug"] is False and seen["host"] == "127.0.0.1" + # Dev server shows the public view too; the printed token logs in. + client = seen["app"].test_client() + assert client.get("/admin/").status_code == 302 + token = web.os.environ["PHYSCOM_ADMIN_TOKEN"] + assert client.post("/login", data={"token": token}).status_code == 302 + assert client.get("/admin/").status_code == 200 def test_cli_demo_if_empty_skips_populated_db(db_file):