Skip to content

fix(admin): honor DEFAULT_SUPERUSER_EMAIL/PASSWORD env vars in bootstrap - #17674

Merged
JinHai-CN merged 7 commits into
infiniflow:mainfrom
Taranum01:fix/17063-superuser-env-v2
Aug 25, 2026
Merged

JinHai-CN merged 7 commits into
infiniflow:mainfrom
Taranum01:fix/17063-superuser-env-v2

Conversation

@Taranum01

Copy link
Copy Markdown
Contributor

Supersedes #17063 (closed as superseded due to unrebasable test-fixture drift).

Summary

The admin server's bootstrap (init_default_admin) and first-login fallback (check_admin) hardcoded [email protected] / admin / admin. The admin CLI's "list envs" output and the EnvironmentsMgr API both advertise DEFAULT_SUPERUSER_EMAIL/PASSWORD/NICKNAME as configurable, but the bootstrap ignored them — operators setting custom env values saw the docs claim support while the code still created the default admin. This matches what api/db/init_data.py:init_superuser already does on the API side.

Fix

Three module-level constants read from env at import time (with the existing defaults), used in both init_default_admin and the first-login check_admin fallback. The existing-superuser row lookup in init_default_admin now keys off the configured email so a custom DEFAULT_SUPERUSER_EMAIL steers the tenant-backfill branch correctly.

Scope

Core change only — the previous PR's test scaffolding (reload_admin_auth fixture with sys.modules stubbing) conflicts with the evolved test/unit_test/admin/conftest.py on current main and was excluded from this fresh port. Tests can be re-added on the new fixture shape in a follow-up if needed.

Refs #16876

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d9069afc-5ddc-4150-afca-20fd6ac78e66

📥 Commits

Reviewing files that changed from the base of the PR and between fdaeb7c and 5cb1706.

📒 Files selected for processing (1)
  • admin/server/auth.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • admin/server/auth.py

📝 Walkthrough

Walkthrough

The authentication module adds validated environment-backed defaults for the bootstrap administrator. Creation flows use these values. Tenant backfill matches the configured email and raises an error when no matching active superuser exists.

Changes

Bootstrap administrator configuration

Layer / File(s) Summary
Define administrator defaults
admin/server/auth.py
The module reads environment settings and defines fallback values for the bootstrap administrator nickname, email, and password. Empty values raise RuntimeError.
Apply administrator defaults
admin/server/auth.py
init_default_admin and check_admin use the configured values. Tenant backfill matches the configured email and raises AdminException when no matching active superuser exists.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: ⚪ Minimal · up to 5cb17

The bootstrap now honors configured default-superuser environment variables instead of always using hardcoded credentials. No actionable merge-blocking risk remains after normal checks and review.

Poem

A rabbit checks each setting bright,
Rejects blank values out of sight.
The admin hops with names aligned,
Tenant records match the configured kind.
Bootstrap carrots grow just right.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description check ✅ Passed The description includes the required Summary section and clearly explains the problem, fix, scope, and background.
Title check ✅ Passed The title clearly identifies the fix that makes bootstrap honor the DEFAULT_SUPERUSER_EMAIL and DEFAULT_SUPERUSER_PASSWORD environment variables.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (2)
admin/server/auth.py (2)

199-210: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log successful first-login bootstrap.

The changed path logs only that the username was not found. Add a success log after UserService.save completes. Do not log DEFAULT_SUPERUSER_PASSWORD.

As per coding guidelines, **/*.py: Add logging for new flows.

Proposed log
         if not UserService.save(**user_info):
             raise AdminException("Can't init admin.", 500)
+        logging.info("Default administrator created during first-login fallback")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@admin/server/auth.py` around lines 199 - 210, The first-login bootstrap flow
needs a success log after UserService.save completes. Add a concise log
identifying the successful admin bootstrap without including
DEFAULT_SUPERUSER_PASSWORD, and keep the existing username-not-found logging
unchanged.

Source: Coding guidelines


106-109: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Add focused tests for the bootstrap configuration contract.

Set environment variables before importing admin/server/auth.py. Cover unset values, custom values, blank-value rejection, tenant backfill, and first-login fallback. These paths currently have no focused test in the supplied cohort.

As per coding guidelines, **/*: Preserve still-valid behavior with focused tests.

