Files
3x-ui/internal/web/service/client_renewal_write_validation_test.go
Jack 9672249edb feat(clients): add calendar weekly renewal and schedule previews (#6524)
* feat(clients): add calendar weekly renewal and schedule previews

Expose fixed-day, calendar-weekly, calendar-monthly, and disabled renewal
through one shared selector in individual and bulk client forms. Store the
weekly weekday separately (Monday 1 through Sunday 7) and use panel-local
calendar dates rather than a fixed 168-hour duration. Resolve skipped or
repeated midnights to the first valid instant of the selected date, and skip
an entirely nonexistent calendar date rather than changing the weekday.

Reuse the existing renewal writer and share its boundary alignment and
per-period catch-up calculation with an authenticated, read-only preview.
Keep monthly precedence for legacy records, fixed-day interval semantics,
maximum renewal allowances, first-use durations, and operator-disabled
settings unchanged. Selecting a mode does not rewrite an existing cutoff;
an unset calendar cutoff requires an explicit action to choose the first.
The last-valid-second preview uses the stored exclusive expiry, even when
the billing calculation aligns a legacy last-second cutoff up to midnight.

Carry weekly schedules through client persistence, paging, enable toggles,
inbound settings, and node traffic reconciliation. Migrate missing or nullable
weekday columns to disabled by default without altering existing limits, and
include the new isolated-schema PostgreSQL regression in the live CI gate.

Regenerate API contracts and reference documentation, add lifecycle and form
regressions, and document timezone, quota-reset, and upgrade considerations.
All participating nodes must be upgraded before weekly mode is enabled;
older binaries ignore the new field. Independent periodic traffic resets and
the optional month-end subscription-header display are not changed.

* fix(clients): validate renewal schedules across inbound write paths

Reject conflicting weekly/interval/monthly schedules and out-of-range
weekdays on inbound creation and edits, legacy one-client apply paths,
record/link synchronization, and traffic metadata writes. Validate imported
traffic snapshots as well, before any inbound or client is persisted, so
an inbound API cannot create a client that the clients page cannot toggle.

Merge a weekly-related schedule as one timestamp-selected tuple rather
than filling its zero fields from another renewal mode. Preserve empty
migration snapshots and the existing non-weekly monthly/interval merge
semantics. Renewal caps, counters, credentials, and deadlines are unchanged.

Add regressions for nine write paths, unchanged records and runtime calls
after rejection, valid inbound clients remaining editable, and duplicate
record merges between individually valid renewal modes.

* docs(clients): clarify depleted-client deletion risks on downgrade

Explain in English and Chinese that older versions not only stop weekly
renewal: their depleted-client cleanup can delete a weekly-only client once
its expiry or quota is exhausted. This is conditional on cleanup, not an
automatic deletion caused by downgrade itself.

Recommend backing up and converting weekly schedules to a mode supported
by every participating version before rollback, and avoiding cleanup while
mixed versions or unconverted clients remain. Merely disabling weekly
renewal does not restore the old binary's missing purge protection.

* fix(clients): bound weekly renewal date searches

Limit the search for a valid weekly calendar date to eight candidates so
an unusual timezone cannot monopolize the single traffic writer. Exhaustion
returns the original instant, allowing the existing catch-up forward-progress
guard to stop without advancing expiry, consuming an allowance, resetting
traffic, or falling back to a fixed-duration schedule that can drift.

Reject a non-future calendar suggestion in the read-only preview instead of
offering an immediately expired initial cutoff. Also report failed weekly
catch-up as a search error when allowances remain, not as cap exhaustion.
Existing preview errors use the form's current warning; no API schema or
locale changes are needed.

Exercise exhaustion with a synthetic valid TZif containing twelve skipped
Sundays. This fault-injection case was red without the bound; it is not a
claim that a production IANA timezone was observed hanging. Keep the Havana
and Apia regressions for real skipped/repeated midnights and absent dates.

* fix(tests): isolate weekly renewal preview timezone

Stop the weekly search regression from replacing process-global time.Local.
CI caught that assignment and its cleanup racing with background timer reads
through time.Now, even though the top-level tests do not use t.Parallel.

Pass the timezone and current instant into the unchanged preview calculation.
The public service still validates the request and resolves the panel timezone;
API responses, renewal accounting, and persisted client data are unchanged.

Use fixed dates for both suggestion and catch-up exhaustion, removing the
test's dependency on today's date and its unnecessary database setup. Keep a
bounded-lifetime background clock reader to expose future global-timezone
mutations under the existing race gate rather than disabling that check.

* ci: retrigger PR checks

Create an empty commit to request a fresh pull-request CI run after release dependency downloads failed with network errors.

No source, dependency, or workflow changes are included. Retry the existing checks without bypassing them.

* ci: retry PR checks and record deferred download hardening

Request another CI run after the amd64 release job compiled successfully but failed during dependency fetching with exit code 4 (network failure).

Record possible follow-up improvements for the Linux release fetch helper:
- Print each download URL and destination, and preserve error details.
- Reuse the existing curl configuration with up to five retries; add connection and per-attempt timeouts and a bounded retry window.
- Download to a temporary file and promote it to the final filename only after a successful, non-empty transfer. Keep the job failing if downloads ultimately fail.
- Validate successful downloads, recovery after a temporary failure, and correct failure after persistent errors before shipping such a change.

These improvements are intentionally deferred, not implemented or tested by this commit. This commit is empty: renewal logic, dependencies, workflow configuration, check requirements, and TLS verification remain unchanged.

---------

Co-authored-by: JacktheRanger <219502738+JacktheRanger@users.noreply.github.com>
2026-09-26 22:59:23 +02:00

132 lines
5.8 KiB
Go

package service
import (
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
func TestClientRenewalWriteValidation(t *testing.T) {
for _, operation := range []string{"add inbound", "update inbound", "add inbound client", "update inbound client", "sync inbound", "client delta", "add stat", "update stat", "import stat"} {
for _, schedule := range []struct {
name string
reset, day, weekday int
errorMessage string
}{
{"weekly and interval", 7, 0, 3, "client weekly renewal cannot be combined with reset or resetDay"},
{"weekly and monthly", 0, 1, 3, "client weekly renewal cannot be combined with reset or resetDay"},
{"invalid weekday", 0, 0, 8, "client resetWeekday must be between 0 and 7, got: 8"},
} {
t.Run(operation+"/"+schedule.name, func(t *testing.T) {
setupConflictDB(t)
nodeID, fake := setupNodeRuntime(t)
svc, inboundSvc := &ClientService{}, &InboundService{}
client := model.Client{Email: "renewal-boundary", ID: "11111111-1111-1111-1111-111111111111", SubID: "renewal-boundary-sub", Enable: true, ResetWeekday: 3, ResetMax: 4, ExpiryTime: time.Now().Add(time.Hour).UnixMilli()}
inbound := nodeInbound(t, nodeID, 41759, []model.Client{client})
if err := inboundSvc.AddClientStat(database.GetDB(), inbound.Id, &client); err != nil {
t.Fatal(err)
}
record, err := svc.GetRecordByEmail(nil, client.Email)
if err != nil {
t.Fatal(err)
}
beforeRecord := *record
beforeTraffic := readTraffic(t, database.GetDB(), client.Email)
beforeSettings := inbound.Settings
client.Reset, client.ResetDay, client.ResetWeekday = schedule.reset, schedule.day, schedule.weekday
update := *inbound
update.Settings = clientsSettings(t, []model.Client{client})
switch operation {
case "add inbound", "import stat":
update.Id, update.Port, update.Tag = 0, 41760, "renewal-boundary-new"
if operation == "import stat" {
update.Settings = beforeSettings
update.ClientStats = []xray.ClientTraffic{{Email: "invalid-import-stat", Reset: schedule.reset, ResetDay: schedule.day, ResetWeekday: schedule.weekday}}
}
_, _, err = inboundSvc.AddInbound(&update)
case "update inbound":
_, _, err = inboundSvc.UpdateInbound(&update)
case "add inbound client":
client.Email = "invalid-new-client"
update.Settings = clientsSettings(t, []model.Client{client})
_, err = svc.AddInboundClient(inboundSvc, &update)
case "update inbound client":
_, err = svc.UpdateInboundClient(inboundSvc, &update, client.Email)
case "sync inbound":
err = svc.SyncInbound(nil, inbound.Id, []model.Client{client})
case "client delta":
err = svc.ApplyInboundClientDelta(nil, inbound.Id, []model.Client{client}, nil)
case "add stat":
err = inboundSvc.AddClientStat(database.GetDB(), inbound.Id, &client)
case "update stat":
err = inboundSvc.UpdateClientStat(database.GetDB(), client.Email, &client)
}
if err == nil || err.Error() != schedule.errorMessage+"\n" {
t.Fatalf("write error = %v, want %q", err, schedule.errorMessage)
}
var persisted model.Inbound
if err := database.GetDB().First(&persisted, inbound.Id).Error; err != nil {
t.Fatal(err)
}
if persisted.Settings != beforeSettings {
t.Fatal("rejected write changed inbound settings")
}
record, err = svc.GetRecordByEmail(nil, beforeRecord.Email)
if err != nil || *record != beforeRecord || readTraffic(t, database.GetDB(), beforeRecord.Email) != beforeTraffic {
t.Fatalf("rejected write changed client/traffic: record=%+v error=%v", record, err)
}
for _, table := range []string{"inbounds", "clients", "client_traffics"} {
var count int64
if err := database.GetDB().Table(table).Count(&count).Error; err != nil || count != 1 {
t.Fatalf("%s count/error = %d/%v, want 1/nil", table, count, err)
}
}
if fake.addInbound.Load() != 0 || fake.updateInbound.Load() != 0 || fake.delInbound.Load() != 0 || fake.addClient.Load() != 0 || fake.updateUser.Load() != 0 {
t.Fatal("rejected write dispatched to the runtime")
}
})
}
}
}
func TestInboundRenewalModesRemainEditable(t *testing.T) {
for _, weekly := range []bool{false, true} {
name := "legacy monthly with interval"
if weekly {
name = "weekly"
}
t.Run(name, func(t *testing.T) {
setupConflictDB(t)
nodeID, _ := setupNodeRuntime(t)
svc, inboundSvc := &ClientService{}, &InboundService{}
client := model.Client{Email: "renewal-editable", ID: "11111111-1111-1111-1111-111111111111", Enable: true, Reset: 7, ResetDay: 1, ResetMax: 4, ExpiryTime: time.Now().Add(time.Hour).UnixMilli()}
if weekly {
client.Reset, client.ResetDay, client.ResetWeekday = 0, 0, 3
}
inbound := &model.Inbound{Tag: "renewal-editable", NodeID: &nodeID, Port: 41761, Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, []model.Client{client})}
if _, _, err := inboundSvc.AddInbound(inbound); err != nil {
t.Fatal(err)
}
if _, _, err := inboundSvc.UpdateInbound(inbound); err != nil {
t.Fatal(err)
}
record, err := svc.GetRecordByEmail(nil, client.Email)
if err != nil {
t.Fatal(err)
}
toggle := *record.ToClient()
toggle.Enable = false
if _, err := svc.Update(inboundSvc, record.Id, toggle, 0); err != nil {
t.Fatalf("valid inbound client could not be toggled: %v", err)
}
record, err = svc.GetRecordByEmail(nil, client.Email)
if err != nil || record.Enable || record.Reset != client.Reset || record.ResetDay != client.ResetDay || record.ResetWeekday != client.ResetWeekday || record.ResetMax != 4 {
t.Fatalf("valid schedule/toggle not preserved: %+v/%v", record, err)
}
})
}
}