Allow configured proxy login origins
This commit is contained in:
1 parent
201e3a5134
commit
2e09c56f4d
4 files changed
+64
-16
No files matched your search
@@ -5,3 +5,5 @@ PRIMETHAI_SESSION_SECRET=CHANGE_ME
|
||||
PRIMETHAI_SESSION_TTL_HOURS=168
|
||||
# auto adds Secure when the HTTPS proxy sends X-Forwarded-Proto: https.
|
||||
PRIMETHAI_COOKIE_SECURE=auto
|
||||
# Optional comma-separated public origins if the reverse proxy cannot preserve each request's Host header.
|
||||
# PRIMETHAI_ALLOWED_ORIGINS=https://trade.example.com,https://stocks.example.net
|
||||
@@ -250,7 +250,7 @@ Run the strategy dashboard from the project folder:
|
||||
python -m primethai webui
|
||||
```
|
||||
|
||||
The app requires a local `.env` file for its login. The project has a generated `.env` for this workspace; for another installation, copy `.env.example` to `.env` and set a username, a unique password of at least 12 characters, and a random session secret of at least 32 bytes. The `.env` file is excluded from Git. `PRIMETHAI_SESSION_TTL_HOURS` controls how long a login lasts (default 168 hours); `PRIMETHAI_COOKIE_SECURE=auto` enables secure cookies when an HTTPS reverse proxy sends `X-Forwarded-Proto: https`. Restart the server after changing these settings.
|
||||
The app requires a local `.env` file for its login. The project has a generated `.env` for this workspace; for another installation, copy `.env.example` to `.env` and set a username, a unique password of at least 12 characters, and a random session secret of at least 32 bytes. The `.env` file is excluded from Git. `PRIMETHAI_SESSION_TTL_HOURS` controls how long a login lasts (default 168 hours); `PRIMETHAI_COOKIE_SECURE=auto` enables secure cookies when an HTTPS reverse proxy sends `X-Forwarded-Proto: https`. The app accepts the current public host when the proxy preserves the original `Host` or `X-Forwarded-Host` and `X-Forwarded-Proto` headers. If the proxy uses a fixed internal host, list the accepted full public origins in `PRIMETHAI_ALLOWED_ORIGINS`, separated by commas, for example `https://trade.example.com,https://stocks.example.net`. Include a non-default port in the origin. Restart the server after changing these settings.
|
||||
|
||||
Then open `http://127.0.0.1:18900` and sign in. The same login protects the portfolio page, backtest page, and API; there is also an **ออกจากระบบ** button. Sessions use signed, HTTP-only, same-site cookies and expire after the configured lifetime. The home page is the portfolio book; the historical chart and simulation are at `/backtest`. At startup, the service checks SiamChart and downloads the latest EOD ZIP unless a successful after-close refresh has already happened that day, then recalculates signals. It merges each dated CSV into a cumulative local archive instead of replacing earlier sessions; `data/raw/siamchart/set-archive_EOD_LAST.sources.json` records the provider and coverage for each stored session. It repeats automatically on Thai weekdays after 20:30 Asia/Bangkok and retries network failures every 30 minutes. If SiamChart fails after the close, Yahoo Finance through `yfinance` is the secondary feed. The fallback must include a SET index bar and at least 95% of the previous session's top-100 liquid model universe, plus current signal/held symbols, before its data is accepted. If it cannot meet that check, the app keeps the prior complete price history and shows its date; there is no upload step. The **อัปเดตสัญญาณ** button remains as an optional immediate refresh. The service process must remain running for scheduled refreshes. The calculation runs on the server and can take a few minutes.
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
ENV_PATH = Path(__file__).resolve().parent.parent / ".env"
|
||||
@@ -26,6 +27,58 @@ class AuthConfig:
|
||||
session_secret: bytes = field(repr=False)
|
||||
session_ttl_seconds: int = 7 * 24 * 60 * 60
|
||||
cookie_secure: str = "auto"
|
||||
allowed_origins: frozenset[str] = field(default_factory=frozenset)
|
||||
|
||||
|
||||
def normalize_origin(value: str) -> str | None:
|
||||
"""Return a canonical HTTP(S) origin, rejecting full URLs and malformed hosts."""
|
||||
value = value.strip()
|
||||
if not value or "\\" in value or any(char.isspace() for char in value):
|
||||
return None
|
||||
try:
|
||||
parsed = urlsplit(value)
|
||||
port = parsed.port
|
||||
except ValueError:
|
||||
return None
|
||||
scheme = parsed.scheme.casefold()
|
||||
if (
|
||||
scheme not in {"http", "https"}
|
||||
or parsed.hostname is None
|
||||
or parsed.username is not None
|
||||
or parsed.password is not None
|
||||
or parsed.path not in {"", "/"}
|
||||
or parsed.query
|
||||
or parsed.fragment
|
||||
):
|
||||
return None
|
||||
host = parsed.hostname.casefold()
|
||||
if ":" in host:
|
||||
host = f"[{host}]"
|
||||
else:
|
||||
try:
|
||||
host = host.encode("idna").decode("ascii").rstrip(".")
|
||||
except UnicodeError:
|
||||
return None
|
||||
if not host:
|
||||
return None
|
||||
if port is not None and not ((scheme == "http" and port == 80) or (scheme == "https" and port == 443)):
|
||||
host = f"{host}:{port}"
|
||||
return f"{scheme}://{host}"
|
||||
|
||||
|
||||
def _allowed_origins_from_env(raw: str) -> frozenset[str]:
|
||||
allowed: set[str] = set()
|
||||
for entry in raw.split(","):
|
||||
entry = entry.strip()
|
||||
if not entry:
|
||||
continue
|
||||
normalized = normalize_origin(entry)
|
||||
if normalized is None:
|
||||
raise RuntimeError(
|
||||
"PRIMETHAI_ALLOWED_ORIGINS ต้องเป็นรายการ origin แบบ http(s)://ชื่อโฮสต์[:พอร์ต] คั่นด้วยจุลภาค"
|
||||
)
|
||||
allowed.add(normalized)
|
||||
return frozenset(allowed)
|
||||
|
||||
|
||||
def _dotenv_value(raw: str) -> str:
|
||||
@@ -100,12 +153,14 @@ def load_auth_config(path: str | Path = ENV_PATH) -> AuthConfig:
|
||||
cookie_secure = os.environ.get("PRIMETHAI_COOKIE_SECURE", "auto").strip().casefold()
|
||||
if cookie_secure not in {"auto", "true", "false"}:
|
||||
raise RuntimeError("PRIMETHAI_COOKIE_SECURE ต้องเป็น auto, true หรือ false")
|
||||
allowed_origins = _allowed_origins_from_env(os.environ.get("PRIMETHAI_ALLOWED_ORIGINS", ""))
|
||||
return AuthConfig(
|
||||
username=username,
|
||||
password=password,
|
||||
session_secret=secret.encode("utf-8"),
|
||||
session_ttl_seconds=ttl_hours * 60 * 60,
|
||||
cookie_secure=cookie_secure,
|
||||
allowed_origins=allowed_origins,
|
||||
)
|
||||
|
||||
|
||||
|
||||
+6
-15
@@ -26,6 +26,7 @@ from .auth import (
|
||||
create_session,
|
||||
expired_session_cookie,
|
||||
load_auth_config,
|
||||
normalize_origin,
|
||||
session_cookie,
|
||||
verify_session,
|
||||
)
|
||||
@@ -589,26 +590,16 @@ def _handler_factory(archives: tuple[Path, ...], report_dir: Path,
|
||||
return forwarded == "https"
|
||||
|
||||
def _same_origin(self) -> bool:
|
||||
origin = self.headers.get("Origin", "")
|
||||
if not origin:
|
||||
return False
|
||||
try:
|
||||
parsed = urlsplit(origin)
|
||||
except ValueError:
|
||||
origin = normalize_origin(self.headers.get("Origin", ""))
|
||||
if origin is None:
|
||||
return False
|
||||
if origin in auth.allowed_origins:
|
||||
return True
|
||||
expected_host = (self.headers.get("X-Forwarded-Host") or self.headers.get("Host", ""))
|
||||
expected_host = expected_host.split(",", 1)[0].strip().casefold()
|
||||
forwarded_proto = self.headers.get("X-Forwarded-Proto", "").split(",", 1)[0].strip().casefold()
|
||||
expected_scheme = forwarded_proto or "http"
|
||||
return bool(
|
||||
parsed.scheme.casefold() == expected_scheme
|
||||
and parsed.netloc.casefold() == expected_host
|
||||
and not parsed.username
|
||||
and not parsed.password
|
||||
and not parsed.path
|
||||
and not parsed.query
|
||||
and not parsed.fragment
|
||||
)
|
||||
return origin == normalize_origin(f"{expected_scheme}://{expected_host}")
|
||||
|
||||
@staticmethod
|
||||
def _safe_next(value: str) -> str:
|
||||
|
||||
Reference in new issue
Block a user