Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(admin): stop silent superuser creation on auth probe and harden bootstrap (#18702)

陈志谦706e87af9f47
diff --git a/admin/server/auth.py b/admin/server/auth.py
index 8d864c15b4..cba5d1f9cb 100644
--- a/admin/server/auth.py
+++ b/admin/server/auth.py
@@ -17,11 +17,11 @@
import logging
import os
+import secrets
import uuid
from functools import wraps
from datetime import datetime
-from flask import jsonify, request
from flask_login import current_user, login_user
from api.common.exceptions import AdminException, UserNotFoundError
@@ -30,13 +30,26 @@ from api.db.services import UserService
from api.db import UserTenantRole
from api.db.services.user_service import TenantService, UserTenantService
from common.constants import ActiveEnum, StatusEnum
-from api.utils.crypt import decrypt
+from common.file_utils import get_project_base_directory
+from api.utils.crypt import CryptPayloadError, decrypt
from common.misc_utils import get_uuid
from common.time_utils import current_timestamp, datetime_format, get_format_time
from common.connection_utils import sync_construct_response
from common import settings
+# Bootstrap password for the default superuser created by init_default_admin().
+# ADMIN_DEFAULT_PASSWORD is admin-server specific; DEFAULT_SUPERUSER_PASSWORD is
+# shared with api/db/init_data.py so a deployment can keep one bootstrap
+# password for both sides. Unlike api/db/init_data.py (which still falls back
+# to the literal "admin"), the admin server falls back to a random password
+# delivered through a 0600 bootstrap file: the admin panel manages sandbox providers
+# (including the "local" provider, i.e. host-level execution), so a guessable
+# default here would effectively be host RCE.
+ADMIN_DEFAULT_PASSWORD_ENV = "ADMIN_DEFAULT_PASSWORD"
+DEFAULT_SUPERUSER_PASSWORD_ENV = "DEFAULT_SUPERUSER_PASSWORD"
+
+
# The admin server reports DEFAULT_SUPERUSER_EMAIL via
# `services.EnvironmentsMgr.get_all()` and the admin CLI's "list envs"
# output, so operators reasonably expect the env value to drive the
@@ -49,13 +62,12 @@ from common import settings
#
# Reject empty env values explicitly: ``os.getenv(name, fallback)``
# only uses the fallback when the variable is *unset*, so a misconfigured
-# operator setting ``DEFAULT_SUPERUSER_PASSWORD=`` would otherwise
-# persist an empty password — every first login would silently fail with
-# "credentials don't match" instead of a clear startup error. We
-# deliberately preserve the raw value (no whitespace stripping) so a
-# password like ``" s3cret "`` keeps its leading/trailing whitespace
-# and isn't silently mutated before being hashed/stored. Email/nickname
-# callers strip separately because whitespace there would be invalid.
+# operator setting ``DEFAULT_SUPERUSER_EMAIL=`` would otherwise
+# propagate an empty email into the bootstrap flow. We deliberately
+# preserve raw password values (no whitespace stripping) so a password
+# like ``" s3cret "`` keeps its leading/trailing whitespace and isn't
+# silently mutated before being hashed/stored. Email/nickname strip
+# separately because whitespace there would be invalid.
def _required_env(name, default):
value = os.getenv(name, default)
if not value:
@@ -91,7 +103,12 @@ def _required_env_stripped(name, default):
DEFAULT_SUPERUSER_NICKNAME = _required_env_stripped("DEFAULT_SUPERUSER_NICKNAME", "admin")
DEFAULT_SUPERUSER_EMAIL = _required_env_stripped("DEFAULT_SUPERUSER_EMAIL", "[email protected]")
-DEFAULT_SUPERUSER_PASSWORD = _required_env("DEFAULT_SUPERUSER_PASSWORD", "admin")
+# NOTE: there is deliberately no DEFAULT_SUPERUSER_PASSWORD module constant
+# here. The bootstrap password resolves at startup via
+# _resolve_bootstrap_admin_password() — ADMIN_DEFAULT_PASSWORD, then
+# DEFAULT_SUPERUSER_PASSWORD, then a random password delivered through a
+# 0600 file — instead of falling back to the literal "admin" that
+# api/db/init_data.py still uses.
def setup_auth(login_manager):
@@ -143,13 +160,54 @@ def setup_auth(login_manager):
return None
+def _resolve_bootstrap_admin_password() -> tuple[str, str | None]:
+ """Return ``(plain_password, env_var_name)`` for the bootstrap superuser.
+
+ Precedence: ADMIN_DEFAULT_PASSWORD, then DEFAULT_SUPERUSER_PASSWORD (the
+ variable honoured by api/db/init_data.py on the web side), then a random
+ password that is delivered through a 0600 bootstrap file, never the log.
+ """
+ for env_name in (ADMIN_DEFAULT_PASSWORD_ENV, DEFAULT_SUPERUSER_PASSWORD_ENV):
+ value = os.getenv(env_name)
+ if value:
+ return value, env_name
+ return secrets.token_urlsafe(18), None
+
+
+def _write_bootstrap_password_file(password: str) -> str | None:
+ """Write the generated bootstrap password to a 0600 file beside the logs.
+
+ Returns the file path, or None when the file could not be written (the
+ password is then unrecoverable and the operator must set
+ ADMIN_DEFAULT_PASSWORD and recreate the account — failing closed beats
+ leaking the credential into a log stream).
+ """
+ target_dir = os.path.join(get_project_base_directory(), "logs")
+ path = os.path.join(target_dir, "admin_bootstrap_password.txt")
+ try:
+ os.makedirs(target_dir, exist_ok=True)
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(fd, "w") as fh:
+ fh.write(password + "\n")
+ return path
+ except OSError as e:
+ logging.error(f"Failed to write the admin bootstrap password file {path}: {e}")
+ return None
+
+
def init_default_admin():
# Verify that at least one active admin user exists. If not, create a default one.
+ # This runs only from the explicit startup path in admin_server.py; the
+ # authentication handlers below must never create accounts.
users = UserService.query(is_superuser=True)
if not users:
+ password, env_name = _resolve_bootstrap_admin_password()
default_admin = {
"id": uuid.uuid1().hex,
- "password": encode_to_base64(DEFAULT_SUPERUSER_PASSWORD),
+ # UserService.save() hashes this value and both login paths compare
+ # against base64(<plain password>) - same convention as
+ # api/db/init_data.py.
+ "password": encode_to_base64(password),
"nickname": DEFAULT_SUPERUSER_NICKNAME,
"is_superuser": True,
"email": DEFAULT_SUPERUSER_EMAIL,
@@ -159,6 +217,21 @@ def init_default_admin():
if not UserService.save(**default_admin):
raise AdminException("Can't init admin.", 500)
add_tenant_for_admin(default_admin, UserTenantRole.OWNER)
+ if env_name:
+ logging.info(f"Created default superuser {DEFAULT_SUPERUSER_EMAIL} with the password from {env_name}. Change it after the first login.")
+ else:
+ password_file = _write_bootstrap_password_file(password)
+ if password_file:
+ logging.warning(
+ f"No superuser found and neither {ADMIN_DEFAULT_PASSWORD_ENV} nor {DEFAULT_SUPERUSER_PASSWORD_ENV} is set. "
+ f"Created default superuser {DEFAULT_SUPERUSER_EMAIL}; its randomly generated password was written once to {password_file} (mode 0600). Read it there and change it immediately after the first login."
+ )
+ else:
+ logging.error(
+ f"No superuser found and neither {ADMIN_DEFAULT_PASSWORD_ENV} nor {DEFAULT_SUPERUSER_PASSWORD_ENV} is set, "
+ f"and the bootstrap password file could not be written. The randomly generated password for {DEFAULT_SUPERUSER_EMAIL} is NOT recoverable: "
+ f"delete the account and re-run with {ADMIN_DEFAULT_PASSWORD_ENV} set."
+ )
elif not any([u.is_active == ActiveEnum.ACTIVE.value for u in users]):
raise AdminException("No active admin. Please update 'is_active' in db manually.", 500)
else:
@@ -252,7 +325,15 @@ def login_admin(email: str, password: str):
users = UserService.query(email=email)
if not users:
raise UserNotFoundError(email)
- decrypted = decrypt(password)
+ try:
+ decrypted = decrypt(password)
+ except CryptPayloadError:
+ # A payload the client could not encode correctly is the client's
+ # failure, not a server fault: answer with the same generic mismatch
+ # as any other credential rejection. Server-side faults
+ # (missing/invalid private key) propagate to the caller instead.
+ logging.info("Admin login with undecryptable password payload.")
+ raise AdminException("Email and password do not match!")
user = UserService.query_user(email, decrypted)
if not user:
raise AdminException("Email and password do not match!")
@@ -270,53 +351,3 @@ def login_admin(email: str, password: str):
user.save()
msg = "Welcome back!"
return sync_construct_response(data=resp, auth=user.get_id(), message=msg)
-
-
-def check_admin(username: str, password: str):
- users = UserService.query(email=username)
- if not users:
- logging.info(f"Username: {username} is not registered!")
- # On first login with an unrecognised username, fall back to the
- # env-configured default admin bootstrap so an operator who set
- # ``[email protected]`` gets an admin at
- # ``[email protected]`` — matching what ``services.EnvironmentsMgr.get_all``
- # advertises and what the API-side ``init_superuser`` already
- # does. See infiniflow/ragflow#16876.
- user_info = {
- "id": uuid.uuid1().hex,
- "password": encode_to_base64(DEFAULT_SUPERUSER_PASSWORD),
- "nickname": DEFAULT_SUPERUSER_NICKNAME,
- "is_superuser": True,
- "email": DEFAULT_SUPERUSER_EMAIL,
- "creator": "system",
- "status": "1",
- }
- if not UserService.save(**user_info):
- raise AdminException("Can't init admin.", 500)
-
- user = UserService.query_user(username, password)
- if user:
- return True
- else:
- return False
-
-
-def login_verify(f):
- @wraps(f)
- def decorated(*args, **kwargs):
- auth = request.authorization
- if not auth or "username" not in auth.parameters or "password" not in auth.parameters:
- return jsonify({"code": 401, "message": "Authentication required", "data": None}), 200
-
- username = auth.parameters["username"]
- password = auth.parameters["password"]
- try:
- if not check_admin(username, password):
- return jsonify({"code": 500, "message": "Access denied", "data": None}), 200
- except Exception:
- logging.exception("An error occurred during admin login verification.")
- return jsonify({"code": 500, "message": "An internal server error occurred."}), 200
-
- return f(*args, **kwargs)
-
- return decorated
diff --git a/admin/server/routes.py b/admin/server/routes.py
index e56f86f684..859471fa01 100644
--- a/admin/server/routes.py
+++ b/admin/server/routes.py
@@ -23,7 +23,7 @@ from datetime import datetime
from flask import Blueprint, Response, request
from flask_login import current_user, login_required, logout_user
-from auth import login_verify, login_admin, check_admin_auth
+from auth import login_admin, check_admin_auth
from responses import success_response, error_response
from services import UserMgr, ServiceMgr, UserServiceMgr, SettingsMgr, ConfigMgr, EnvironmentsMgr, SandboxMgr
from roles import RoleMgr
@@ -64,15 +64,6 @@ def logout():
return error_response(str(e), 500)
-@admin_bp.route("/auth", methods=["GET"])
-@login_verify
-def auth_admin():
- try:
- return success_response(None, "Admin is authorized", 0)
- except Exception as e:
- return error_response(str(e), 500)
-
-
@admin_bp.route("/users", methods=["GET"])
@login_required
@check_admin_auth
diff --git a/api/utils/crypt.py b/api/utils/crypt.py
index 53afcbec0d..e4961aed15 100644
--- a/api/utils/crypt.py
+++ b/api/utils/crypt.py
@@ -16,13 +16,21 @@
import base64
import os
-import sys
from pathlib import Path
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from common.file_utils import get_project_base_directory
+class CryptPayloadError(ValueError):
+ """Raised when a client-supplied ciphertext payload is malformed.
+
+ Distinguished from server-side faults (missing or invalid private-key
+ file, key import failures), which propagate unchanged so callers can
+ treat them as server errors rather than bad credentials.
+ """
+
+
def crypt(line):
"""
decrypt(crypt(input_string)) == base64(input_string), which frontend and ragflow_cli use.
@@ -37,30 +45,27 @@ def crypt(line):
def decrypt(line):
file_path = os.path.join(get_project_base_directory(), "conf", "private.pem")
+ # Key-file read/import failures are server faults and propagate as-is.
rsa_key = RSA.importKey(Path(file_path).read_text(), "Welcome")
cipher = Cipher_pkcs1_v1_5.new(rsa_key)
- return cipher.decrypt(base64.b64decode(line), "Fail to decrypt password!").decode("utf-8")
-
-
-def decrypt2(crypt_text):
- from base64 import b64decode, b16decode
- from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
- from Crypto.PublicKey import RSA
-
- decode_data = b64decode(crypt_text)
- if len(decode_data) == 127:
- hex_fixed = "00" + decode_data.hex()
- decode_data = b16decode(hex_fixed.upper())
-
- file_path = os.path.join(get_project_base_directory(), "conf", "private.pem")
- pem = Path(file_path).read_text()
- rsa_key = RSA.importKey(pem, "Welcome")
- cipher = Cipher_PKCS1_v1_5.new(rsa_key)
- decrypt_text = cipher.decrypt(decode_data, None)
- return (b64decode(decrypt_text)).decode()
-
-
-if __name__ == "__main__":
- passwd = crypt(sys.argv[1])
- print(passwd)
- print(decrypt(passwd))
+ # Everything below concerns the client-supplied payload. Strip internal
+ # whitespace first: line-wrapped base64 (as test fixtures and PEM-style
+ # senders produce) is legal base64, but b64decode(validate=True) would
+ # reject the embedded newlines. After the strip, validate=True still
+ # catches genuinely malformed payloads (non-alphabet characters).
+ try:
+ ciphertext = base64.b64decode("".join(line.split()), validate=True)
+ except ValueError as e:
+ raise CryptPayloadError("password payload is not valid base64") from e
+ try:
+ plaintext = cipher.decrypt(ciphertext, None)
+ except ValueError as e:
+ # e.g. pycryptodome's "Ciphertext with incorrect length" for
+ # well-formed base64 that is not a valid ciphertext block.
+ raise CryptPayloadError("password payload failed RSA decryption") from e
+ if plaintext is None:
+ raise CryptPayloadError("password payload failed RSA decryption")
+ try:
+ return plaintext.decode("utf-8")
+ except UnicodeDecodeError as e:
+ raise CryptPayloadError("decrypted password payload is not valid UTF-8") from e
diff --git a/docker/.env b/docker/.env
index 034f050159..6fa933db82 100644
--- a/docker/.env
+++ b/docker/.env
@@ -231,11 +231,21 @@ JAEGER_UI_PORT=16686
SVR_WEB_HTTP_PORT=80
SVR_WEB_HTTPS_PORT=443
SVR_HTTP_PORT=9380
+# Admin server REST API port, published externally by design (direct API
+# access is supported).
ADMIN_SVR_HTTP_PORT=9381
SVR_MCP_PORT=9382
GO_HTTP_PORT=9384
GO_ADMIN_PORT=9383
+# Password for the default superuser ([email protected]) that the admin server
+# creates on first start when no superuser exists. When unset (and
+# DEFAULT_SUPERUSER_PASSWORD is also unset), a random password is generated and
+# written once to logs/admin_bootstrap_password.txt (mode 0600, the container's
+# /ragflow/logs volume) - read it there and change it immediately after the
+# first login.
+ADMIN_DEFAULT_PASSWORD=admin
+
# API_PROXY_SCHEME=hybrid # go and python hybrid deploy mode
# API_PROXY_SCHEME=go # use go server deployment
API_PROXY_SCHEME=python # use pure python server deployment
diff --git a/docs/administrator/admin/admin_ui/before_you_begin.md b/docs/administrator/admin/admin_ui/before_you_begin.md
index b22ce5cacc..31eae39255 100644
--- a/docs/administrator/admin/admin_ui/before_you_begin.md
+++ b/docs/administrator/admin/admin_ui/before_you_begin.md
@@ -18,12 +18,10 @@ Regular users do not need to enter the Admin UI when they use business features
## Initial Administrator Account
-After the first deployment, you can log in with the default administrator account:
+After the first deployment, you can log in with the default administrator account `[email protected]`. Its password is chosen when the admin server starts and no superuser exists yet:
-| Field | Value |
-| --- | --- |
-| Username | `[email protected]` |
-| Default password | `admin` |
+- If the `ADMIN_DEFAULT_PASSWORD` environment variable is set (or `DEFAULT_SUPERUSER_PASSWORD`, which is shared with the web service bootstrap), that value is used.
+- Otherwise a random password is generated and written **once** to `logs/admin_bootstrap_password.txt` (mode 0600; in a docker deployment check the `docker/ragflow-logs` volume) — retrieve it from that file, log in, and change it immediately.
This account is used to initialize the system and create subsequent administrator accounts. It is not recommended as a long-term shared daily operations account.
diff --git a/docs/administrator/admin/ragflow_cli.md b/docs/administrator/admin/ragflow_cli.md
index e5f7771d7f..ac81561a72 100644
--- a/docs/administrator/admin/ragflow_cli.md
+++ b/docs/administrator/admin/ragflow_cli.md
@@ -29,7 +29,7 @@ The RAGFlow CLI is a command-line-based system administration tool that offers a
```
You will be prompted to enter the superuser's password to log in.
- The default password is admin.
+ See [Default Administrative Account](#default-administrative-account) for how the initial password is chosen.
**Parameters:**
@@ -40,7 +40,7 @@ The RAGFlow CLI is a command-line-based system administration tool that offers a
## Default Administrative Account
- Username: [email protected]
-- Password: admin
+- Password: the value of the `ADMIN_DEFAULT_PASSWORD` (or `DEFAULT_SUPERUSER_PASSWORD`) environment variable; if neither is set when the admin server first starts, a random password is generated and written once to `logs/admin_bootstrap_password.txt` (mode 0600). Change it after the first login.
## Supported Commands
diff --git a/test/unit_test/admin/test_auth_hardening.py b/test/unit_test/admin/test_auth_hardening.py
new file mode 100644
index 0000000000..32b0493f47
--- /dev/null
+++ b/test/unit_test/admin/test_auth_hardening.py
@@ -0,0 +1,224 @@
+#
+# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""
+Unit tests for the admin auth bootstrap hardening in ``admin/server/auth.py``.
+
+Covers the security fixes for the "anonymous probe resurrects the superuser"
+chain:
+
+1. The Basic-Auth probe endpoint (GET /api/v1/admin/auth, ``login_verify`` /
+ ``check_admin``) — the historic silent-superuser-creation path — is dead
+ code (the admin UI uses the JSON login, ragflow-cli uses POST
+ /admin/login) and has been removed outright instead of hardened.
+2. ``init_default_admin`` must not hardcode ``admin``: the bootstrap password
+ comes from ``ADMIN_DEFAULT_PASSWORD`` (or ``DEFAULT_SUPERUSER_PASSWORD``,
+ shared with ``api/db/init_data.py``) or is randomly generated and written
+ once to a 0600 bootstrap file, never the log.
+3. Decrypt failures are classified: client payload faults answer with the
+ generic credential mismatch, while server-side key faults propagate
+ instead of masquerading as wrong-password verdicts.
+
+The per-address login throttle that earlier revisions carried was removed
+on review: its counters were process-local, so under a multi-worker
+deployment the limit would silently multiply and the control would become
+an unreliable mix of false protection and unpredictable 429s for real
+users. The admin server deliberately avoids shared-state dependencies
+(filesystem sessions, no Redis), so the honest options were a shared-store
+implementation or no throttle; rag/utils/redis_conn.py already ships an
+atomic token-bucket Lua script if a Redis-backed version is ever wanted.
+"""
+
+import base64
+import logging
+from unittest import mock
+
+# The admin conftest (test/unit_test/admin/conftest.py) already prepends
+# admin/server to sys.path. The full dependency graph must be importable;
+# an import failure fails test setup rather than silently stubbing the
+# modules under test.
+import auth
+import pytest
+
+assert auth.__file__.endswith("admin/server/auth.py"), f"unexpected auth module resolved: {auth.__file__}"
+
+
+def _no_bootstrap_password_env(monkeypatch):
+ monkeypatch.delenv("ADMIN_DEFAULT_PASSWORD", raising=False)
+ monkeypatch.delenv("DEFAULT_SUPERUSER_PASSWORD", raising=False)
+
+
+class TestInitDefaultAdminPassword:
+ def test_random_password_when_env_unset_is_not_logged(self, tmp_path, caplog):
+ with (
+ caplog.at_level(logging.WARNING),
+ mock.patch.object(auth, "get_project_base_directory", return_value=str(tmp_path)),
+ mock.patch.object(auth, "UserService") as user_service,
+ mock.patch.object(auth, "add_tenant_for_admin") as add_tenant,
+ ):
+ user_service.query.return_value = []
+ user_service.save.return_value = object()
+
+ auth.init_default_admin()
+
+ user_service.save.assert_called_once()
+ saved = user_service.save.call_args.kwargs
+ assert saved["email"] == "[email protected]"
+ assert saved["is_superuser"] is True
+ # Stored value is base64(<plain password>) and must not be the old default.
+ stored_password = base64.b64decode(saved["password"]).decode("utf-8")
+ assert stored_password != "admin"
+ assert len(stored_password) >= 18
+ # The random password goes to the 0600 bootstrap file and never the log.
+ assert stored_password not in caplog.text
+ assert "admin_bootstrap_password.txt" in caplog.text
+ assert "0600" in caplog.text
+ add_tenant.assert_called_once()
+
+ def test_random_password_written_to_0600_file_matching_the_saved_hash(self, tmp_path, caplog):
+ with (
+ caplog.at_level(logging.WARNING),
+ mock.patch.object(auth, "get_project_base_directory", return_value=str(tmp_path)),
+ mock.patch.object(auth, "UserService") as user_service,
+ mock.patch.object(auth, "add_tenant_for_admin"),
+ ):
+ user_service.query.return_value = []
+ user_service.save.return_value = object()
+
+ auth.init_default_admin()
+
+ saved = user_service.save.call_args.kwargs
+ stored_password = base64.b64decode(saved["password"]).decode("utf-8")
+
+ password_file = tmp_path / "logs" / "admin_bootstrap_password.txt"
+ assert password_file.exists()
+ assert password_file.read_text(encoding="utf-8").strip() == stored_password
+ assert (password_file.stat().st_mode & 0o777) == 0o600
+ # The log announces the file, not the credential itself.
+ assert stored_password not in caplog.text
+ assert str(password_file) in caplog.text
+
+ def test_unwritable_bootstrap_dir_fails_closed_without_leaking(self, tmp_path, caplog):
+ locked_dir = tmp_path / "logs"
+ locked_dir.mkdir()
+ locked_dir.chmod(0o500) # read+execute, no write
+ try:
+ with (
+ caplog.at_level(logging.ERROR),
+ mock.patch.object(auth, "get_project_base_directory", return_value=str(tmp_path)),
+ mock.patch.object(auth, "UserService") as user_service,
+ mock.patch.object(auth, "add_tenant_for_admin"),
+ ):
+ user_service.query.return_value = []
+ user_service.save.return_value = object()
+
+ auth.init_default_admin()
+
+ saved = user_service.save.call_args.kwargs
+ stored_password = base64.b64decode(saved["password"]).decode("utf-8")
+ # Fail closed: no file, and the password never reaches the log.
+ assert not (locked_dir / "admin_bootstrap_password.txt").exists()
+ assert stored_password not in caplog.text
+ assert "NOT recoverable" in caplog.text
+ finally:
+ locked_dir.chmod(0o700)
+
+ def test_random_passwords_differ_between_bootstraps(self):
+ first, first_env = auth._resolve_bootstrap_admin_password()
+ second, second_env = auth._resolve_bootstrap_admin_password()
+ assert first_env is None and second_env is None
+ assert first != second
+
+ def test_admin_default_password_env_wins_and_is_not_logged(self, monkeypatch, caplog):
+ monkeypatch.setenv("ADMIN_DEFAULT_PASSWORD", "s3cr3t-bootstrap")
+ with caplog.at_level(logging.INFO), mock.patch.object(auth, "UserService") as user_service, mock.patch.object(auth, "add_tenant_for_admin"):
+ user_service.query.return_value = []
+ user_service.save.return_value = object()
+
+ auth.init_default_admin()
+
+ saved = user_service.save.call_args.kwargs
+ assert base64.b64decode(saved["password"]).decode("utf-8") == "s3cr3t-bootstrap"
+ assert "s3cr3t-bootstrap" not in caplog.text
+
+ def test_falls_back_to_default_superuser_password_env(self, monkeypatch):
+ monkeypatch.setenv("DEFAULT_SUPERUSER_PASSWORD", "web-side-bootstrap")
+ with mock.patch.object(auth, "UserService") as user_service, mock.patch.object(auth, "add_tenant_for_admin"):
+ user_service.query.return_value = []
+ user_service.save.return_value = object()
+
+ auth.init_default_admin()
+
+ saved = user_service.save.call_args.kwargs
+ assert base64.b64decode(saved["password"]).decode("utf-8") == "web-side-bootstrap"
+
+ def test_existing_superuser_skips_creation(self):
+ existing = mock.MagicMock(is_active="1", email="[email protected]", id="x" * 32)
+ existing.to_dict.return_value = {"id": "x" * 32, "email": "[email protected]", "nickname": "admin"}
+ with mock.patch.object(auth, "UserService") as user_service, mock.patch.object(auth, "TenantService") as tenant_service:
+ user_service.query.return_value = [existing]
+ tenant_service.get_by_id.return_value = (True, mock.MagicMock())
+
+ auth.init_default_admin()
+
+ user_service.save.assert_not_called()
+
+
+class TestDecryptFailureClassification:
+ def test_client_payload_fault_is_a_generic_credential_mismatch(self):
+ from api.utils.crypt import CryptPayloadError
+
+ registered = mock.MagicMock()
+ with (
+ mock.patch.object(auth, "UserService") as user_service,
+ mock.patch.object(auth, "decrypt", side_effect=CryptPayloadError("bad payload")),
+ ):
+ user_service.query.return_value = [registered]
+
+ with pytest.raises(auth.AdminException, match="do not match"):
+ auth.login_admin("[email protected]", "not-valid-base64")
+
+ # A payload the client could not encode correctly must not surface
+ # as a server error (which would hint at key-management problems).
+ user_service.query_user.assert_not_called()
+
+ def test_server_side_decrypt_fault_propagates(self):
+ registered = mock.MagicMock()
+ with (
+ mock.patch.object(auth, "UserService") as user_service,
+ mock.patch.object(auth, "decrypt", side_effect=RuntimeError("private key file missing")),
+ ):
+ user_service.query.return_value = [registered]
+
+ # Key-management faults are server errors, not credential
+ # verdicts: they propagate instead of answering "wrong password".
+ with pytest.raises(RuntimeError, match="private key file missing"):
+ auth.login_admin("[email protected]", "anything")
+
+
+class TestDecryptAcceptsLineWrappedBase64:
+ def test_round_trip_with_embedded_newlines(self):
+ """b64decode(validate=True) rejects embedded newlines; decrypt must
+ strip internal whitespace first or line-wrapped base64 payloads
+ (test fixtures, PEM-style senders) are treated as bad credentials."""
+ import base64 as b64
+
+ from api.utils.crypt import crypt, decrypt
+
+ blob = crypt("123")
+ wrapped = "\n".join(blob[i : i + 16] for i in range(0, len(blob), 16))
+
+ assert decrypt(wrapped) == b64.b64encode(b"123").decode()
+ assert decrypt(blob) == b64.b64encode(b"123").decode()