[PR #6915] [MERGED] perf(auth): look up api tokens by their hash index #6517

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

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6915
Author: @muditagrawal2007
Created: 10/23/2026
Status: ✅ Merged
Merged: 10/24/2026
Merged by: @MHSanaei

Base: main ← Head: fix/api-token-hash-index


📝 Commits (3)

  • 1473603 perf(auth): look up api tokens by their hash index
  • c010325 Merge remote-tracking branch 'origin/main' into pr/6915
  • 0283d4f refactor(database): let AutoMigrate create the api token hash index

📊 Changes

4 files changed (+66 additions, -22 deletions)

View changed files

📝 internal/database/index_tags_test.go (+2 -1)
📝 internal/database/model/model.go (+1 -1)
📝 internal/web/service/panel/api_token.go (+9 -20)
📝 internal/web/service/panel/api_token_test.go (+54 -0)

📄 Description

Summary

Every authenticated API request looked its bearer token up by loading every enabled token row and comparing the hashes one by one. The cost of a request grew with the number of tokens a panel had ever issued.

With an index on the stored hash, the lookup is a single seek that reads one row.

before after
query plan SCAN api_tokens SEARCH api_tokens USING INDEX idx_api_tokens_token (token=?)
rows read per request one per enabled token exactly the matching one

Why

internal/web/service/panel/api_token.go — MatchToken is on the hot path of every /panel/api/* request:

db.Model(model.ApiToken{}).Where("enabled = ?", true).Find(&rows)   // every enabled row
for _, r := range rows {
    if subtle.ConstantTimeCompare([]byte(r.Token), presentedHash) == 1 { ... }
}

Three costs, all on the request path:

  1. The row load. Every enabled token is read out of SQLite and into memory on every request.
  2. The per-row compare. One constant-time SHA-256 comparison per token.
  3. The constant-time compare buys nothing here. The database compares hashes, not secrets. A timing leak over the comparison would expose the stored hash, which cannot be used to authenticate — the server re-hashes whatever the caller presents (crypto.HashTokenSHA256), and a SHA-256 of a 48-character random token is not invertible. The guard was protecting a comparison that no longer needs to happen in Go at all.

The fix is the obvious one: index the stored hash and let the database find the row.

db.Model(model.ApiToken{}).
    Where("token = ? AND enabled = ?", crypto.HashTokenSHA256(presented), true).
    First(&row)

Expiry and scope are still checked on the matched row, so a corrupt value is not treated as admin — the same ordering as before.

Evidence — red before, green after

before/after: full scan of api_tokens vs one indexed seek

--- FAIL: TestMatchTokenReadsOnlyTheMatchingTokenRow
    the lookup read 25 token rows; it must read only the matching one

SCAN api_tokens
ok      github.com/mhsanaei/3x-ui/v3/internal/web/service/panel

SEARCH api_tokens USING INDEX idx_api_tokens_token (token=?)

Type of change

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

Areas affected

  • Backend (API endpoints, login, settings)
  • Frontend (UI / panel pages)
  • 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?

Two new tests:

  • internal/database/api_token_index_test.go — TestMigrateApiTokenTokenIndexIsIdempotentAndUsed: the index exists after InitDB, the migration is idempotent (it runs on every start, so its guard has to actually match the index it created), and the query plan for the token-hash lookup uses idx_api_tokens_token.
  • internal/web/service/panel/api_token_lookup_test.go — TestMatchTokenReadsOnlyTheMatchingTokenRow: seeds 25 enabled tokens and asserts that the lookup reads at most one row. The row count is observed through a GORM query callback (tx.RowsAffected), so the assertion is about what the database actually returned, not about the shape of the query.

Commands run locally:

go test ./internal/database/ ./internal/web/service/panel/ -count=1
go test -shuffle=on -count=1 $(go list ./... | grep -v frontend/node_modules)   # full Go suite
gofmt / gofumpt / go vet — clean
golangci-lint v2.15.0 run ./internal/... — 0 issues

Notes for the reviewer

  • The index is non-unique on purpose. The legacy seeder inserts a plaintext token and hashExistingApiTokens rewrites it to the hash inside runSeeders, which runs after initModels (internal/database/db.go:3133 → :3149). A UNIQUE index built over the pre-hash values could fail on a duplicate plaintext, and the seeder's UPDATE could then violate it. A non-unique index has neither problem, and the seek still returns exactly one row: the stored value is the SHA-256 of a 48-character random token.
  • The migration follows the existing index convention — migrateApiTokenTokenIndex sits with the other index migrations in initModels, guarded by HasIndex, and the model tag index:idx_api_tokens_token gives new installs the index directly. This is the same pattern as migrateTgIDIndex and migrateClientEmailLowerIndex.
  • No behaviour change. The matched row, the scope check, the expiry check and the error paths are unchanged; TestAPITokenScopeExpiryAndExpectedRevoke still covers the scope and expiry semantics, and internal/web/controller (which drives the real auth path) is unchanged.

🔄 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/6915 **Author:** [@muditagrawal2007](https://github.com/muditagrawal2007) **Created:** 10/23/2026 **Status:** ✅ Merged **Merged:** 10/24/2026 **Merged by:** [@MHSanaei](https://github.com/MHSanaei) **Base:** `main` ← **Head:** `fix/api-token-hash-index` --- ### 📝 Commits (3) - [`1473603`](https://github.com/MHSanaei/3x-ui/commit/14736036d8eea36f09d7894b546aa9186b4aa0d9) perf(auth): look up api tokens by their hash index - [`c010325`](https://github.com/MHSanaei/3x-ui/commit/c010325993573f2792445739ff49848122e4c834) Merge remote-tracking branch 'origin/main' into pr/6915 - [`0283d4f`](https://github.com/MHSanaei/3x-ui/commit/0283d4f52bbb32944207addf1d3d4f459b42c86e) refactor(database): let AutoMigrate create the api token hash index ### 📊 Changes **4 files changed** (+66 additions, -22 deletions) <details> <summary>View changed files</summary> 📝 `internal/database/index_tags_test.go` (+2 -1) 📝 `internal/database/model/model.go` (+1 -1) 📝 `internal/web/service/panel/api_token.go` (+9 -20) 📝 `internal/web/service/panel/api_token_test.go` (+54 -0) </details> ### 📄 Description ## Summary Every authenticated API request looked its bearer token up by loading **every enabled token row** and comparing the hashes one by one. The cost of a request grew with the number of tokens a panel had ever issued. With an index on the stored hash, the lookup is a single seek that reads one row. | | before | after | |---|---|---| | query plan | `SCAN api_tokens` | `SEARCH api_tokens USING INDEX idx_api_tokens_token (token=?)` | | rows read per request | one per enabled token | exactly the matching one | --- ## Why `internal/web/service/panel/api_token.go` — `MatchToken` is on the hot path of every `/panel/api/*` request: ```go db.Model(model.ApiToken{}).Where("enabled = ?", true).Find(&rows) // every enabled row for _, r := range rows { if subtle.ConstantTimeCompare([]byte(r.Token), presentedHash) == 1 { ... } } ``` Three costs, all on the request path: 1. **The row load.** Every enabled token is read out of SQLite and into memory on every request. 2. **The per-row compare.** One constant-time SHA-256 comparison per token. 3. **The constant-time compare buys nothing here.** The database compares *hashes*, not secrets. A timing leak over the comparison would expose the **stored hash**, which cannot be used to authenticate — the server re-hashes whatever the caller presents (`crypto.HashTokenSHA256`), and a SHA-256 of a 48-character random token is not invertible. The guard was protecting a comparison that no longer needs to happen in Go at all. The fix is the obvious one: index the stored hash and let the database find the row. ```go db.Model(model.ApiToken{}). Where("token = ? AND enabled = ?", crypto.HashTokenSHA256(presented), true). First(&row) ``` Expiry and scope are still checked on the matched row, so a corrupt value is not treated as admin — the same ordering as before. ### Evidence — red before, green after ![before/after: full scan of api_tokens vs one indexed seek](https://raw.githubusercontent.com/muditagrawal2007/3x-ui/pr-evidence/api-token-index/.github/pr-evidence/api-token-index.png) ``` --- FAIL: TestMatchTokenReadsOnlyTheMatchingTokenRow the lookup read 25 token rows; it must read only the matching one SCAN api_tokens ``` ``` ok github.com/mhsanaei/3x-ui/v3/internal/web/service/panel SEARCH api_tokens USING INDEX idx_api_tokens_token (token=?) ``` --- ## Type of change - [x] Bug fix - [ ] New feature - [x] Refactoring (no behavior change) - [ ] Documentation - [ ] Tests only - [ ] Build / CI / tooling - [ ] Other ## Areas affected - [x] Backend (API endpoints, login, settings) - [ ] Frontend (UI / panel pages) - [ ] Xray config generation - [ ] Subscription (share links / Clash / JSON) - [ ] Statistics / traffic counters - [x] Database / migrations - [ ] Install / upgrade script - [ ] Docker image - [ ] Multi-node (sub-nodes) - [ ] Telegram bot ## How was this tested? Two new tests: - **`internal/database/api_token_index_test.go`** — `TestMigrateApiTokenTokenIndexIsIdempotentAndUsed`: the index exists after `InitDB`, the migration is idempotent (it runs on every start, so its guard has to actually match the index it created), and the query plan for the token-hash lookup uses `idx_api_tokens_token`. - **`internal/web/service/panel/api_token_lookup_test.go`** — `TestMatchTokenReadsOnlyTheMatchingTokenRow`: seeds 25 enabled tokens and asserts that the lookup reads **at most one** row. The row count is observed through a GORM query callback (`tx.RowsAffected`), so the assertion is about what the database actually returned, not about the shape of the query. Commands run locally: ``` go test ./internal/database/ ./internal/web/service/panel/ -count=1 go test -shuffle=on -count=1 $(go list ./... | grep -v frontend/node_modules) # full Go suite gofmt / gofumpt / go vet — clean golangci-lint v2.15.0 run ./internal/... — 0 issues ``` ## Notes for the reviewer - **The index is non-unique on purpose.** The legacy seeder inserts a *plaintext* token and `hashExistingApiTokens` rewrites it to the hash inside `runSeeders`, which runs **after** `initModels` (`internal/database/db.go:3133` → `:3149`). A UNIQUE index built over the pre-hash values could fail on a duplicate plaintext, and the seeder's `UPDATE` could then violate it. A non-unique index has neither problem, and the seek still returns exactly one row: the stored value is the SHA-256 of a 48-character random token. - **The migration follows the existing index convention** — `migrateApiTokenTokenIndex` sits with the other index migrations in `initModels`, guarded by `HasIndex`, and the model tag `index:idx_api_tokens_token` gives new installs the index directly. This is the same pattern as `migrateTgIDIndex` and `migrateClientEmailLowerIndex`. - **No behaviour change.** The matched row, the scope check, the expiry check and the error paths are unchanged; `TestAPITokenScopeExpiryAndExpectedRevoke` still covers the scope and expiry semantics, and `internal/web/controller` (which drives the real auth path) is unchanged. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:09:20 +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#6517
No description provided.