Also applies to: 119-122, 199-210

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@admin/server/auth.py` around lines 106 - 109, Add focused tests for the
bootstrap configuration contract in admin/server/auth.py, setting environment
variables before importing the module so import-time defaults are exercised.
Cover unset values, custom values, rejection of blank values, tenant backfill,
and first-login fallback, including the configuration symbols and paths around
DEFAULT_SUPERUSER_PASSWORD, DEFAULT_SUPERUSER_EMAIL, and the related lines noted
in the diff. Preserve existing valid behavior while asserting each expected
resolved value.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@admin/server/auth.py`:
- Around line 39-45: Update the module-load comment in the admin server
bootstrap section to state only that services.EnvironmentsMgr.get_all() and the
admin CLI expose DEFAULT_SUPERUSER_EMAIL, while DEFAULT_SUPERUSER_PASSWORD is
not environment-listed. Remove the claim that both values are reported, without
changing password exposure behavior or the bootstrap functions.
- Around line 39-49: Validate DEFAULT_SUPERUSER_NICKNAME,
DEFAULT_SUPERUSER_EMAIL, and DEFAULT_SUPERUSER_PASSWORD after reading their
environment values and reject unset-equivalent blank or whitespace-only inputs
before defining the module-level constants. Preserve the existing defaults for
unset variables, and ensure bootstrap functions use only validated non-blank
values.
- Around line 199-210: Update check_admin() so the DEFAULT_SUPERUSER_EMAIL
fallback user is created only when username matches DEFAULT_SUPERUSER_EMAIL;
otherwise preserve the existing-user authentication path without creating a
separate fallback account. Ensure fallback creation and UserService.query_user
authentication always target the same identity.
- Around line 119-122: Update init_default_admin() to handle the case where no
active user matches DEFAULT_SUPERUSER_EMAIL: create the configured administrator
when existing active superusers are only mismatches, or explicitly fail with a
clear migration-guidance message. Preserve the existing tenant-backfill behavior
for a matching configured admin and ensure normal startup does not silently skip
initialization when --init-superuser is not provided.

---

Nitpick comments:
In `@admin/server/auth.py`:
- Around line 199-210: The first-login bootstrap flow needs a success log after
UserService.save completes. Add a concise log identifying the successful admin
bootstrap without including DEFAULT_SUPERUSER_PASSWORD, and keep the existing
username-not-found logging unchanged.
- Around line 106-109: Add focused tests for the bootstrap configuration
contract in admin/server/auth.py, setting environment variables before importing
the module so import-time defaults are exercised. Cover unset values, custom
values, rejection of blank values, tenant backfill, and first-login fallback,
including the configuration symbols and paths around DEFAULT_SUPERUSER_PASSWORD,
DEFAULT_SUPERUSER_EMAIL, and the related lines noted in the diff. Preserve
existing valid behavior while asserting each expected resolved value.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1dd1f0f1-6cfb-4efc-be88-c4500d44471e

📥 Commits

Reviewing files that changed from the base of the PR and between 776b937 and 975e734.

📒 Files selected for processing (1)
  • admin/server/auth.py

Comment thread admin/server/auth.py Resolved
Comment thread admin/server/auth.py Resolved
Comment thread admin/server/auth.py Resolved
Comment thread admin/server/auth.py
Comment on lines +199 to +210
# 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("admin"),
"nickname": "admin",
"password": encode_to_base64(DEFAULT_SUPERUSER_PASSWORD),
"nickname": DEFAULT_SUPERUSER_NICKNAME,
"is_superuser": True,
"email": "[email protected]",
"email": DEFAULT_SUPERUSER_EMAIL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 8 '\bcheck_admin\s*\(' --glob '*.py'

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Tracked admin/server/auth.py:\n'
git ls-files | grep -E '(^|/)admin/server/auth\.py$' || true

printf '\nRelevant snippets:\n'
if [ -f admin/server/auth.py ]; then
  wc -l admin/server/auth.py
  sed -n '160,245p' admin/server/auth.py | cat -n -v
fi

printf '\nSearch for auth flow symbols:\n'
rg -n 'DEFAULT_SUPERUSER|check_admin|query_user|query_superuser|create_user|encode_to_base64' --glob '*.py' admin server . || true

