[GH-ISSUE #6935] [Bug] LDAP auto-delete detaches clients on the second tick after a partial directory fetch #4589

Closed
opened 2026-10-31 20:40:43 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @muditagrawal2007 on GitHub (Oct 25, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6935

Summary

The LDAP auto-delete safety guard protects only one cron tick. When a directory returns a partial or empty result, the guard refuses deletion, but the job then overwrites its trusted baseline with that untrusted count. The next tick compares against the lowered baseline and detaches clients that are still present in LDAP.

This is a correctness/data-loss bug rather than an authentication bypass: it requires LDAP auto-delete to be enabled and the directory to return an incomplete result.

Impact

  • Clients are detached from every LDAP-managed inbound in the sync.
  • The clients remain in clients and traffic tables but are no longer attached to their inbound, so the sync does not self-heal them.
  • The failure repeats every minute while the partial directory result persists.
  • The first tick logs that auto-delete was skipped, which can make the subsequent destructive tick look surprising.

Affected version

Reproduced against the latest release v3.10.2 and current main (de21c128).

The relevant code is in internal/web/job/ldap_sync_job.go:

if autoDelete && j.autoDeleteSafeForFetch(len(flags)) {
        // ... detach clients absent from flags ...
}
j.lastFlagCount.Store(int64(len(flags)))

autoDeleteSafeForFetch correctly rejects the fetch, but lastFlagCount.Store runs unconditionally. The field therefore changes from a trusted previous population to an untrusted rejected result.

Failure timeline

flowchart TD
    A["Trusted baseline: 10 LDAP users"] --> B["Tick 2: directory returns 4 users"]
    B --> C{"Retention guard<br/>4 is below 50% of 10"}
    C -->|"Refused"| D["No clients detached"]
    C -->|"Bug also stores 4"| E["Baseline lowered to 4"]
    E --> F["Tick 3: directory returns the same 4 users"]
    F --> G{"Retention guard<br/>4 is not below 50% of 4"}
    G -->|"Allowed"| H["6 legitimate clients detached"]
    H --> I["Xray restart scheduled"]

The empty-result variant is worse: a zero baseline disables the retention comparison, so the next partial result is accepted immediately.

Reproduction

Preconditions:

  1. Enable LDAP auto-delete.
  2. Configure an LDAP-managed inbound with at least two clients.
  3. The directory initially returns the full population.

Then change the directory result to a partial population and run the sync twice:

Fetched 10 LDAP flags
LDAP sync job started
Fetched 4 LDAP flags
LDAP auto-delete skipped: fetched 4 users, previous successful sync saw 10 (below 50% retention)
LDAP sync job started
Fetched 4 LDAP flags
Deleted client u4@ldap from inbound id=1(tag=ldap-baseline-in)
Deleted client u5@ldap from inbound id=1(tag=ldap-baseline-in)
Deleted client u6@ldap from inbound id=1(tag=ldap-baseline-in)
Deleted client u7@ldap from inbound id=1(tag=ldap-baseline-in)
Deleted client u8@ldap from inbound id=1(tag=ldap-baseline-in)
Deleted client u9@ldap from inbound id=1(tag=ldap-baseline-in)
Xray restart scheduled after batch deletion

Proposed fix

Only a fetch accepted by the retention guard may advance the baseline:

if autoDelete {
        if !j.autoDeleteSafeForFetch(len(flags)) {
                return
        }
        // ... detach clients absent from flags ...
}
j.lastTrustedFlagCount.Store(int64(len(flags)))

Renaming lastFlagCount to lastTrustedFlagCount makes the invariant explicit: it stores a population that passed the safety check, never a result that was rejected.

This keeps auto-delete's safety-first behavior: clients stay attached while the directory population is implausibly small, until the directory recovers to the configured retention floor.

Regression tests

The accompanying tests exercise the real LDAP wire protocol, the real cron job, the real client services, and a real SQLite database:

  • TestLdapAutoDeleteKeepsBaselineAfterRefusedFetch
  • TestLdapAutoDeleteKeepsBaselineAfterEmptyFetch

Both tests were confirmed red before the fix and green after it.

Verification

go test ./internal/web/job -run 'TestLdapAutoDeleteKeepsBaseline|TestAutoDeleteAllowed' -count=1
go test ./internal/web/job -count=1
go test -race ./internal/web/job -run 'TestLdapAutoDeleteKeepsBaseline|TestAutoDeleteAllowed' -count=1
make verify

All commands pass with the fix.

Originally created by @muditagrawal2007 on GitHub (Oct 25, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6935 ## Summary The LDAP auto-delete safety guard protects only **one cron tick**. When a directory returns a partial or empty result, the guard refuses deletion, but the job then overwrites its trusted baseline with that untrusted count. The next tick compares against the lowered baseline and detaches clients that are still present in LDAP. This is a correctness/data-loss bug rather than an authentication bypass: it requires LDAP auto-delete to be enabled and the directory to return an incomplete result. ## Impact - Clients are detached from every LDAP-managed inbound in the sync. - The clients remain in `clients` and traffic tables but are no longer attached to their inbound, so the sync does not self-heal them. - The failure repeats every minute while the partial directory result persists. - The first tick logs that auto-delete was skipped, which can make the subsequent destructive tick look surprising. ## Affected version Reproduced against the latest release `v3.10.2` and current `main` (`de21c128`). The relevant code is in [`internal/web/job/ldap_sync_job.go`](https://github.com/MHSanaei/3x-ui/blob/main/internal/web/job/ldap_sync_job.go#L160-L171): ```go if autoDelete && j.autoDeleteSafeForFetch(len(flags)) { // ... detach clients absent from flags ... } j.lastFlagCount.Store(int64(len(flags))) ``` `autoDeleteSafeForFetch` correctly rejects the fetch, but `lastFlagCount.Store` runs unconditionally. The field therefore changes from a **trusted previous population** to an **untrusted rejected result**. ## Failure timeline ```mermaid flowchart TD A["Trusted baseline: 10 LDAP users"] --> B["Tick 2: directory returns 4 users"] B --> C{"Retention guard<br/>4 is below 50% of 10"} C -->|"Refused"| D["No clients detached"] C -->|"Bug also stores 4"| E["Baseline lowered to 4"] E --> F["Tick 3: directory returns the same 4 users"] F --> G{"Retention guard<br/>4 is not below 50% of 4"} G -->|"Allowed"| H["6 legitimate clients detached"] H --> I["Xray restart scheduled"] ``` The empty-result variant is worse: a zero baseline disables the retention comparison, so the next partial result is accepted immediately. ## Reproduction Preconditions: 1. Enable LDAP auto-delete. 2. Configure an LDAP-managed inbound with at least two clients. 3. The directory initially returns the full population. Then change the directory result to a partial population and run the sync twice: ```text Fetched 10 LDAP flags LDAP sync job started Fetched 4 LDAP flags LDAP auto-delete skipped: fetched 4 users, previous successful sync saw 10 (below 50% retention) LDAP sync job started Fetched 4 LDAP flags Deleted client u4@ldap from inbound id=1(tag=ldap-baseline-in) Deleted client u5@ldap from inbound id=1(tag=ldap-baseline-in) Deleted client u6@ldap from inbound id=1(tag=ldap-baseline-in) Deleted client u7@ldap from inbound id=1(tag=ldap-baseline-in) Deleted client u8@ldap from inbound id=1(tag=ldap-baseline-in) Deleted client u9@ldap from inbound id=1(tag=ldap-baseline-in) Xray restart scheduled after batch deletion ``` ## Proposed fix Only a fetch accepted by the retention guard may advance the baseline: ```go if autoDelete { if !j.autoDeleteSafeForFetch(len(flags)) { return } // ... detach clients absent from flags ... } j.lastTrustedFlagCount.Store(int64(len(flags))) ``` Renaming `lastFlagCount` to `lastTrustedFlagCount` makes the invariant explicit: it stores a population that passed the safety check, never a result that was rejected. This keeps auto-delete's safety-first behavior: clients stay attached while the directory population is implausibly small, until the directory recovers to the configured retention floor. ## Regression tests The accompanying tests exercise the real LDAP wire protocol, the real cron job, the real client services, and a real SQLite database: - `TestLdapAutoDeleteKeepsBaselineAfterRefusedFetch` - `TestLdapAutoDeleteKeepsBaselineAfterEmptyFetch` Both tests were confirmed red before the fix and green after it. ## Verification ```text go test ./internal/web/job -run 'TestLdapAutoDeleteKeepsBaseline|TestAutoDeleteAllowed' -count=1 go test ./internal/web/job -count=1 go test -race ./internal/web/job -run 'TestLdapAutoDeleteKeepsBaseline|TestAutoDeleteAllowed' -count=1 make verify ``` All commands pass with the fix.
Author
Owner

@muditagrawal2007 commented on GitHub (Oct 25, 2026):

Implemented in #6936.\n\nThe fix keeps the retention baseline unchanged whenever autoDeleteSafeForFetch rejects a directory result, and renames the field to lastTrustedFlagCount to make that invariant explicit. The PR adds protocol-level regression coverage for both partial and empty directory responses, and the full make verify gate passes locally.

<!-- gh-comment-id:6401633137 --> @muditagrawal2007 commented on GitHub (Oct 25, 2026): Implemented in #6936.\n\nThe fix keeps the retention baseline unchanged whenever `autoDeleteSafeForFetch` rejects a directory result, and renames the field to `lastTrustedFlagCount` to make that invariant explicit. The PR adds protocol-level regression coverage for both partial and empty directory responses, and the full `make verify` gate passes locally.
Author
Owner

@github-actions[bot] commented on GitHub (Oct 25, 2026):

Confirmed bug, still present on the default branch. The auto-delete retention guard only protects one cron tick. The job's baseline is overwritten with the fetch the guard just rejected, so the next tick compares against that lowered number and detaches clients that are still in the directory. This was introduced together with the guard and ships in v3.10.0 and v3.10.2. @MHSanaei

What the code does

internal/web/job/ldap_sync_job.go, (*LdapSyncJob).Run:

// ldap_sync_job.go:162
if autoDelete && j.autoDeleteSafeForFetch(len(flags)) {
    ...
        j.deleteClientsNotInLDAP(tag, ldapEmailSet)
    ...
}
j.lastFlagCount.Store(int64(len(flags)))   // :171, runs even when the guard said no

autoDeleteSafeForFetch reads that same field as its baseline:

// ldap_sync_job.go:181-182
previous := j.lastFlagCount.Load()
if previous > 0 && int64(fetched)*100 < previous*ldapAutoDeleteMinRetainPercent {

Its own warning calls the field the "previous successful sync" (:183), and the constant's comment says a fetch must keep 50% of "the previous successful fetch" (:16-18). The intent is clear, and line 171 breaks it. With ldapAutoDeleteMinRetainPercent = 50, your example plays out as follows:

  1. Tick 1 fetches 10 users and stores 10.
  2. Tick 2 fetches 4. The check 400 < 500 refuses the fetch, but 4 is stored anyway.
  3. Tick 3 fetches 4 again. 400 < 200 is false, so the fetch is accepted and the 6 missing clients go to BulkDetach (:313).

The empty variant you describe is also right. Line 177 refuses fetched == 0, but line 171 then stores 0. On the next tick the previous > 0 condition at line 182 is false, so any non-empty partial result is accepted with no retention comparison at all.

The existing test TestAutoDeleteAllowed (internal/web/job/ldap_auto_delete_guard_test.go) only checks autoDeleteSafeForFetch with a hand-set previous. It never runs two ticks through Run, so it cannot catch this. I could not see the regression tests you mention because they are not in this repository, so I have not verified them.

Verdict: Confirmed bug
Severity: High (clients lose inbound access through an opt-in feature (ldapAutoDelete) after a directory hiccup; the rows survive and can be re-attached)
Confidence: High
Root cause: internal/web/job/ldap_sync_job.go:171: Run calls j.lastFlagCount.Store(int64(len(flags))) unconditionally, so a fetch the guard refused (autoDeleteSafeForFetch, :176-188) becomes the next tick's baseline. Introduced in f4b7b08e "fix(ldap): stop auto-delete from wiping every client on an empty directory".
Same class: Same invariant ("only a trusted fetch may set the baseline"), different trigger: lastFlagCount is an in-memory atomic.Int64 (:25) on a job built fresh by job.NewLdapSyncJob() (internal/web/web.go:396). After every panel restart the baseline is 0, so the first post-restart tick accepts any non-empty partial fetch (:182 previous > 0 short-circuits). This is my inference from the code, and the proposed fix does not cover it.
Already fixed: Still present on the default branch (7f82daa4); f4b7b08e is in v3.10.0 and v3.10.2
Duplicate of: None
Evidence: ldap_sync_job.go:162, :171, :177-179, :181-186, :16-18; ldap_auto_delete_guard_test.go:7-33; git tag --contains f4b7b08e → v3.10.0, v3.10.2
Not determined: Whether the maintainer wants the baseline to persist across restarts. That is a design choice, not something the source answers.

Suggested fix: only a fetch that autoDeleteSafeForFetch accepted should update the baseline, so move the Store inside the accepted branch, as the reporter proposes. When auto-delete is off, the job can still record the count. One trade-off to decide on: a real drop of more than 50% in the directory would then block auto-delete until the panel restarts, because the baseline would never come down. That case may need a deliberate override path.

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:6401639506 --> @github-actions[bot] commented on GitHub (Oct 25, 2026): **Confirmed bug, still present on the default branch.** The auto-delete retention guard only protects one cron tick. The job's baseline is overwritten with the fetch the guard just rejected, so the next tick compares against that lowered number and detaches clients that are still in the directory. This was introduced together with the guard and ships in `v3.10.0` and `v3.10.2`. @MHSanaei ### What the code does `internal/web/job/ldap_sync_job.go`, `(*LdapSyncJob).Run`: ```go // ldap_sync_job.go:162 if autoDelete && j.autoDeleteSafeForFetch(len(flags)) { ... j.deleteClientsNotInLDAP(tag, ldapEmailSet) ... } j.lastFlagCount.Store(int64(len(flags))) // :171, runs even when the guard said no ``` `autoDeleteSafeForFetch` reads that same field as its baseline: ```go // ldap_sync_job.go:181-182 previous := j.lastFlagCount.Load() if previous > 0 && int64(fetched)*100 < previous*ldapAutoDeleteMinRetainPercent { ``` Its own warning calls the field the "previous successful sync" (`:183`), and the constant's comment says a fetch must keep 50% of "the previous successful fetch" (`:16-18`). The intent is clear, and line 171 breaks it. With `ldapAutoDeleteMinRetainPercent = 50`, your example plays out as follows: 1. Tick 1 fetches 10 users and stores 10. 2. Tick 2 fetches 4. The check `400 < 500` refuses the fetch, but 4 is stored anyway. 3. Tick 3 fetches 4 again. `400 < 200` is false, so the fetch is accepted and the 6 missing clients go to `BulkDetach` (`:313`). The empty variant you describe is also right. Line 177 refuses `fetched == 0`, but line 171 then stores 0. On the next tick the `previous > 0` condition at line 182 is false, so any non-empty partial result is accepted with no retention comparison at all. The existing test `TestAutoDeleteAllowed` (`internal/web/job/ldap_auto_delete_guard_test.go`) only checks `autoDeleteSafeForFetch` with a hand-set `previous`. It never runs two ticks through `Run`, so it cannot catch this. I could not see the regression tests you mention because they are not in this repository, so I have not verified them. Verdict: Confirmed bug Severity: High (clients lose inbound access through an opt-in feature (`ldapAutoDelete`) after a directory hiccup; the rows survive and can be re-attached) Confidence: High Root cause: `internal/web/job/ldap_sync_job.go:171`: `Run` calls `j.lastFlagCount.Store(int64(len(flags)))` unconditionally, so a fetch the guard refused (`autoDeleteSafeForFetch`, `:176-188`) becomes the next tick's baseline. Introduced in f4b7b08e "fix(ldap): stop auto-delete from wiping every client on an empty directory". Same class: Same invariant ("only a trusted fetch may set the baseline"), different trigger: `lastFlagCount` is an in-memory `atomic.Int64` (`:25`) on a job built fresh by `job.NewLdapSyncJob()` (`internal/web/web.go:396`). After every panel restart the baseline is 0, so the first post-restart tick accepts any non-empty partial fetch (`:182` `previous > 0` short-circuits). This is my inference from the code, and the proposed fix does not cover it. Already fixed: Still present on the default branch (7f82daa4); f4b7b08e is in `v3.10.0` and `v3.10.2` Duplicate of: None Evidence: `ldap_sync_job.go:162`, `:171`, `:177-179`, `:181-186`, `:16-18`; `ldap_auto_delete_guard_test.go:7-33`; `git tag --contains f4b7b08e` → `v3.10.0`, `v3.10.2` Not determined: Whether the maintainer wants the baseline to persist across restarts. That is a design choice, not something the source answers. Suggested fix: only a fetch that `autoDeleteSafeForFetch` accepted should update the baseline, so move the `Store` inside the accepted branch, as the reporter proposes. When auto-delete is off, the job can still record the count. One trade-off to decide on: a real drop of more than 50% in the directory would then block auto-delete until the panel restarts, because the baseline would never come down. That case may need a deliberate override path. *This reply was generated automatically; a maintainer may follow up.* <!-- claude-issue:analyst -->
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#4589
No description provided.