Skip to content

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

fix: Keep env-bootstrapped admin usable and unpromoted (#851)

Souptik Chakrabortya5879735b79a
diff --git a/README.md b/README.md
index 62c4cfe66..eee193bd7 100644
--- a/README.md
+++ b/README.md
@@ -673,7 +673,7 @@ data/
└── system/ # auth · grants · audit · user-secrets/<owner> (OAuth tokens)
```
-The **first registered user becomes admin** and owns model catalogs, provider credentials, shared knowledge bases, skills, and per-user grants. Everyone else gets an isolated workspace and a redacted Settings page — admin-assigned models, KBs, and skills show up as scoped, read-only options, never as raw API keys.
+The **first registered user becomes admin** and owns model catalogs, provider credentials, shared knowledge bases, skills, and per-user grants. Everyone else gets an isolated workspace and a redacted Settings page — admin-assigned models, KBs, and skills show up as scoped, read-only options, never as raw API keys. If `auth.json` already carries a `username` + `password_hash`, that account *is* the admin: `/register` stays closed and accounts created from `/admin/users` are always `role=user` until you promote them.
**Enable it:** turn auth on in `data/user/settings/auth.json`, restart `deeptutor start`, register the first admin at `/register`, then add users from `/admin/users` and assign models, KBs, skills, partners, tool/MCP/CLI-app policy, and code-execution access through grants.
diff --git a/deeptutor/multi_user/identity.py b/deeptutor/multi_user/identity.py
index 989c76518..fa6ec646d 100644
--- a/deeptutor/multi_user/identity.py
+++ b/deeptutor/multi_user/identity.py
@@ -121,6 +121,44 @@ def _migrate_secret() -> None:
logger.warning("Failed to migrate legacy auth secret: %s", exc)
+def _env_bootstrap_admin() -> tuple[str, str]:
+ """Return ``(username, password_hash)`` for the ``auth.json`` bootstrap admin.
+
+ Both halves are required: the shipped default seeds a username with an
+ empty hash, which cannot authenticate and therefore is not an admin. An
+ empty tuple entry means "no bootstrap admin configured".
+
+ :mod:`deeptutor.services.auth` is imported lazily because it imports this
+ module. Its resolved globals — rather than a fresh settings read — are the
+ source of truth on purpose: they are exactly the credentials
+ ``authenticate()`` accepts, so the promotion gate in :func:`save_user` and
+ the login path can never disagree about whether an admin already exists.
+ """
+ try:
+ from deeptutor.services import auth as auth_service
+
+ username = str(getattr(auth_service, "AUTH_USERNAME", "") or "")
+ password_hash = str(getattr(auth_service, "AUTH_PASSWORD_HASH", "") or "")
+ except Exception as exc: # pragma: no cover - auth settings unavailable
+ logger.warning("Could not resolve the bootstrap admin credentials: %s", exc)
+ return "", ""
+ if not username or not password_hash:
+ return "", ""
+ return username, password_hash
+
+
+def _env_admin_record(password_hash: str) -> dict[str, Any]:
+ """Build the in-memory record representing the bootstrap admin."""
+ return {
+ "id": "env-admin",
+ "hash": password_hash,
+ "role": "admin",
+ "created_at": "",
+ "disabled": False,
+ "avatar": "",
+ }
+
+
def load_users( # nosec B107 - empty defaults mean "no env fallback supplied".
env_username: str = "",
env_password_hash: str = "",
@@ -152,21 +190,20 @@ def load_users( # nosec B107 - empty defaults mean "no env fallback supplied".
if USERS_FILE.exists() and changed:
_write_users(canonical)
- if canonical:
- return canonical
-
- if env_username and env_password_hash:
- return {
- env_username: {
- "id": "env-admin",
- "hash": env_password_hash,
- "role": "admin",
- "created_at": "",
- "disabled": False,
- }
- }
+ # The bootstrap admin is merged in whenever it is configured, not only when
+ # the store is empty. Falling back to it only for an empty store locked the
+ # operator who bootstrapped the deployment out of their own instance the
+ # moment the first real account was written (#849). A stored record with the
+ # same username wins, so the account can later be adopted into the store.
+ # The merge is deliberately in-memory only; no write path passes the env
+ # arguments, so the bootstrap hash is never persisted into ``users.json``
+ # where a rotation of ``auth.json`` could no longer supersede it.
+ if env_username and env_password_hash and env_username not in canonical:
+ merged = {env_username: _env_admin_record(env_password_hash)}
+ merged.update(canonical)
+ return merged
- return {}
+ return canonical
def save_user(username: str, hashed_password: str, role: Role = "user") -> dict[str, Any]:
@@ -174,8 +211,17 @@ def save_user(username: str, hashed_password: str, role: Role = "user") -> dict[
# Read-modify-write must be atomic so concurrent first-time registrations
# cannot each see an empty store and each promote themselves to admin.
with _USERS_WRITE_LOCK:
+ # Called without the env arguments on purpose: ``users`` is written back
+ # to disk below, and the bootstrap admin must stay an in-memory overlay.
users = load_users()
- effective_role: Role = "admin" if not users else role
+ env_username, _ = _env_bootstrap_admin()
+ # A configured bootstrap admin counts as an existing account, so the
+ # first account an operator creates from /admin/users is not silently
+ # promoted — that endpoint documents role="user" (#849). Re-saving the
+ # bootstrap admin's own username adopts it into the store instead, and
+ # must keep the admin role.
+ account_exists = bool(users) or (bool(env_username) and env_username != username)
+ effective_role: Role = role if account_exists else "admin"
existing = users.get(username) or {}
record = {
"id": str(existing.get("id") or new_user_id()),
diff --git a/tests/multi_user/conftest.py b/tests/multi_user/conftest.py
index 00b8a8da2..fc8e48df7 100644
--- a/tests/multi_user/conftest.py
+++ b/tests/multi_user/conftest.py
@@ -56,6 +56,15 @@ def mu_isolated_root(tmp_path, monkeypatch) -> Path:
monkeypatch.setattr(grants, "GRANTS_DIR", system_root / "grants")
+ # The ``auth.json`` bootstrap admin is process-global state rather than a
+ # path, and it now takes part in the first-user promotion decision (#849).
+ # Clear it so a developer with real credentials configured sees the same
+ # results as CI; tests that need one patch these back explicitly.
+ from deeptutor.services import auth as auth_service
+
+ monkeypatch.setattr(auth_service, "AUTH_USERNAME", "")
+ monkeypatch.setattr(auth_service, "AUTH_PASSWORD_HASH", "")
+
admin_root.mkdir(parents=True, exist_ok=True)
return tmp_path
diff --git a/tests/multi_user/test_env_bootstrap_admin.py b/tests/multi_user/test_env_bootstrap_admin.py
new file mode 100644
index 000000000..1dab9cdab
--- /dev/null
+++ b/tests/multi_user/test_env_bootstrap_admin.py
@@ -0,0 +1,265 @@
+"""Regression tests for the env/``auth.json`` bootstrap admin (issue #849).
+
+Two deployment shapes have to behave differently, and the identity store used
+to conflate them:
+
+* **Env-bootstrapped** — ``auth.json`` carries ``username`` +
+ ``password_hash`` and ``users.json`` is empty. An admin already exists, so
+ accounts created from ``/admin/users`` must stay ``role="user"`` and the
+ bootstrap admin must keep working after the store gains its first record.
+* **Genuinely empty** — no bootstrap credentials at all. The first account to
+ register is promoted to admin, which is the documented bootstrap path.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+# A real bcrypt hash of "bootstrap-pass-1234", generated in-test so no secret
+# literal is committed.
+_BOOTSTRAP_PASSWORD = "bootstrap-pass-1234" # nosec B105 - test fixture credential
+
+
+def bootstrap_hash() -> str:
+ from deeptutor.services.auth import hash_password
+
+ return hash_password(_BOOTSTRAP_PASSWORD)
+
+
+def env_admin(mu_isolated_root, monkeypatch, bootstrap_hash):
+ """Simulate an ``auth.json``-bootstrapped admin with an empty user store."""
+ from deeptutor.services import auth as auth_service
+
+ monkeypatch.setattr(auth_service, "AUTH_USERNAME", "operator")
+ monkeypatch.setattr(auth_service, "AUTH_PASSWORD_HASH", bootstrap_hash)
+ monkeypatch.setattr(auth_service, "AUTH_ENABLED", True)
+ return "operator"
+
+
+# ---------------------------------------------------------------------------
+# Bug A — the first account created by an admin must not be promoted
+# ---------------------------------------------------------------------------
+
+
+def test_first_created_account_is_not_promoted_when_env_admin_exists(env_admin):
+ """``POST /auth/users`` documents role=``user``; honour that."""
+ from deeptutor.multi_user.identity import save_user
+
+ record = save_user("student1", "$2b$12$placeholder", role="user")
+
+ assert record["role"] == "user"
+
+
+def test_admin_can_still_create_an_explicit_admin_when_env_admin_exists(env_admin):
+ """The gate must not clamp an explicitly requested admin role."""
+ from deeptutor.multi_user.identity import save_user
+
+ record = save_user("deputy", "$2b$12$placeholder", role="admin")
+
+ assert record["role"] == "admin"
+
+
+# ---------------------------------------------------------------------------
+# Bug B — the env bootstrap admin must survive the store gaining records
+# ---------------------------------------------------------------------------
+
+
+def test_env_admin_still_resolves_after_first_account_is_created(env_admin, bootstrap_hash):
+ from deeptutor.multi_user.identity import load_users, save_user
+
+ save_user("student1", "$2b$12$placeholder", role="user")
+
+ users = load_users(env_admin, bootstrap_hash)
+
+ assert set(users) == {env_admin, "student1"}
+ assert users[env_admin]["role"] == "admin"
+ assert users[env_admin]["hash"] == bootstrap_hash
+
+
+def test_env_admin_can_log_in_after_first_account_is_created(env_admin):
+ """End-to-end shape of the reported lockout: login returned 401."""
+ from deeptutor.multi_user.identity import save_user
+ from deeptutor.services.auth import authenticate
+
+ save_user("student1", "$2b$12$placeholder", role="user")
+
+ payload = authenticate(env_admin, _BOOTSTRAP_PASSWORD)
+
+ assert payload is not None
+ assert payload.role == "admin"
+
+
+def test_env_admin_is_never_written_into_the_user_store(env_admin):
+ """The bootstrap admin is an in-memory overlay, not a persisted record.
+
+ Persisting it would pin the hash at the time of the first write, so a
+ later rotation of ``auth.json`` would silently keep accepting the old
+ password.
+ """
+ import json
+
+ from deeptutor.multi_user.identity import USERS_FILE, save_user
+
+ save_user("student1", "$2b$12$placeholder", role="user")
+
+ on_disk = json.loads(USERS_FILE.read_text(encoding="utf-8"))
+ assert set(on_disk) == {"student1"}
+
+
+def test_stored_record_wins_over_env_bootstrap_admin(env_admin):
+ """Re-creating the bootstrap username adopts the account into the store."""
+ from deeptutor.multi_user.identity import load_users, save_user
+
+ save_user(env_admin, "$2b$12$adopted", role="admin")
+
+ users = load_users(env_admin, "$2b$12$fromenv")
+
+ assert users[env_admin]["hash"] == "$2b$12$adopted"
+ assert users[env_admin]["role"] == "admin"
+
+
+def test_adopting_the_bootstrap_username_keeps_admin_role(env_admin):
+ """The adoption write must not be demoted to ``user`` by the new gate."""
+ from deeptutor.multi_user.identity import save_user
+
+ record = save_user(env_admin, "$2b$12$adopted", role="user")
+
+ assert record["role"] == "admin"
+
+
+def test_env_admin_appears_exactly_once_in_the_admin_user_list(env_admin, bootstrap_hash):
+ from deeptutor.multi_user.identity import list_user_info, save_user
+
+ save_user("student1", "$2b$12$placeholder", role="user")
+
+ listed = list_user_info(env_admin, bootstrap_hash)
+ usernames = [item["username"] for item in listed]
+
+ assert usernames.count(env_admin) == 1
+ assert set(usernames) == {env_admin, "student1"}
+
+
+def test_is_first_user_is_false_when_only_the_env_admin_exists(env_admin):
+ from deeptutor.services.auth import is_first_user
+
+ assert is_first_user() is False
+
+
+# ---------------------------------------------------------------------------
+# No-env-admin path — the documented bootstrap behaviour is preserved
+# ---------------------------------------------------------------------------
+
+
+def test_first_account_is_promoted_when_no_env_admin_exists(mu_isolated_root):
+ from deeptutor.multi_user.identity import save_user
+
+ record = save_user("alice", "$2b$12$placeholder", role="user")
+
+ assert record["role"] == "admin"
+
+
+def test_second_account_is_not_promoted_when_no_env_admin_exists(mu_isolated_root):
+ from deeptutor.multi_user.identity import save_user
+
+ save_user("alice", "$2b$12$placeholder", role="user")
+ record = save_user("bob", "$2b$12$placeholder", role="user")
+
+ assert record["role"] == "user"
+
+
+def test_partial_env_credentials_do_not_count_as_an_admin(mu_isolated_root, monkeypatch):
+ """A username with no hash cannot log in, so it must not block promotion.
+
+ This is the shipped default (``auth.json`` seeds ``username="admin"`` with
+ an empty hash), so treating it as an existing admin would leave a fresh
+ deployment with no way to create one.
+ """
+ from deeptutor.multi_user.identity import save_user
+ from deeptutor.services import auth as auth_service
+
+ monkeypatch.setattr(auth_service, "AUTH_USERNAME", "admin")
+ monkeypatch.setattr(auth_service, "AUTH_PASSWORD_HASH", "")
+
+ record = save_user("alice", "$2b$12$placeholder", role="user")
+
+ assert record["role"] == "admin"
+
+
+def test_is_first_user_is_true_for_a_genuinely_empty_deployment(mu_isolated_root):
+ from deeptutor.services.auth import is_first_user
+
+ assert is_first_user() is True
+
+
+# ---------------------------------------------------------------------------
+# End-to-end over the real router — the exact sequence reported in #849
+# ---------------------------------------------------------------------------
+
+
+def bootstrap_client(env_admin, monkeypatch):
+ """TestClient over the auth router, authenticated as the bootstrap admin."""
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ import deeptutor.api.routers.auth as auth_router
+ from deeptutor.services.auth import TokenPayload
+
+ tokens = {
+ "operator-token": TokenPayload(username=env_admin, role="admin", user_id="env-admin"),
+ }
+ monkeypatch.setattr(auth_router, "AUTH_ENABLED", True)
+ monkeypatch.setattr(auth_router, "decode_token", lambda token: tokens.get(token))
+
+ app = FastAPI()
+ app.include_router(auth_router.router, prefix="/api/v1/auth")
+ return TestClient(app), {"Authorization": "Bearer operator-token"}
+
+
+def test_admin_create_user_returns_role_user(bootstrap_client):
+ client, headers = bootstrap_client
+
+ response = client.post(
+ "/api/v1/auth/users",
+ json={"username": "student1", "password": "student-pass-1234"},
+ headers=headers,
+ )
+
+ assert response.status_code == 201
+ body = response.json()
+ assert body["role"] == "user"
+ assert body["is_admin"] is False
+
+
+def test_bootstrap_admin_remains_listed_after_creating_an_account(bootstrap_client, env_admin):
+ client, headers = bootstrap_client
+
+ client.post(
+ "/api/v1/auth/users",
+ json={"username": "student1", "password": "student-pass-1234"},
+ headers=headers,
+ )
+ listed = client.get("/api/v1/auth/users", headers=headers).json()
+
+ by_name = {item["username"]: item for item in listed}
+ assert by_name[env_admin]["role"] == "admin"
+ assert by_name["student1"]["role"] == "user"
+
+
+def test_bootstrap_admin_username_cannot_be_taken_by_a_new_account(bootstrap_client, env_admin):
+ """The bootstrap username is now reserved, so it cannot be clobbered.
+
+ Creating a store record under that name would shadow the overlay and
+ demote the operator, so the endpoint must reject it as already taken.
+ """
+ client, headers = bootstrap_client
+
+ response = client.post(
+ "/api/v1/auth/users",
+ json={"username": env_admin, "password": "attacker-pass-1234"},
+ headers=headers,
+ )
+
+ assert response.status_code == 409