Repository: infiniflow/ragflow

Length of output: 22456


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'admin/server/auth.py surrounding code:\n'
sed -n '90,128p' admin/server/auth.py | cat -n -v
sed -n '189,238p' admin/server/auth.py | cat -n -v

printf '\nadmin/server/services.py UserMgr methods:\n'
sed -n '50,280p' admin/server/services.py | cat -n -v

printf '\nUserService.query_user implementation:\n'
cat -n api/db/services/user_service.py | sed -n '70,105p'

printf '\nBehavioral probe: simulate login_verify inputs without executing repository code:\n'
python3 - <<'PY'
for username in ["[email protected]", "[email protected]", "different"]:
    users = [] if username != "[email protected]" else [{"email":"[email protected]", "is_superuser":True, "password":"admin"}]
    default_email = "[email protected]"
    if not users:
        users.append({"email": default_email, "is_superuser":True, "password":"admin"})
    checked = any({"email":default_email, "password":"admin"}.get(k) == users[0].get(k) for k in ["email","password"])
    print({"input_username": username, "created_user_email": users[-1]["email"], "authenticated_username": username, "username_equals_creating_email": username == default_email, "check_admin_returns": checked})
PY

Repository: infiniflow/ragflow

Length of output: 17672


Keep fallback creation and authentication on the same identity.

When username differs from DEFAULT_SUPERUSER_EMAIL, check_admin() creates a superuser for the configured email, then authenticates UserService.query_user(username, password). For a first login with another username that already exists, the created fallback admin account is left unauthenticated. Only create the fallback when username == DEFAULT_SUPERUSER_EMAIL.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@admin/server/auth.py` around lines 199 - 210, Update check_admin() so the
DEFAULT_SUPERUSER_EMAIL fallback user is created only when username matches
DEFAULT_SUPERUSER_EMAIL; otherwise preserve the existing-user authentication
path without creating a separate fallback account. Ensure fallback creation and
UserService.query_user authentication always target the same identity.

Taranum01 pushed a commit to Taranum01/ragflow that referenced this pull request Jul 31, 2026
Three follow-ups from the review on infiniflow#17674:

1. **Comment correctness** (`services.EnvironmentsMgr.get_all` returns
   only `DEFAULT_SUPERUSER_EMAIL`, not the password — the previous
   comment implied both were listed, which would mislead an operator
   reading the env-listing output and expect the password to appear
   there too).

2. **Reject blank/whitespace env values** via a `_required_env` helper
   before defining the three module-level constants. Without this,
   `DEFAULT_SUPERUSER_PASSWORD=` would silently persist an empty
   password (os.getenv uses fallback only when *unset*, not when
   empty), making every first login fail with the misleading
   'credentials do not match' error rather than a startup-time
   configuration error.

3. **Admin email mismatch in `init_default_admin`** — when active
   superusers exist but none match `DEFAULT_SUPERUSER_EMAIL`, raise
   an explicit `AdminException` with migration guidance (run the
   API-side `--init-superuser` to align) instead of silently skipping
   the tenant backfill. The previous behaviour diverged the
   bootstrap credential from the env value without telling anyone.

Item 4 (check_admin auth-bypass) does not apply to this PR — the
function referenced in the review was in the closed predecessor
infiniflow#17063, which was superseded by this PR that only touches
`init_default_admin`.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@admin/server/auth.py`:
- Around line 54-62: Update _required_env to log the setting name, without its
value, before raising for missing or whitespace-only configuration. Also add
logging in the migration mismatch failure flow around the referenced lines,
recording only the mismatch state and excluding the password and full
environment values; preserve the existing exceptions and avoid logging secrets.
- Around line 54-67: Update _required_env and the DEFAULT_SUPERUSER_*
initialization so DEFAULT_SUPERUSER_PASSWORD is validated as non-blank but
returned without stripping leading or trailing whitespace; retain trimming for
nickname and email normalization.
- Around line 147-164: Update the administrator matching logic around
default_admin_rows to consider only rows with is_active set before selecting a
DEFAULT_SUPERUSER_EMAIL match and performing tenant backfill. Ensure an inactive
matching account cannot suppress the migration AdminException when active
superusers use different emails.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 464285ed-bfa1-4b19-9dbc-bee77861dac9

