public-release phases 1-3: read-only public mode, gunicorn container, demo bootstrap, CI, README
- before_request guard: visitors browse + explore; writes need PHYSCOM_ADMIN_TOKEN login - SameSite=Lax/HttpOnly cookies, persisted secret key, debug off unless FLASK_DEBUG=1 - non-root gunicorn container with healthcheck; physcom demo --if-empty on first start - landing page Top Concepts, write controls hidden from visitors - CI workflow, pyproject metadata, compose Ollama parity, README rewrite - tests/test_web_access.py: access control + GET smoke test of every page Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -2,11 +2,12 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Flask, g
|
||||
from flask import Flask, abort, g, redirect, render_template, request, session, url_for
|
||||
|
||||
from physcom.db.schema import init_db
|
||||
from physcom.db.repository import Repository
|
||||
@@ -15,12 +16,41 @@ from physcom.units import format_quantity
|
||||
|
||||
DEFAULT_DB = Path("data/physcom.db")
|
||||
|
||||
# Everything a read-only visitor may not reach. Writes (any non-GET) are
|
||||
# locked separately, except the purely exploratory results.explore.
|
||||
ADMIN_GET_ENDPOINTS = {"pipeline.pipeline_form", "entities.entity_new", "domains.domain_new"}
|
||||
PUBLIC_POST_ENDPOINTS = {"results.explore", "login"}
|
||||
|
||||
|
||||
def db_path() -> Path:
|
||||
return Path(os.environ.get("PHYSCOM_DB", str(DEFAULT_DB)))
|
||||
|
||||
|
||||
def _secret_key() -> str:
|
||||
"""FLASK_SECRET_KEY, else a key persisted next to the DB so admin
|
||||
sessions survive restarts."""
|
||||
key = os.environ.get("FLASK_SECRET_KEY")
|
||||
if key:
|
||||
return key
|
||||
path = db_path().parent / ".secret_key"
|
||||
try:
|
||||
return path.read_text().strip()
|
||||
except FileNotFoundError:
|
||||
key = secrets.token_hex(32)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(key)
|
||||
return key
|
||||
|
||||
|
||||
def is_admin() -> bool:
|
||||
from flask import current_app
|
||||
return current_app.config["OPEN_ACCESS"] or session.get("admin", False)
|
||||
|
||||
|
||||
def get_repo() -> Repository:
|
||||
"""Return a Repository scoped to the current request."""
|
||||
if "repo" not in g:
|
||||
db_path = Path(os.environ.get("PHYSCOM_DB", str(DEFAULT_DB)))
|
||||
conn = init_db(db_path)
|
||||
conn = init_db(db_path())
|
||||
g.repo = Repository(conn)
|
||||
return g.repo
|
||||
|
||||
@@ -31,9 +61,56 @@ def close_db(exc: BaseException | None = None) -> None:
|
||||
repo.conn.close()
|
||||
|
||||
|
||||
def create_app() -> Flask:
|
||||
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
|
||||
(no token set = no one can write)."""
|
||||
app = Flask(__name__)
|
||||
app.secret_key = os.environ.get("FLASK_SECRET_KEY") or secrets.token_hex(32)
|
||||
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",
|
||||
)
|
||||
app.jinja_env.globals["is_admin"] = is_admin
|
||||
|
||||
@app.before_request
|
||||
def require_admin():
|
||||
if is_admin() or request.endpoint in (None, "static"):
|
||||
return None
|
||||
blueprint = request.endpoint.split(".")[0]
|
||||
if request.method in ("GET", "HEAD"):
|
||||
if blueprint == "admin" or request.endpoint in ADMIN_GET_ENDPOINTS:
|
||||
return redirect(url_for("login", next=request.path))
|
||||
return None
|
||||
if request.endpoint not in PUBLIC_POST_ENDPOINTS:
|
||||
abort(403)
|
||||
return None
|
||||
|
||||
@app.route("/login", methods=["GET", "POST"])
|
||||
def login():
|
||||
error = None
|
||||
if request.method == "POST":
|
||||
given = request.form.get("token", "")
|
||||
if admin_token and hmac.compare_digest(given, admin_token):
|
||||
session.clear()
|
||||
session["admin"] = True
|
||||
session.permanent = True
|
||||
target = request.args.get("next", "")
|
||||
# Only same-site relative paths, never "//evil.com".
|
||||
if not target.startswith("/") or target.startswith("//"):
|
||||
target = url_for("index")
|
||||
return redirect(target)
|
||||
error = "Wrong token." if admin_token else "Admin login is disabled (PHYSCOM_ADMIN_TOKEN not set)."
|
||||
return render_template("login.html", error=error), (401 if error else 200)
|
||||
|
||||
@app.route("/logout", methods=["POST"])
|
||||
def logout():
|
||||
session.clear()
|
||||
return redirect(url_for("index"))
|
||||
|
||||
app.jinja_env.filters["qty"] = format_quantity
|
||||
|
||||
@@ -54,7 +131,6 @@ def create_app() -> Flask:
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
from flask import render_template
|
||||
repo = get_repo()
|
||||
entities = repo.list_entities()
|
||||
dims = {e.dimension for e in entities}
|
||||
@@ -66,12 +142,21 @@ def create_app() -> Flask:
|
||||
"domains": len(domains),
|
||||
"combinations": sum(status_counts.values()),
|
||||
}
|
||||
return render_template("home.html", stats=stats)
|
||||
top_concepts = []
|
||||
for d in domains:
|
||||
top = repo.get_top_results(d.name, limit=1)
|
||||
if top and top[0]["composite_score"]:
|
||||
top_concepts.append((d, top[0]))
|
||||
return render_template("home.html", stats=stats, top_concepts=top_concepts)
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def run() -> None:
|
||||
"""Entry point for `physcom-web` script."""
|
||||
app = create_app()
|
||||
app.run(host=os.environ.get("HOST", "127.0.0.1"), debug=True, port=int(os.environ.get("PORT", "5000")))
|
||||
app = create_app(open_access=True)
|
||||
app.run(
|
||||
host=os.environ.get("HOST", "127.0.0.1"),
|
||||
debug=os.environ.get("FLASK_DEBUG") == "1",
|
||||
port=int(os.environ.get("PORT", "5000")),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user