[PR #6405] [MERGED] fix(cli): let -getApiToken name the token it regenerates #6257

Closed
opened 2026-11-02 04:07:26 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6405
Author: @rokokol
Created: 9/3/2026
Status: ✅ Merged
Merged: 9/8/2026
Merged by: @MHSanaei

Base: main ← Head: fix/cli-token-name


📝 Commits (4)

  • eaa4229 fix(cli): let -getApiToken name the token it regenerates
  • 9a1fcf9 fix(cli): keep the installer's token out of the rotated slot
  • a0f52c5 fix(cli): stop the -getApiToken true form from swallowing -tokenName
  • 351bbbb Merge branch 'main' into fix/cli-token-name

📊 Changes

5 files changed (+208 additions, -9 deletions)

View changed files

➕ api_token_cli_test.go (+148 -0)
📝 install.sh (+2 -2)
📝 internal/web/service/panel/api_token.go (+4 -0)
📝 internal/web/service/panel/api_token_test.go (+25 -0)
📝 main.go (+29 -7)

📄 Description

Summary

x-ui setting -getApiToken now takes an optional -tokenName, so callers stop sharing one hardcoded credential slot, and its help text describes what it actually does instead of claiming to display a token.

Why

The flag is registered as "Display current API token". It cannot display anything — tokens are stored as SHA-256 hashes, and the command's own first two output lines say exactly that. What it does is destroy and reissue a credential: GetApiToken calls RecreateByName(cliFallbackTokenName), and cliFallbackTokenName is the hardcoded "cli-fallback". RecreateByName deletes every row with that name and creates a new one.

Two consequences:

  1. The help text invites a destructive action. An operator reads "Display current API token", runs it expecting a read-only lookup, and revokes a credential somebody else is using.
  2. The name is a single global slot. Two operators — or an operator and an automated job — silently invalidate each other. The loser is left with a token that answers HTTP 404 with an empty body, which is indistinguishable from a wrong webBasePath, so the failure never says what happened.

This is not hypothetical in this repository: install.sh is one of the colliding callers, at lines 1231 and 1325:

config_apiToken=$(${xui_folder}/x-ui setting -getApiToken true | grep -Eo 'apiToken: .+' | awk '{print $2}')

A hand-run -getApiToken invalidates the token the installer just wrote into the install-result file, and re-running the installer invalidates the operator's.

What changed

  • -tokenName <name>, defaulting to cli-fallback. Every existing invocation, install.sh included, behaves exactly as before.
  • -getApiToken deliberately stays a boolean. install.sh called it as -getApiToken true; with BoolVar that trailing true is a positional, but a StringVar would swallow it as the flag's value and mint a token literally named true. That rules out the -getApiToken=<name> shape.
  • The -getApiToken true form no longer swallows later flags. Go's flag package stops parsing at the first non-flag argument, so that trailing true does not merely get ignored — it terminates parsing. An operator copying the shape the repository itself demonstrated and running x-ui setting -getApiToken true -tokenName ci-bot left tokenName empty and rotated cli-fallback: exactly the collision this PR removes, reached through the documented invocation. Both install.sh call sites drop the stray true, and setting now warns whenever it is handed positional arguments, naming what it ignored. A warning rather than an error, because an older install.sh in the wild still passes true and has to keep working.
  • Corrected help text on both branches. The strings described only the rotation path, so on a fresh panel -h announced cli-fallback while the command actually mints install, and nothing is regenerated or invalidated there at all.
  • An explicit name reaches both branches of GetApiToken. The function has two: on a database with no tokens it calls Create, otherwise it rotates via RecreateByName. Without -tokenName each keeps the name it already used — install and cli-fallback respectively — so unnamed calls are byte-for-byte unchanged. With -tokenName ci-bot both branches use ci-bot, so the same command no longer yields a different name depending on whether the database happens to be empty.
  • RecreateByName now caps the name at 64 characters. Create already enforces that on the same column; RecreateByName did not, and it now receives operator input. It has exactly one production caller, so nothing else can regress.

Why the two default names were left alone

Unifying them looks tempting — the install token is never rotated by the CLI, so it persists indefinitely — but it would break the case this PR exists to fix. install.sh records the token it gets on a fresh panel into its install-result file. If both branches rotated cli-fallback, the operator's next bare -getApiToken would destroy that exact row and silently invalidate the recorded credential. The split default is what keeps an unnamed call harmless; TestGetApiTokenPreservesInstallTokenWhenRotating pins it by comparing the row's id and hash across a rotation.

Not included, deliberately: RecreateByName never sets Scope, so its rows silently take the column default of admin, while Create runs NormalizeScope. Exposing a -tokenScope flag means fixing that asymmetry first — a privilege question that deserves its own PR and its own reasoning rather than riding along here.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Documentation
  • Tests only
  • Build / CI / tooling
  • Other

Areas affected

  • Frontend (UI / panel pages)
  • Backend (API endpoints, login, settings)
  • Xray config generation
  • Subscription (share links / Clash / JSON)
  • Statistics / traffic counters
  • Database / migrations
  • Install / upgrade script
  • Docker image
  • Multi-node (sub-nodes)
  • Telegram bot

How was this tested?

New api_token_cli_test.go (package main, throwaway DB via XUI_DB_FOLDER) plus one case added to internal/web/service/panel/api_token_test.go. Each was checked to fail without the fix:

Test Fails without
TestGetApiTokenRotatesOnlyTheNamedToken threading the name through — this is the bug: a call naming ci-bot must leave weekly-report authenticating
TestGetApiTokenUsesGivenNameOnEmptyDatabase the name reaching the Create branch
TestGetApiTokenPreservesInstallTokenWhenRotating the split default — checks the install row's id and hash survive a later rotation, so a deleted-and-recreated row cannot pass
TestGetApiTokenTrimsName the TrimSpace fallback
TestGetApiTokenWarnsOnIgnoredPositionalArgs pins that -getApiToken true -tokenName ci-bot leaves tokenName empty and leaves the positional visible, so the CLI can warn rather than silently rotate cli-fallback
TestRecreateByNameRejectsOverlongName the 64-character cap, asserting the concrete message rather than any error
go build ./...
go test ./... -shuffle=on -count=1
golangci-lint run          # 0 issues
gofumpt -l                 # clean

Manual, against a scratch database:

$ x-ui setting -getApiToken true          # install.sh's exact form, fresh DB
apiToken: YWl2RfKhCW…                     # still parseable by its grep

$ x-ui setting -getApiToken               # operator, later
The API token "cli-fallback" has been regenerated (any previous one is now invalid):
apiToken: khf3yrIzOzOz…

$ x-ui setting -getApiToken -tokenName ci-bot
The API token "ci-bot" has been regenerated (any previous one is now invalid):

$ x-ui setting -getApiToken true -tokenName ci-bot     # the old, trap-shaped form
warning: ignored "true -tokenName ci-bot" and any flags after it; put flags before positional arguments
The API token "cli-fallback" has been regenerated (any previous one is now invalid):

$ sqlite3 x-ui.db 'select name from api_tokens order by id;'
install
cli-fallback
ci-bot

The installer's token is still there and untouched; the fallback slot rotated; the named one is its own row.

Screenshots / recordings

N/A — CLI only.

Breaking changes

None. Without -tokenName the command does exactly what it did before on both branches — install on a fresh panel, cli-fallback afterwards — so install.sh needs no change and no recorded credential is invalidated. The only additions are a new optional flag and a corrected help string.

Checklist

  • I tested the change locally and confirmed the described behavior.
  • I added or updated tests for the new behavior (when applicable).
  • go build ./... and the test suite pass locally.
  • For frontend changes: npm run lint, npm run typecheck, and npm run build pass. — N/A, no frontend change
  • I updated the Wiki / README / API docs if user-facing behavior changed. — -getApiToken is not documented under docs/; the corrected -h output is the only reference
  • My commits follow the project's existing message style.
  • I have no unrelated changes mixed into this PR.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/MHSanaei/3x-ui/pull/6405 **Author:** [@rokokol](https://github.com/rokokol) **Created:** 9/3/2026 **Status:** ✅ Merged **Merged:** 9/8/2026 **Merged by:** [@MHSanaei](https://github.com/MHSanaei) **Base:** `main` ← **Head:** `fix/cli-token-name` --- ### 📝 Commits (4) - [`eaa4229`](https://github.com/MHSanaei/3x-ui/commit/eaa422945380df9164503a1dc2a39c1a6523888e) fix(cli): let -getApiToken name the token it regenerates - [`9a1fcf9`](https://github.com/MHSanaei/3x-ui/commit/9a1fcf90f7c4e9f22876ae4b8aa5a8d2bc312719) fix(cli): keep the installer's token out of the rotated slot - [`a0f52c5`](https://github.com/MHSanaei/3x-ui/commit/a0f52c505d976a75bb6f5c12f947fa03f293cb94) fix(cli): stop the `-getApiToken true` form from swallowing -tokenName - [`351bbbb`](https://github.com/MHSanaei/3x-ui/commit/351bbbb04980361576dfed23b645bd8f155231fd) Merge branch 'main' into fix/cli-token-name ### 📊 Changes **5 files changed** (+208 additions, -9 deletions) <details> <summary>View changed files</summary> ➕ `api_token_cli_test.go` (+148 -0) 📝 `install.sh` (+2 -2) 📝 `internal/web/service/panel/api_token.go` (+4 -0) 📝 `internal/web/service/panel/api_token_test.go` (+25 -0) 📝 `main.go` (+29 -7) </details> ### 📄 Description ## Summary `x-ui setting -getApiToken` now takes an optional `-tokenName`, so callers stop sharing one hardcoded credential slot, and its help text describes what it actually does instead of claiming to display a token. ## Why The flag is registered as **"Display current API token"**. It cannot display anything — tokens are stored as SHA-256 hashes, and the command's own first two output lines say exactly that. What it does is destroy and reissue a credential: `GetApiToken` calls `RecreateByName(cliFallbackTokenName)`, and `cliFallbackTokenName` is the hardcoded `"cli-fallback"`. `RecreateByName` deletes every row with that name and creates a new one. Two consequences: 1. **The help text invites a destructive action.** An operator reads "Display current API token", runs it expecting a read-only lookup, and revokes a credential somebody else is using. 2. **The name is a single global slot.** Two operators — or an operator and an automated job — silently invalidate each other. The loser is left with a token that answers `HTTP 404` with an empty body, which is indistinguishable from a wrong `webBasePath`, so the failure never says what happened. This is not hypothetical in this repository: **`install.sh` is one of the colliding callers**, at lines 1231 and 1325: ```sh config_apiToken=$(${xui_folder}/x-ui setting -getApiToken true | grep -Eo 'apiToken: .+' | awk '{print $2}') ``` A hand-run `-getApiToken` invalidates the token the installer just wrote into the install-result file, and re-running the installer invalidates the operator's. ## What changed - **`-tokenName <name>`**, defaulting to `cli-fallback`. Every existing invocation, `install.sh` included, behaves exactly as before. - **`-getApiToken` deliberately stays a boolean.** `install.sh` called it as `-getApiToken true`; with `BoolVar` that trailing `true` is a positional, but a `StringVar` would swallow it as the flag's value and mint a token literally named `true`. That rules out the `-getApiToken=<name>` shape. - **The `-getApiToken true` form no longer swallows later flags.** Go's `flag` package stops parsing at the first non-flag argument, so that trailing `true` does not merely get ignored — it *terminates* parsing. An operator copying the shape the repository itself demonstrated and running `x-ui setting -getApiToken true -tokenName ci-bot` left `tokenName` empty and rotated `cli-fallback`: exactly the collision this PR removes, reached through the documented invocation. Both `install.sh` call sites drop the stray `true`, and `setting` now warns whenever it is handed positional arguments, naming what it ignored. A warning rather than an error, because an older `install.sh` in the wild still passes `true` and has to keep working. - **Corrected help text on both branches.** The strings described only the rotation path, so on a fresh panel `-h` announced `cli-fallback` while the command actually mints `install`, and nothing is regenerated or invalidated there at all. - **An explicit name reaches both branches of `GetApiToken`.** The function has two: on a database with no tokens it calls `Create`, otherwise it rotates via `RecreateByName`. Without `-tokenName` each keeps the name it already used — `install` and `cli-fallback` respectively — so unnamed calls are byte-for-byte unchanged. With `-tokenName ci-bot` both branches use `ci-bot`, so the same command no longer yields a different name depending on whether the database happens to be empty. - **`RecreateByName` now caps the name at 64 characters.** `Create` already enforces that on the same column; `RecreateByName` did not, and it now receives operator input. It has exactly one production caller, so nothing else can regress. ### Why the two default names were left alone Unifying them looks tempting — the `install` token is never rotated by the CLI, so it persists indefinitely — but it would break the case this PR exists to fix. `install.sh` records the token it gets on a fresh panel into its install-result file. If both branches rotated `cli-fallback`, the operator's next bare `-getApiToken` would destroy that exact row and silently invalidate the recorded credential. The split default is what keeps an unnamed call harmless; `TestGetApiTokenPreservesInstallTokenWhenRotating` pins it by comparing the row's id and hash across a rotation. Not included, deliberately: `RecreateByName` never sets `Scope`, so its rows silently take the column default of `admin`, while `Create` runs `NormalizeScope`. Exposing a `-tokenScope` flag means fixing that asymmetry first — a privilege question that deserves its own PR and its own reasoning rather than riding along here. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactoring (no behavior change) - [ ] Documentation - [ ] Tests only - [ ] Build / CI / tooling - [ ] Other ## Areas affected - [ ] Frontend (UI / panel pages) - [x] Backend (API endpoints, login, settings) - [ ] Xray config generation - [ ] Subscription (share links / Clash / JSON) - [ ] Statistics / traffic counters - [ ] Database / migrations - [x] Install / upgrade script - [ ] Docker image - [ ] Multi-node (sub-nodes) - [ ] Telegram bot ## How was this tested? New `api_token_cli_test.go` (package `main`, throwaway DB via `XUI_DB_FOLDER`) plus one case added to `internal/web/service/panel/api_token_test.go`. Each was checked to fail without the fix: | Test | Fails without | |---|---| | `TestGetApiTokenRotatesOnlyTheNamedToken` | threading the name through — this is the bug: a call naming `ci-bot` must leave `weekly-report` authenticating | | `TestGetApiTokenUsesGivenNameOnEmptyDatabase` | the name reaching the `Create` branch | | `TestGetApiTokenPreservesInstallTokenWhenRotating` | the split default — checks the `install` row's id **and** hash survive a later rotation, so a deleted-and-recreated row cannot pass | | `TestGetApiTokenTrimsName` | the `TrimSpace` fallback | | `TestGetApiTokenWarnsOnIgnoredPositionalArgs` | pins that `-getApiToken true -tokenName ci-bot` leaves `tokenName` empty and leaves the positional visible, so the CLI can warn rather than silently rotate `cli-fallback` | | `TestRecreateByNameRejectsOverlongName` | the 64-character cap, asserting the concrete message rather than any error | ``` go build ./... go test ./... -shuffle=on -count=1 golangci-lint run # 0 issues gofumpt -l # clean ``` Manual, against a scratch database: ``` $ x-ui setting -getApiToken true # install.sh's exact form, fresh DB apiToken: YWl2RfKhCW… # still parseable by its grep $ x-ui setting -getApiToken # operator, later The API token "cli-fallback" has been regenerated (any previous one is now invalid): apiToken: khf3yrIzOzOz… $ x-ui setting -getApiToken -tokenName ci-bot The API token "ci-bot" has been regenerated (any previous one is now invalid): $ x-ui setting -getApiToken true -tokenName ci-bot # the old, trap-shaped form warning: ignored "true -tokenName ci-bot" and any flags after it; put flags before positional arguments The API token "cli-fallback" has been regenerated (any previous one is now invalid): $ sqlite3 x-ui.db 'select name from api_tokens order by id;' install cli-fallback ci-bot ``` The installer's token is still there and untouched; the fallback slot rotated; the named one is its own row. ## Screenshots / recordings N/A — CLI only. ## Breaking changes None. Without `-tokenName` the command does exactly what it did before on both branches — `install` on a fresh panel, `cli-fallback` afterwards — so `install.sh` needs no change and no recorded credential is invalidated. The only additions are a new optional flag and a corrected help string. ## Checklist - [x] I tested the change locally and confirmed the described behavior. - [x] I added or updated tests for the new behavior (when applicable). - [x] `go build ./...` and the test suite pass locally. - [ ] For frontend changes: `npm run lint`, `npm run typecheck`, and `npm run build` pass. — N/A, no frontend change - [ ] I updated the Wiki / README / API docs if user-facing behavior changed. — `-getApiToken` is not documented under `docs/`; the corrected `-h` output is the only reference - [x] My commits follow the project's existing message style. - [x] I have no unrelated changes mixed into this PR. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:07:26 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#6257
No description provided.