📥 Commits

Reviewing files that changed from the base of the PR and between 975e734 and 2ef4ade.

📒 Files selected for processing (1)
  • admin/server/auth.py

Comment thread admin/server/auth.py Resolved
Comment thread admin/server/auth.py Resolved
Comment thread admin/server/auth.py Resolved
Taranum01 pushed a commit to Taranum01/ragflow that referenced this pull request Jul 31, 2026
Three follow-ups from the second CodeRabbit pass on infiniflow#17674:

1. **Log the new bootstrap failure flows** (`_required_env` and the
   active-superuser/email mismatch branch) so an operator hitting the
   new errors can see what tripped in the logs, not just in the HTTP
   response. We log only the *setting name* and the *list of existing
   admin emails* — never the password value or the full env map.

2. **Preserve whitespace in DEFAULT_SUPERUSER_PASSWORD** — the
   previous `_required_env` did `.strip()` on every value before
   returning, so a password like "  s3cret  " would be silently
   mutated before being hashed/stored. The helper now returns the raw
   value and only the email/nickname call sites strip whitespace
   (where it would be invalid input).

3. **Filter matching superusers by active status** in
   `init_default_admin` — the previous filter selected any row with
   a matching email, including inactive accounts. An inactive
   matching row paired with an active non-matching row would backfill
   the wrong tenant and silently skip the mismatch error. The filter
   now requires both `u.email == DEFAULT_SUPERUSER_EMAIL` and
   `u.is_active == ActiveEnum.ACTIVE.value`.
@JinHai-CN JinHai-CN added the ci Continue Integration label Aug 10, 2026
@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@JinHai-CN

Copy link
Copy Markdown
Member

@Taranum01 Would please fix the format issue?

┃  ruff-format ❯ 
Would reformat: admin/server/auth.py
1 file would be reformatted

exit status 1

@codecov

codecov Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (aa57022) to head (38a4232).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17674   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Lynn-Inf Lynn-Inf left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One inline comment. Otherwise LGTM.

Comment thread admin/server/auth.py Outdated
# would skip a real active admin with a different email, and
# the "no matching active admin" error below would never
# surface.
default_admin_rows = [u for u in users if u.email == DEFAULT_SUPERUSER_EMAIL and u.is_active == ActiveEnum.ACTIVE.value]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd rather not add the is_active check here. The purpose is to avoid missing an inactive default admin and accidentally creating a duplicate entry.

Taranum01 pushed a commit to Taranum01/ragflow that referenced this pull request Aug 23, 2026
Three follow-ups from the review on infiniflow#17674:

1. **Comment correctness** (`services.EnvironmentsMgr.get_all` returns
   only `DEFAULT_SUPERUSER_EMAIL`, not the password — the previous
   comment implied both were listed, which would mislead an operator
   reading the env-listing output and expect the password to appear
   there too).

2. **Reject blank/whitespace env values** via a `_required_env` helper
   before defining the three module-level constants. Without this,
   `DEFAULT_SUPERUSER_PASSWORD=` would silently persist an empty
   password (os.getenv uses fallback only when *unset*, not when
   empty), making every first login fail with the misleading
   'credentials do not match' error rather than a startup-time
   configuration error.

3. **Admin email mismatch in `init_default_admin`** — when active
   superusers exist but none match `DEFAULT_SUPERUSER_EMAIL`, raise
   an explicit `AdminException` with migration guidance (run the
   API-side `--init-superuser` to align) instead of silently skipping
   the tenant backfill. The previous behaviour diverged the
   bootstrap credential from the env value without telling anyone.

Item 4 (check_admin auth-bypass) does not apply to this PR — the
function referenced in the review was in the closed predecessor
infiniflow#17063, which was superseded by this PR that only touches
`init_default_admin`.
Taranum01 pushed a commit to Taranum01/ragflow that referenced this pull request Aug 23, 2026
Three follow-ups from the second CodeRabbit pass on infiniflow#17674:

1. **Log the new bootstrap failure flows** (`_required_env` and the
   active-superuser/email mismatch branch) so an operator hitting the
   new errors can see what tripped in the logs, not just in the HTTP
   response. We log only the *setting name* and the *list of existing
   admin emails* — never the password value or the full env map.

