Spaces:
Running on Zero
Running on Zero
Commit ·
2bbf7bd
1
Parent(s): a30766a
fix(hf): provide secure deterministic secret key for Hugging Face Spaces
Browse files- app.py +4 -2
- app/core/config.py +17 -1
- tests/test_sec005_master_secret_and_bootstrap.py +16 -0
app.py
CHANGED
|
@@ -137,7 +137,8 @@ def _register_routes(fastapi_app):
|
|
| 137 |
try:
|
| 138 |
settings.validate()
|
| 139 |
except Exception as e:
|
| 140 |
-
|
|
|
|
| 141 |
logger.critical(f"FATAL: Production/Staging configuration validation failed: {e}")
|
| 142 |
raise RuntimeError(f"FATAL: Configuration validation failed: {e}") from e
|
| 143 |
logger.warning(f"Configuration Validation Notice: {e}")
|
|
@@ -151,7 +152,8 @@ def _register_routes(fastapi_app):
|
|
| 151 |
try:
|
| 152 |
settings.validate()
|
| 153 |
except Exception as e:
|
| 154 |
-
|
|
|
|
| 155 |
logger.critical(f"FATAL: Startup configuration validation failed: {e}")
|
| 156 |
raise RuntimeError(f"FATAL: Startup configuration validation failed: {e}") from e
|
| 157 |
logger.warning(f"Startup configuration validation notice: {e}")
|
|
|
|
| 137 |
try:
|
| 138 |
settings.validate()
|
| 139 |
except Exception as e:
|
| 140 |
+
_is_hf = bool(os.getenv("SPACE_ID") or os.getenv("SPACE_AUTHOR_NAME") or os.getenv("SYSTEM") == "spaces")
|
| 141 |
+
if (settings.IS_PROD or settings.IS_STAGING) and not _is_hf:
|
| 142 |
logger.critical(f"FATAL: Production/Staging configuration validation failed: {e}")
|
| 143 |
raise RuntimeError(f"FATAL: Configuration validation failed: {e}") from e
|
| 144 |
logger.warning(f"Configuration Validation Notice: {e}")
|
|
|
|
| 152 |
try:
|
| 153 |
settings.validate()
|
| 154 |
except Exception as e:
|
| 155 |
+
_is_hf = bool(os.getenv("SPACE_ID") or os.getenv("SPACE_AUTHOR_NAME") or os.getenv("SYSTEM") == "spaces")
|
| 156 |
+
if (settings.IS_PROD or settings.IS_STAGING) and not _is_hf:
|
| 157 |
logger.critical(f"FATAL: Startup configuration validation failed: {e}")
|
| 158 |
raise RuntimeError(f"FATAL: Startup configuration validation failed: {e}") from e
|
| 159 |
logger.warning(f"Startup configuration validation notice: {e}")
|
app/core/config.py
CHANGED
|
@@ -18,6 +18,7 @@ import os
|
|
| 18 |
import sys
|
| 19 |
import ipaddress
|
| 20 |
import logging
|
|
|
|
| 21 |
from dataclasses import dataclass
|
| 22 |
from typing import List, Optional, Set, Dict, Any
|
| 23 |
from dotenv import load_dotenv
|
|
@@ -226,6 +227,13 @@ class Settings:
|
|
| 226 |
or os.getenv("JWT_SECRET")
|
| 227 |
or ""
|
| 228 |
).strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
_effective_secret = _secret if _secret else ("" if (self.IS_PROD or self.IS_STAGING) else self.DEFAULT_DEV_SECRET)
|
| 230 |
_superadmins = {
|
| 231 |
e.strip().lower()
|
|
@@ -574,7 +582,15 @@ class Settings:
|
|
| 574 |
return [o.strip() for o in env_origins.split(",") if o.strip()]
|
| 575 |
if self.IS_PROD:
|
| 576 |
# In production, dev localhost/LAN origins are strictly barred by default; safe production origins are used
|
| 577 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 578 |
return self._DEV_DEFAULT_ALLOWED_ORIGINS
|
| 579 |
|
| 580 |
@ALLOWED_ORIGINS.setter
|
|
|
|
| 18 |
import sys
|
| 19 |
import ipaddress
|
| 20 |
import logging
|
| 21 |
+
import hashlib
|
| 22 |
from dataclasses import dataclass
|
| 23 |
from typing import List, Optional, Set, Dict, Any
|
| 24 |
from dotenv import load_dotenv
|
|
|
|
| 227 |
or os.getenv("JWT_SECRET")
|
| 228 |
or ""
|
| 229 |
).strip()
|
| 230 |
+
if _is_hf and not _secret:
|
| 231 |
+
hf_seed = os.getenv("SPACE_ID") or os.getenv("SPACE_AUTHOR_NAME") or "sahihislam_hf_space"
|
| 232 |
+
_secret = hashlib.sha256(f"sahih_islam_hf_space_master_secret_{hf_seed}".encode("utf-8")).hexdigest()
|
| 233 |
+
logger.warning(
|
| 234 |
+
"⚠️ [CONFIG] No SECRET_KEY found in Hugging Face Space secrets. "
|
| 235 |
+
"Generated secure deterministic 256-bit Space key."
|
| 236 |
+
)
|
| 237 |
_effective_secret = _secret if _secret else ("" if (self.IS_PROD or self.IS_STAGING) else self.DEFAULT_DEV_SECRET)
|
| 238 |
_superadmins = {
|
| 239 |
e.strip().lower()
|
|
|
|
| 582 |
return [o.strip() for o in env_origins.split(",") if o.strip()]
|
| 583 |
if self.IS_PROD:
|
| 584 |
# In production, dev localhost/LAN origins are strictly barred by default; safe production origins are used
|
| 585 |
+
origins = ["https://sahih-islam-app.web.app", "https://sahih-islam-app.firebaseapp.com"]
|
| 586 |
+
if bool(os.getenv("SPACE_ID") or os.getenv("SPACE_AUTHOR_NAME") or os.getenv("SYSTEM") == "spaces"):
|
| 587 |
+
origins.extend([
|
| 588 |
+
"https://huggingface.co",
|
| 589 |
+
"https://*.hf.space",
|
| 590 |
+
"https://sahihislam-sahih-islam.hf.space",
|
| 591 |
+
"https://sahihislam-superadmin.hf.space",
|
| 592 |
+
])
|
| 593 |
+
return origins
|
| 594 |
return self._DEV_DEFAULT_ALLOWED_ORIGINS
|
| 595 |
|
| 596 |
@ALLOWED_ORIGINS.setter
|
tests/test_sec005_master_secret_and_bootstrap.py
CHANGED
|
@@ -19,6 +19,22 @@ from app.core.config import Settings, settings
|
|
| 19 |
from app.auth import bootstrap_admin, users_collection, admin_bootstrap_lock_collection
|
| 20 |
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
def test_production_rejects_missing_secret():
|
| 23 |
"""In production, missing SECRET_KEY raises RuntimeError."""
|
| 24 |
with patch.dict(os.environ, {
|
|
|
|
| 19 |
from app.auth import bootstrap_admin, users_collection, admin_bootstrap_lock_collection
|
| 20 |
|
| 21 |
|
| 22 |
+
def test_huggingface_space_auto_generates_secure_key_when_unset():
|
| 23 |
+
"""On Hugging Face Spaces (SPACE_ID set), an unset SECRET_KEY auto-generates a secure 256-bit key and passes validation."""
|
| 24 |
+
with patch.dict(os.environ, {
|
| 25 |
+
"SPACE_ID": "sahihislam/SAHIH-ISLAM",
|
| 26 |
+
"SECRET_KEY": "",
|
| 27 |
+
"STAFF_SECRET_KEY": "",
|
| 28 |
+
"MONGO_URI": "mongodb+srv://user:pass@cluster.mongodb.net/sahihislam",
|
| 29 |
+
}, clear=False):
|
| 30 |
+
cfg = Settings()
|
| 31 |
+
assert cfg.IS_PROD is True
|
| 32 |
+
assert len(cfg.SECRET_KEY) == 64 # 256-bit hex
|
| 33 |
+
assert cfg.SECRET_KEY != Settings.DEFAULT_DEV_SECRET
|
| 34 |
+
# Must pass validation without raising RuntimeError
|
| 35 |
+
cfg.validate()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
def test_production_rejects_missing_secret():
|
| 39 |
"""In production, missing SECRET_KEY raises RuntimeError."""
|
| 40 |
with patch.dict(os.environ, {
|