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")),
|
||||
)
|
||||
|
||||
@@ -3,9 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Blueprint, flash, redirect, render_template, request, url_for
|
||||
|
||||
@@ -138,8 +136,8 @@ def pipeline_run():
|
||||
run_id = repo.create_pipeline_run(domain.id, config)
|
||||
|
||||
# Resolve DB path for the background thread
|
||||
from physcom_web.app import DEFAULT_DB
|
||||
db_path = str(Path(os.environ.get("PHYSCOM_DB", str(DEFAULT_DB))))
|
||||
from physcom_web.app import db_path as _db_path
|
||||
db_path = str(_db_path())
|
||||
|
||||
# Start background thread
|
||||
t = threading.Thread(
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
from flask import Blueprint, flash, redirect, render_template, request, url_for
|
||||
|
||||
from physcom.engine.constraint_resolver import ConstraintResolver
|
||||
@@ -104,9 +106,10 @@ def explore(domain_name: str, combo_id: int):
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
return float(raw)
|
||||
value = float(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
return value if math.isfinite(value) else None
|
||||
|
||||
explore_result = _run_evaluate(
|
||||
repo, domain, combo,
|
||||
|
||||
@@ -704,3 +704,14 @@ select option {
|
||||
|
||||
/* ── Google Fonts import ─────────────────────────────────── */
|
||||
@import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap');
|
||||
|
||||
/* Read-only public mode: hide every write control (the server rejects them anyway). */
|
||||
body.readonly form[method="post"]:not(.public) { display: none; }
|
||||
|
||||
.nav-logout { display: inline; margin: 0; }
|
||||
.nav-logout button {
|
||||
background: none; border: none; cursor: pointer;
|
||||
color: var(--text-secondary); font: inherit; font-size: 0.88rem; font-weight: 500;
|
||||
padding: 0.4rem 0.75rem; border-radius: var(--radius);
|
||||
}
|
||||
.nav-logout button:hover { color: var(--text-primary); background: var(--bg-elevated); }
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
|
||||
<script src="https://unpkg.com/htmx.org@2.0.4"></script>
|
||||
</head>
|
||||
<body>
|
||||
<body{% if not is_admin() %} class="readonly"{% endif %}>
|
||||
<nav>
|
||||
<a href="{{ url_for('index') }}" class="nav-brand">
|
||||
<img src="{{ url_for('static', filename='logo.svg') }}" alt="">
|
||||
@@ -17,9 +17,14 @@
|
||||
<ul>
|
||||
<li><a href="{{ url_for('entities.entity_list') }}">Entities</a></li>
|
||||
<li><a href="{{ url_for('domains.domain_list') }}">Domains</a></li>
|
||||
<li><a href="{{ url_for('pipeline.pipeline_form') }}">Pipeline</a></li>
|
||||
<li><a href="{{ url_for('results.results_index') }}">Results</a></li>
|
||||
{% if is_admin() %}
|
||||
<li><a href="{{ url_for('pipeline.pipeline_form') }}">Pipeline</a></li>
|
||||
<li><a href="{{ url_for('admin.admin_index') }}">Admin</a></li>
|
||||
{% if not config.OPEN_ACCESS %}
|
||||
<li><form method="post" action="{{ url_for('logout') }}" class="nav-logout"><button type="submit">Log out</button></form></li>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Domains</h1>
|
||||
<a href="{{ url_for('domains.domain_new') }}" class="btn btn-primary">New Domain</a>
|
||||
{% if is_admin() %}<a href="{{ url_for('domains.domain_new') }}" class="btn btn-primary">New Domain</a>{% endif %}
|
||||
</div>
|
||||
|
||||
{% if not domains %}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
{% block content %}
|
||||
<div class="page-header">
|
||||
<h1>Entities</h1>
|
||||
<a href="{{ url_for('entities.entity_new') }}" class="btn btn-primary">+ Add Entity</a>
|
||||
{% if is_admin() %}<a href="{{ url_for('entities.entity_new') }}" class="btn btn-primary">+ Add Entity</a>{% endif %}
|
||||
</div>
|
||||
|
||||
{% if not grouped %}
|
||||
|
||||
@@ -14,11 +14,41 @@
|
||||
entity combinations against real-world physics.
|
||||
</p>
|
||||
<div class="hero-actions">
|
||||
{% if is_admin() %}
|
||||
<a href="{{ url_for('pipeline.pipeline_form') }}" class="btn btn-primary">Run Pipeline</a>
|
||||
<a href="{{ url_for('results.results_index') }}" class="btn">View Results</a>
|
||||
{% endif %}
|
||||
<a href="{{ url_for('results.results_index') }}" class="btn{% if not is_admin() %} btn-primary{% endif %}">View Results</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if top_concepts %}
|
||||
<!-- Best concept per domain -->
|
||||
<h2 class="section-heading">Top Concepts</h2>
|
||||
<p class="section-desc">
|
||||
The highest-scoring surviving combination in each domain, out of
|
||||
{{ stats.combinations }} generated.
|
||||
</p>
|
||||
<div class="card">
|
||||
<table>
|
||||
<thead><tr><th>Domain</th><th>Concept</th><th>Score</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for domain, r in top_concepts %}
|
||||
<tr>
|
||||
<td>{{ domain.name }}</td>
|
||||
<td>{{ r.combination.entities|map(attribute='name')|join(' + ') }}</td>
|
||||
<td class="score-cell">{{ "%.4f"|format(r.composite_score) }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('results.result_detail', domain_name=domain.name, combo_id=r.combination.id) }}"
|
||||
class="btn btn-sm">View</a>
|
||||
<a href="{{ url_for('results.results_domain', domain_name=domain.name) }}" class="btn btn-sm">All</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- How It Works -->
|
||||
<h2 class="section-heading">How It Works</h2>
|
||||
<p class="section-desc">
|
||||
|
||||
16
src/physcom_web/templates/login.html
Normal file
16
src/physcom_web/templates/login.html
Normal file
@@ -0,0 +1,16 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Admin login — PhysCom{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Admin login</h1>
|
||||
<div class="card">
|
||||
{% if error %}<div class="flash flash-error">{{ error }}</div>{% endif %}
|
||||
<form method="post" class="public">
|
||||
<div class="form-group">
|
||||
<label for="token">Admin token</label>
|
||||
<input type="password" id="token" name="token" required autofocus autocomplete="current-password">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Log in</button>
|
||||
</form>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -58,7 +58,7 @@
|
||||
{% if status_filter or rating_filter %}
|
||||
<p class="empty">No results matching that filter in this domain.</p>
|
||||
{% else %}
|
||||
<p class="empty">No results for this domain yet. <a href="{{ url_for('pipeline.pipeline_form') }}">Run the pipeline</a> first.</p>
|
||||
<p class="empty">No results for this domain yet.{% if is_admin() %} <a href="{{ url_for('pipeline.pipeline_form') }}">Run the pipeline</a> first.{% endif %}</p>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<table>
|
||||
|
||||
Reference in New Issue
Block a user