2. **Preserve whitespace in DEFAULT_SUPERUSER_PASSWORD** — the
   previous `_required_env` did `.strip()` on every value before
   returning, so a password like "  s3cret  " would be silently
   mutated before being hashed/stored. The helper now returns the raw
   value and only the email/nickname call sites strip whitespace
   (where it would be invalid input).

3. **Filter matching superusers by active status** in
   `init_default_admin` — the previous filter selected any row with
   a matching email, including inactive accounts. An inactive
   matching row paired with an active non-matching row would backfill
   the wrong tenant and silently skip the mismatch error. The filter
   now requires both `u.email == DEFAULT_SUPERUSER_EMAIL` and
   `u.is_active == ActiveEnum.ACTIVE.value`.
Taranum01 pushed a commit to Taranum01/ragflow that referenced this pull request Aug 23, 2026
Three follow-ups from the review on infiniflow#17674:

1. **Comment correctness** (`services.EnvironmentsMgr.get_all` returns
   only `DEFAULT_SUPERUSER_EMAIL`, not the password — the previous
   comment implied both were listed, which would mislead an operator
   reading the env-listing output and expect the password to appear
   there too).

2. **Reject blank/whitespace env values** via a `_required_env` helper
   before defining the three module-level constants. Without this,
   `DEFAULT_SUPERUSER_PASSWORD=` would silently persist an empty
   password (os.getenv uses fallback only when *unset*, not when
   empty), making every first login fail with the misleading
   'credentials do not match' error rather than a startup-time
   configuration error.

3. **Admin email mismatch in `init_default_admin`** — when active
   superusers exist but none match `DEFAULT_SUPERUSER_EMAIL`, raise
   an explicit `AdminException` with migration guidance (run the
   API-side `--init-superuser` to align) instead of silently skipping
   the tenant backfill. The previous behaviour diverged the
   bootstrap credential from the env value without telling anyone.

Item 4 (check_admin auth-bypass) does not apply to this PR — the
function referenced in the review was in the closed predecessor
infiniflow#17063, which was superseded by this PR that only touches
`init_default_admin`.
Taranum01 pushed a commit to Taranum01/ragflow that referenced this pull request Aug 23, 2026
Three follow-ups from the second CodeRabbit pass on infiniflow#17674:

1. **Log the new bootstrap failure flows** (`_required_env` and the
   active-superuser/email mismatch branch) so an operator hitting the
   new errors can see what tripped in the logs, not just in the HTTP
   response. We log only the *setting name* and the *list of existing
   admin emails* — never the password value or the full env map.

2. **Preserve whitespace in DEFAULT_SUPERUSER_PASSWORD** — the
   previous `_required_env` did `.strip()` on every value before
   returning, so a password like "  s3cret  " would be silently
   mutated before being hashed/stored. The helper now returns the raw
   value and only the email/nickname call sites strip whitespace
   (where it would be invalid input).

3. **Filter matching superusers by active status** in
   `init_default_admin` — the previous filter selected any row with
   a matching email, including inactive accounts. An inactive
   matching row paired with an active non-matching row would backfill
   the wrong tenant and silently skip the mismatch error. The filter
   now requires both `u.email == DEFAULT_SUPERUSER_EMAIL` and
   `u.is_active == ActiveEnum.ACTIVE.value`.
pauulavas and others added 5 commits August 23, 2026 13:48
Supersedes infiniflow#17063 (closed as superseded due to unrebasable test
fixture drift). This is a fresh port against current `main` of the
core change only; test scaffolding omitted because the previous PR's
reload_admin_auth fixture conflicts with the conftest.py shape that
has since evolved on main.

## Fix

The admin server's bootstrap (`init_default_admin`) and first-login
fallback (`check_admin`) hardcoded [email protected] / admin / admin.
The admin CLI's "list envs" output and the EnvironmentsMgr API both
advertise DEFAULT_SUPERUSER_EMAIL/PASSWORD/NICKNAME as configurable,
but the bootstrap ignored them — operators setting custom env values
saw the docs claim support while the code still created the default
admin. Matches what `api/db/init_data.py:init_superuser` already does
on the API side.

## Change

