Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: create auth secret and token files with owner only permissions

lukiod255e00b19c2a
diff --git a/deeptutor/multi_user/identity.py b/deeptutor/multi_user/identity.py
index 989c76518..34852a62c 100644
--- a/deeptutor/multi_user/identity.py
+++ b/deeptutor/multi_user/identity.py
@@ -13,6 +13,7 @@ from uuid import uuid4
from .models import Role
from .paths import PROJECT_ROOT, SYSTEM_ROOT, migrate_legacy_multi_user_tree
+from deeptutor.utils.secret_files import write_secret_text
logger = logging.getLogger(__name__)
@@ -110,12 +111,7 @@ def _migrate_secret() -> None:
try:
secret = LEGACY_SECRET_FILE.read_text(encoding="utf-8").strip()
if secret:
- SECRET_FILE.parent.mkdir(parents=True, exist_ok=True)
- SECRET_FILE.write_text(secret, encoding="utf-8")
- try:
- SECRET_FILE.chmod(0o600)
- except OSError:
- pass
+ write_secret_text(SECRET_FILE, secret)
logger.info("Migrated auth secret from %s to %s", LEGACY_SECRET_FILE, SECRET_FILE)
except Exception as exc:
logger.warning("Failed to migrate legacy auth secret: %s", exc)
@@ -308,13 +304,8 @@ def load_or_create_auth_secret() -> str:
existing = SECRET_FILE.read_text(encoding="utf-8").strip()
if existing:
return existing
- SECRET_FILE.parent.mkdir(parents=True, exist_ok=True)
generated = secrets.token_hex(32)
- SECRET_FILE.write_text(generated, encoding="utf-8")
- try:
- SECRET_FILE.chmod(0o600)
- except OSError:
- pass
+ write_secret_text(SECRET_FILE, generated)
logger.warning(
"Auth is enabled and no auth_secret file exists. Generated a stable local secret at %s.",
SECRET_FILE,
diff --git a/deeptutor/services/skill/credentials.py b/deeptutor/services/skill/credentials.py
index 18c6bb973..dd6f629d1 100644
--- a/deeptutor/services/skill/credentials.py
+++ b/deeptutor/services/skill/credentials.py
@@ -19,6 +19,7 @@ from pathlib import Path
from typing import Any
from deeptutor.services.path_service import get_path_service
+from deeptutor.utils.secret_files import write_secret_text
logger = logging.getLogger(__name__)
@@ -77,12 +78,7 @@ def store_token(
tokens = {}
data["tokens"] = tokens
tokens[hub] = {"token": token, "login": login, "name": name}
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
- try:
- path.chmod(0o600)
- except OSError:
- pass
+ write_secret_text(path, json.dumps(data, indent=2, ensure_ascii=False) + "\n")
def clear_token(hub: str) -> bool:
diff --git a/deeptutor/utils/secret_files.py b/deeptutor/utils/secret_files.py
new file mode 100644
index 000000000..a0a3caf57
--- /dev/null
+++ b/deeptutor/utils/secret_files.py
@@ -0,0 +1,35 @@
+"""Helpers for writing files that hold secrets."""
+
+from __future__ import annotations
+
+import contextlib
+import os
+from pathlib import Path
+
+SECRET_FILE_MODE = 0o600
+SECRET_DIR_MODE = 0o700
+
+
+def write_secret_text(path: Path, text: str) -> None:
+ """Write *text* to *path*, readable only by the owner.
+
+ The mode is applied at creation rather than by a later ``chmod``, which
+ would leave the contents world-readable in between.
+ """
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with contextlib.suppress(OSError):
+ path.parent.chmod(SECRET_DIR_MODE)
+
+ # O_CREAT does not apply the mode to an existing file, so a leftover from an
+ # interrupted run must be replaced rather than truncated.
+ with contextlib.suppress(FileNotFoundError):
+ path.unlink()
+
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, SECRET_FILE_MODE)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(text)
+ except BaseException:
+ with contextlib.suppress(OSError):
+ path.unlink()
+ raise