- Three module-level constants read from env at import time:
  - DEFAULT_SUPERUSER_NICKNAME (default "admin")
  - DEFAULT_SUPERUSER_EMAIL (default "[email protected]")
  - DEFAULT_SUPERUSER_PASSWORD (default "admin")
- `init_default_admin`: superuser row uses constants.
- `init_default_admin`: existing-row lookup uses DEFAULT_SUPERUSER_EMAIL.
- `check_admin`: first-login fallback uses constants.

Refs infiniflow#16876
Three follow-ups from the review on infiniflow#17674:

1. **Comment correctness** (`services.EnvironmentsMgr.get_all` returns
   only `DEFAULT_SUPERUSER_EMAIL`, not the password — the previous
   comment implied both were listed, which would mislead an operator
   reading the env-listing output and expect the password to appear
   there too).

2. **Reject blank/whitespace env values** via a `_required_env` helper
   before defining the three module-level constants. Without this,
   `DEFAULT_SUPERUSER_PASSWORD=` would silently persist an empty
   password (os.getenv uses fallback only when *unset*, not when
   empty), making every first login fail with the misleading
   'credentials do not match' error rather than a startup-time
   configuration error.

3. **Admin email mismatch in `init_default_admin`** — when active
   superusers exist but none match `DEFAULT_SUPERUSER_EMAIL`, raise
   an explicit `AdminException` with migration guidance (run the
   API-side `--init-superuser` to align) instead of silently skipping
   the tenant backfill. The previous behaviour diverged the
   bootstrap credential from the env value without telling anyone.

Item 4 (check_admin auth-bypass) does not apply to this PR — the
function referenced in the review was in the closed predecessor
infiniflow#17063, which was superseded by this PR that only touches
`init_default_admin`.
Three follow-ups from the second CodeRabbit pass on infiniflow#17674:

1. **Log the new bootstrap failure flows** (`_required_env` and the
   active-superuser/email mismatch branch) so an operator hitting the
   new errors can see what tripped in the logs, not just in the HTTP
   response. We log only the *setting name* and the *list of existing
   admin emails* — never the password value or the full env map.

2. **Preserve whitespace in DEFAULT_SUPERUSER_PASSWORD** — the
   previous `_required_env` did `.strip()` on every value before
   returning, so a password like "  s3cret  " would be silently
   mutated before being hashed/stored. The helper now returns the raw
   value and only the email/nickname call sites strip whitespace
   (where it would be invalid input).

3. **Filter matching superusers by active status** in
   `init_default_admin` — the previous filter selected any row with
   a matching email, including inactive accounts. An inactive
   matching row paired with an active non-matching row would backfill
   the wrong tenant and silently skip the mismatch error. The filter
   now requires both `u.email == DEFAULT_SUPERUSER_EMAIL` and
   `u.is_active == ActiveEnum.ACTIVE.value`.
Lefthook's preflight `ruff format` check fails on this file because
the PR added multi-line strings that ruff prefers to keep on one
line. Reformat to satisfy the gate without changing behaviour.
@Taranum01
Taranum01 force-pushed the fix/17063-superuser-env-v2 branch from 5cb1706 to e0d00bc Compare August 23, 2026 08:18
@Lynn-Inf

Copy link
Copy Markdown
Contributor

I noticed that the inline suggestion to "not add the is_active check here" hasn't been addressed yet. I'd recommend removing this check to avoid the risk of duplicate entries.

… empty-check

Address the two outstanding review items on PR infiniflow#17674:

1. @Lynn-Inf's inline request (also raised twice in follow-ups):
   'I'd rather not add the is_active check here. The purpose is to
   avoid missing an inactive default admin and accidentally creating
   a duplicate entry.'

   Drop the trailing 'and u.is_active == ActiveEnum.ACTIVE.value'
   from the default_admin_rows filter. The else-branch should
   treat any superuser row matching DEFAULT_SUPERUSER_EMAIL as
   the configured bootstrap admin — activity gating already
   rejects inactive admins at login (login_admin → raise inactive),
   so the bootstrap path stays read-only and won't mint a duplicate.

2. CodeRabbit's whitespace-validation finding: the original
   _required_env helper checks 'if not value:' on the raw value and
   the caller then '.strip()'s the result, so a whitespace-only
   env value (e.g. DEFAULT_SUPERUSER_NICKNAME=' ') would pass the
   empty check, get stripped to '', and silently propagate. Split
   into two helpers: _required_env (preserves raw value, used for
   the password so '  s3cret  ' isn't mutated) and
   _required_env_stripped (strips before the empty check, used for
   nickname + email). The runner crash now surfaces as the
   intended config-error message at startup.
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Aug 25, 2026
@Taranum01

Copy link
Copy Markdown
Contributor Author

@Lynn-Inf — pushed commit a82a7801 addressing your request and the related whitespace-only CodeRabbit finding:

1. is_active filter removed (your request):

default_admin_rows = [u for u in users if u.email == DEFAULT_SUPERUSER_EMAIL]

Activity gating already happens in login_admin (the is_active == INACTIVE branch at line 240), so the bootstrap path stays read-only and won't mint a duplicate entry.

2. Whitespace-only env values (CodeRabbit, addressed on this PR while here):
Split _required_env into two helpers:

  • _required_env (preserves raw value — used for password so a password like ' s3cret ' keeps its whitespace and isn't silently mutated before hashing).
  • _required_env_stripped (strips before the empty check — used for nickname/email). A whitespace-only DEFAULT_SUPERUSER_NICKNAME=' ' now surfaces the intended 'is set to whitespace-only value' config error at startup instead of slipping through to a silent downstream failure.

ruff format and ruff check both pass on the file.

@Lynn-Inf Lynn-Inf left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@JinHai-CN
JinHai-CN merged commit 4301561 into infiniflow:main Aug 25, 2026
3 checks passed
Taranum01 added a commit to Taranum01/ragflow that referenced this pull request Aug 28, 2026
…ix fallback (infiniflow#17876 review)

Per @xugangqiang's review on infiniflow#17876:

## Removed the trailing commit text in token.go
The previous PR had ' (fix(chunker): preserve incoming Mom ...)' as
stray characters at the end of the append call which broke
compilation with a 'missing , in argument list' typecheck. The
suffix was a left-over commit message, not code. Removed.

## Restored the TrimPrefix fallback in applyChildrenDelimText
The old behaviour used Mom: strings.TrimPrefix(t, "\n") — i.e. the
fallback Mom stripped a single leading newline from the current
chunk's text. My previous change used mom = t (no strip) which would
let the leading newline leak through to JSON-keyed SQL downstream.
Restored the historical default:

    mom := d.Mom
    if mom == "" {
        mom = strings.TrimPrefix(t, "\n")
    }

## Dropped admin/server/auth.py from this PR
The superuser-env work has already landed via PR infiniflow#17674 (commit
4301561) and the current tree contains the improved
_required_env_stripped() version. This PR's auth.py diff would
overwrite the merged fix with the older _required_env() +
caller-side .strip() pattern that CodeRabbit flagged as buggy
('  ' passes the empty check, then collapses to ''). Conflict was
why the PR showed mergeable: CONFLICTING — also flagged in the
review.

After the drop, this PR carries only the chunker Mom-preservation
fix; the superuser-env path stays on its own branch.

## Added the missing tests
- TestApplyChildrenDelimText_FallbackStripsLeadingNewline — pins
  the strings.TrimPrefix behaviour so a future change that drops
  the strip is caught. Uses Text: "\nalpha. beta. gamma" and
  asserts every child Mom == "alpha. beta. gamma" (no leading
  newline).
- TestApplyChildrenDelim_SymmetryWithTextPath — symmetry test
  between the JSON branch (applyChildrenDelim, takes explicit seg)
  and the text branch (applyChildrenDelimText, falls back to
  TrimPrefix(d.Text, "\n")). Asserts both produce the same Mom
  for equivalent input.

## Rebased onto latest main
Skip-dropped the five admin/server/auth.py commits during rebase
to clear the conflict that xugangqiang flagged. The result is a
clean two-file diff:

    internal/ingestion/component/chunker/token.go      | 12 ++++-
    internal/ingestion/component/chunker/token_test.go | 57 ++++++++++++++++++++++
    2 files changed, 68 insertions(+), 1 deletion(-)

gofmt -l clean. Full go build blocked locally by the same office_oxide
cgo transitive dep as in previous PRs (unrelated).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants