From 05f7aa94bbe15af6ef1e2d36144978c0d7e20f66 Mon Sep 17 00:00:00 2001 From: GlobalTechInfo Date: Sat, 17 Oct 2026 18:30:27 +0500 Subject: [PATCH 1/2] Manage VLESS client UUIDs from the dashboard Until now the REALITY client list was a comma-joined config value, so revoking a UUID meant editing configuration and restarting the service. A management screen that only takes effect on restart is a trap, so this makes the change real. The list lives in a vless_clients table, one row per client. Precedence is unchanged in spirit: REALITY_CLIENT_IDS still pins the list from configuration and now says so, because accepting edits that quietly do nothing is worse than refusing them. An id left behind by the old comma-joined value is adopted into the table on first run rather than dropped -- otherwise the first dashboard change would revoke a client that is still in the field. Making it live meant teaching the xray supervisor to re-point itself. The reload carries a config that has already passed `xray run --test`, so an invalid change is refused and the running front door keeps serving; the supervisor is the only thing that stops and starts the child, and it answers once the new child is actually accepting connections. Measured live: an add applies in 0.08s. Two refusals worth having. Removing the last client is rejected, because xray with no clients is a front door that rejects everyone and an operator should have to mean it. And a refused change restores the row rather than dropping it, so the database never claims something xray does not do. Verified live against xray on a real port: a UUID added through the API served traffic immediately, the same client failed the moment it was revoked, the untouched client kept working, and xray's own log named the refusal (proxy/vless/encoding: rejected). Covered end to end in tests too, including the case the race detector caught on the way: s.cfg is written under configMu while being read here. --- README.md | 18 +- database.go | 150 ++++++++++++++ main.go | 157 ++++++++++++++- reality.go | 348 +++++++++++++++++++++++++++----- reality_test.go | 14 +- vless_test.go | 526 ++++++++++++++++++++++++++++++++++++++++++++++++ web/index.html | 144 +++++++++++++ 7 files changed, 1300 insertions(+), 57 deletions(-) create mode 100644 vless_test.go diff --git a/README.md b/README.md index 65bf066..2d45693 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Deploys on any PaaS, including the ones that expose only a single HTTP endpoint. - **Single-Port Multiplexing** - SOCKS5, TLS, dashboards and the tunnel share one port, so it runs on Render/Koyeb/Heroku/Northflank where raw TCP never reaches the app - **WebSocket Tunnel** - Carries SOCKS5 over an HTTP upgrade for platforms whose edge terminates TLS; ships with a matching client - **REALITY** - Xray front door that presents a real website's certificate to an active prober; sessions still land in the SOCKS5 pipeline +- **VLESS Client Management** - Add, disable and revoke REALITY UUIDs from the dashboard; xray is reloaded in place, no restart - **Client Mode** - Same binary exposes a local SOCKS5 port that relays through the tunnel - **User Management** - Create, update, delete users with tier-based limits - **Tier System** - Free, Basic, Pro, and Unlimited tiers with connection/data/bandwidth limits @@ -310,8 +311,14 @@ other REALITY-capable client can import the same parameters instead: | Fingerprint | `chrome` | | Flow | none | -Give each device its own UUID (`xray uuid`, then list them in -`REALITY_CLIENT_IDS`) so one can be revoked without disturbing the others. +Give each device its own UUID so one can be revoked without disturbing the +others. The dashboard's **REALITY Clients** panel is the usual way: add a client, +and the UUID reaches xray immediately. Revoking one takes effect within a second +and needs no restart. + +Setting `REALITY_CLIENT_IDS` still works, and pins the list from configuration: +while it is set the panel says so and refuses changes rather than accepting edits +that would quietly do nothing. `REALITY_BIND` defaults to `0.0.0.0:443`, which is IPv4 only. On an IPv6-only host set it to `[::]:443`. @@ -390,7 +397,7 @@ Edit `config.json` or use environment variables (env vars override config file): | `REALITY_SERVER_NAMES` | dest host | SNI values to impersonate, comma separated | | `REALITY_PRIVATE_KEY` | generated | REALITY private key. Generated once and reused from the database when empty; `xray x25519` prints a pair | | `REALITY_SHORT_IDS` | generated | Short ids, comma separated. Up to 16 hex characters; rotating locks out existing clients | -| `REALITY_CLIENT_IDS` | generated | VLESS UUIDs, comma separated, one per device. `xray uuid` prints one | +| `REALITY_CLIENT_IDS` | generated | VLESS UUIDs, comma separated. Pins the list and disables panel management | | `REALITY_PUBLIC_HOST` | empty | This host's IP or domain, written into the generated client config so it is usable as-is | | `XRAY_BIN` | xray | Path to the xray binary | | `REALITY_CLIENT_FILE` | reality-client.json | Where the generated client config is written | @@ -454,8 +461,9 @@ socks5-proxy restore -in socks5-20261017.tar.gz The archive holds `socks5.db`, `config.json` and, when REALITY is enabled, `reality-client.json`. **Restoring the same archive keeps every REALITY client -working**, because the keypair travels with it; restoring an older or different -one invalidates every client you have imported. +working**, because the keypair travels with it and the managed VLESS UUIDs live +in the database; restoring an older or different one invalidates every client you +have imported. `restore` refuses to run while the server is up, because replacing a database that another process still has open is how SQLite ends up cleaning up the wrong diff --git a/database.go b/database.go index 8129ffa..ec18546 100644 --- a/database.go +++ b/database.go @@ -8,6 +8,7 @@ import ( "log/slog" "os" "path/filepath" + "strings" "sync" "time" @@ -121,6 +122,16 @@ func (s *Store) migrate() error { )`, `CREATE INDEX IF NOT EXISTS idx_user_connections_user ON user_connections(user_id)`, `CREATE INDEX IF NOT EXISTS idx_user_connections_time ON user_connections(connected_at)`, + // VLESS client UUIDs for the REALITY front door. One row per client, so + // a revoked id is a deleted or disabled row rather than an edit of a + // comma-joined string, and the dashboard has a name to show for each. + `CREATE TABLE IF NOT EXISTS vless_clients ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + uuid TEXT UNIQUE NOT NULL, + label TEXT NOT NULL DEFAULT '', + enabled INTEGER NOT NULL DEFAULT 1, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP + )`, } for _, q := range queries { @@ -577,6 +588,145 @@ func (s *Store) ResetUserData(id int64) error { return err } +// ─── VLESS clients ───────────────────────────────────────────────────────── +// +// The UUIDs xray accepts on the REALITY inbound. Only enabled rows reach the +// rendered config, so disabling one revokes it without deleting the record. + +type VlessClient struct { + ID int64 `json:"id"` + UUID string `json:"uuid"` + Label string `json:"label"` + Enabled bool `json:"enabled"` + CreatedAt string `json:"created_at"` +} + +// IsUUID reports whether s looks like a UUID xray would accept. Deliberately +// shape-only: this is the trust boundary between an operator typing into the +// dashboard and the xray config, so the check is cheap and never guesses. +func IsUUID(s string) bool { + if len(s) != 36 { + return false + } + for i, c := range s { + switch i { + case 8, 13, 18, 23: + if c != '-' { + return false + } + default: + if !strings.ContainsRune("0123456789abcdefABCDEF", c) { + return false + } + } + } + return true +} + +func (s *Store) CreateVlessClient(uuid, label string) (*VlessClient, error) { + uuid = strings.TrimSpace(uuid) + if !IsUUID(uuid) { + return nil, fmt.Errorf("%q is not a UUID", uuid) + } + s.mu.Lock() + res, err := s.db.Exec("INSERT INTO vless_clients (uuid, label) VALUES (?, ?)", uuid, label) + if err != nil { + s.mu.Unlock() + return nil, err + } + id, err := res.LastInsertId() + s.mu.Unlock() + if err != nil { + return nil, err + } + // Read the row back rather than echoing the arguments: created_at is a + // database default, and a response that shows it empty is worse than one + // that shows the truth. + return s.GetVlessClient(id) +} + +func (s *Store) ListVlessClients() ([]VlessClient, error) { + s.mu.Lock() + defer s.mu.Unlock() + + rows, err := s.db.Query("SELECT id, uuid, label, enabled, created_at FROM vless_clients ORDER BY id") + if err != nil { + return nil, err + } + defer rows.Close() + + out := []VlessClient{} + for rows.Next() { + var c VlessClient + var enabled int + if err := rows.Scan(&c.ID, &c.UUID, &c.Label, &enabled, &c.CreatedAt); err != nil { + return nil, err + } + c.Enabled = enabled != 0 + out = append(out, c) + } + return out, rows.Err() +} + +// EnabledVlessClientUUIDs is what the xray config is rendered from. +func (s *Store) EnabledVlessClientUUIDs() ([]string, error) { + clients, err := s.ListVlessClients() + if err != nil { + return nil, err + } + out := make([]string, 0, len(clients)) + for _, c := range clients { + if c.Enabled { + out = append(out, c.UUID) + } + } + return out, nil +} + +func (s *Store) GetVlessClient(id int64) (*VlessClient, error) { + s.mu.Lock() + defer s.mu.Unlock() + + var c VlessClient + var enabled int + err := s.db.QueryRow("SELECT id, uuid, label, enabled, created_at FROM vless_clients WHERE id=?", id). + Scan(&c.ID, &c.UUID, &c.Label, &enabled, &c.CreatedAt) + if err != nil { + return nil, err + } + c.Enabled = enabled != 0 + return &c, nil +} + +func (s *Store) UpdateVlessClient(id int64, label *string, enabled *bool) error { + s.mu.Lock() + defer s.mu.Unlock() + + if label != nil { + if _, err := s.db.Exec("UPDATE vless_clients SET label=? WHERE id=?", *label, id); err != nil { + return err + } + } + if enabled != nil { + value := 0 + if *enabled { + value = 1 + } + if _, err := s.db.Exec("UPDATE vless_clients SET enabled=? WHERE id=?", value, id); err != nil { + return err + } + } + return nil +} + +func (s *Store) DeleteVlessClient(id int64) error { + s.mu.Lock() + defer s.mu.Unlock() + + _, err := s.db.Exec("DELETE FROM vless_clients WHERE id=?", id) + return err +} + // ─── Connection Tracking ─────────────────────────────────────────────────── func (s *Store) TrackConnectionStart(userID int64, target string) (int64, error) { diff --git a/main.go b/main.go index 08b4d25..36f7f73 100644 --- a/main.go +++ b/main.go @@ -538,6 +538,14 @@ type ProxyServer struct { // Persistence store *Store + // REALITY front door. The runner is nil unless REALITY_ENABLED is set, and + // realityKeys is the key material its config was rendered from, so a + // dashboard change to the VLESS client list can be re-rendered and swapped + // in without a restart. + realityMu sync.Mutex + reality *realityRunner + realityKeys realityKeys + // Shutdown shutdownOnce sync.Once shutdownCh chan struct{} @@ -1736,6 +1744,150 @@ func (s *ProxyServer) adminHandler() http.Handler { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) }) + // ─── VLESS clients (REALITY) ────────────────────────────────────────── + // + // A UUID added here is accepted by xray within a second, and a deleted or + // disabled one stops working just as fast. Management that only took + // effect on restart would be a trap. + + mux.HandleFunc("/api/vless-clients", func(w http.ResponseWriter, r *http.Request) { + if s.store == nil { + http.Error(w, "database not available", http.StatusServiceUnavailable) + return + } + + switch r.Method { + case http.MethodGet: + clients, err := s.store.ListVlessClients() + if err != nil { + http.Error(w, "list failed: "+err.Error(), http.StatusInternalServerError) + return + } + s.realityMu.Lock() + enabled := s.reality != nil + s.realityMu.Unlock() + s.configMu.RLock() + pinned := len(s.cfg.RealityClientIDs) > 0 + s.configMu.RUnlock() + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]any{ + "clients": clients, + "reality_enabled": enabled, + "managed_by_config": pinned, + }) + + case http.MethodPost: + if err := s.requireRealityManager(w); err != nil { + return + } + var req struct { + UUID string `json:"uuid"` + Label string `json:"label"` + } + if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil { + http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest) + return + } + s.configMu.RLock() + xrayBin := s.cfg.RealityXrayBin + s.configMu.RUnlock() + + uuid := strings.TrimSpace(req.UUID) + if uuid == "" { + generated, err := generateVlessUUID(xrayBin) + if err != nil { + http.Error(w, "could not generate a uuid: "+err.Error(), http.StatusInternalServerError) + return + } + uuid = generated + } + client, err := s.store.CreateVlessClient(uuid, req.Label) + if err != nil { + http.Error(w, "create failed: "+err.Error(), http.StatusBadRequest) + return + } + if err := s.applyVlessClients(); err != nil { + // The row is saved, so removing it here keeps the database and + // the running xray telling the same story. + s.store.DeleteVlessClient(client.ID) + http.Error(w, "xray rejected the change, nothing was applied: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(client) + + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } + }) + + mux.HandleFunc("/api/vless-clients/", func(w http.ResponseWriter, r *http.Request) { + if s.store == nil { + http.Error(w, "database not available", http.StatusServiceUnavailable) + return + } + parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/vless-clients/"), "/") + if len(parts) == 0 || parts[0] == "" { + http.Error(w, "client ID required", http.StatusBadRequest) + return + } + id := parseInt64(parts[0]) + + switch { + case r.Method == http.MethodDelete && len(parts) == 1: + if err := s.requireRealityManager(w); err != nil { + return + } + client, err := s.store.GetVlessClient(id) + if err != nil { + http.Error(w, "client not found", http.StatusNotFound) + return + } + if err := s.store.DeleteVlessClient(id); err != nil { + http.Error(w, "delete failed: "+err.Error(), http.StatusInternalServerError) + return + } + if err := s.applyVlessClients(); err != nil { + // Put the row back: xray never stopped accepting it, so the + // database must not claim otherwise. + if _, rerr := s.store.CreateVlessClient(client.UUID, client.Label); rerr != nil { + s.logger.Error("could not restore a refused vless client", "uuid", client.UUID, "error", rerr) + } + http.Error(w, "xray rejected the change, nothing was applied: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]string{"status": "deleted"}) + + case r.Method == http.MethodPut && len(parts) == 1: + if err := s.requireRealityManager(w); err != nil { + return + } + var req struct { + Label *string `json:"label"` + Enabled *bool `json:"enabled"` + } + if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil { + http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest) + return + } + if err := s.store.UpdateVlessClient(id, req.Label, req.Enabled); err != nil { + http.Error(w, "update failed: "+err.Error(), http.StatusInternalServerError) + return + } + if err := s.applyVlessClients(); err != nil { + http.Error(w, "xray rejected the change, nothing was applied: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]string{"status": "updated"}) + + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } + }) + // GET /api/tiers - list available tiers mux.HandleFunc("/api/tiers", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { @@ -2079,12 +2231,15 @@ func runServer(logger *slog.Logger, configFile string) { // rather than leaving a front door that never came up. var reality *realityRunner if cfg.RealityEnabled { - runner, err := startRealityForServer(cfg, dbCfg, store, logger) + runner, keys, err := startRealityForServer(cfg, dbCfg, store, logger) if err != nil { logger.Error("failed to start REALITY", "error", err) os.Exit(1) } reality = runner + // Handed to the server so the dashboard can add and revoke VLESS + // clients without a restart. + server.reality, server.realityKeys = runner, keys } // Periodic stats persistence (every 60 seconds) diff --git a/reality.go b/reality.go index 7ef496d..ff590f0 100644 --- a/reality.go +++ b/reality.go @@ -10,6 +10,7 @@ import ( "fmt" "log/slog" "net" + "net/http" "os" "os/exec" "path/filepath" @@ -445,12 +446,22 @@ func resolveRealityKeys(cfg Config, persisted map[string]string, store *Store, l keys.ShortID = hex.EncodeToString(raw) } + // Client UUIDs, in precedence order: + // + // 1. REALITY_CLIENT_IDS. Configuration pinning always wins, which is the + // same promise the rest of the environment handling makes. + // 2. The vless_clients table, which the dashboard manages. + // 3. The legacy comma-joined config value, adopted into the table on first + // run so an upgrade does not revoke anyone's UUID. + // 4. A generated one, which becomes a table row so it survives a restart. keys.ClientIDs = nonEmpty(cfg.RealityClientIDs) - if len(keys.ClientIDs) == 0 && persisted[dbRealityClientIDs] != "" { - keys.ClientIDs = splitList(persisted[dbRealityClientIDs]) + if len(keys.ClientIDs) == 0 && store != nil { + keys.ClientIDs, _ = store.EnabledVlessClientUUIDs() + if len(keys.ClientIDs) == 0 && persisted[dbRealityClientIDs] != "" { + keys.ClientIDs = adoptLegacyClientIDs(store, splitList(persisted[dbRealityClientIDs]), logger) + } } - generatedIDs := len(keys.ClientIDs) == 0 - if generatedIDs { + if len(keys.ClientIDs) == 0 { out, err := runXray(bin, "uuid") if err != nil { return keys, err @@ -461,6 +472,13 @@ func resolveRealityKeys(cfg Config, persisted map[string]string, store *Store, l if len(keys.ClientIDs) == 0 { return keys, errors.New("xray uuid returned no id") } + if store != nil { + // A UUID that changes on every restart would silently break every + // saved client profile, so the generated one is stored. + if _, err := store.CreateVlessClient(keys.ClientIDs[0], "generated"); err != nil { + logger.Warn("could not store the generated VLESS id; it will change on restart", "error", err) + } + } } if keys.ServerName = firstNonEmpty(cfg.RealityServerNames...); keys.ServerName == "" { @@ -478,14 +496,32 @@ func resolveRealityKeys(cfg Config, persisted map[string]string, store *Store, l if generatedShortID { saveRealitySetting(store, logger, dbRealityShortID, keys.ShortID) } - if generatedIDs { - saveRealitySetting(store, logger, dbRealityClientIDs, strings.Join(keys.ClientIDs, ",")) - } } return keys, nil } +// adoptLegacyClientIDs moves an id list from the old comma-joined config value +// into the table. Without this, the first dashboard change would drop the ids +// that upgrade brought with it, because the table would then shadow the config. +func adoptLegacyClientIDs(store *Store, ids []string, logger *slog.Logger) []string { + for _, id := range ids { + if !IsUUID(id) { + continue + } + if _, err := store.CreateVlessClient(id, "migrated"); err != nil { + logger.Warn("could not migrate a REALITY client id; it will be dropped from the managed list", "error", err) + continue + } + } + kept, err := store.EnabledVlessClientUUIDs() + if err != nil { + logger.Warn("could not read the migrated VLESS ids", "error", err) + return nil + } + return kept +} + func saveRealitySetting(store *Store, logger *slog.Logger, key, value string) { if err := store.SaveConfig(key, value); err != nil { // Non-fatal: the value is still in use this run, it just will not @@ -566,73 +602,100 @@ func pruneStaleRealityConfigs(maxAge time.Duration) { // realityRunner owns the xray child process. type realityRunner struct { - bin string - cfgFile string - logger *slog.Logger + bin string + logger *slog.Logger + host string + port int mu sync.Mutex + cfgFile string // owned by supervise() once running; read under mu elsewhere cmd *exec.Cmd stopped bool + reload chan realityReload stop chan struct{} exited chan struct{} } +// realityReload asks the supervisor to swap in a new, already validated config +// file. The supervisor replies on done; a nil error means xray is running on the +// new file. +type realityReload struct { + cfgFile string + done chan error +} + // startReality validates the rendered config before serving, so a broken setup // fails loudly at startup instead of leaving a silent dead front door. func startReality(cfg Config, k realityKeys, logger *slog.Logger) (*realityRunner, error) { - data, err := renderRealityServerConfig(cfg, k) + bin := cfg.RealityXrayBin + if bin == "" { + bin = "xray" + } + cfgFile, err := renderValidatedServerConfig(bin, cfg, k) if err != nil { return nil, err } + pruneStaleRealityConfigs(24 * time.Hour) + + r := &realityRunner{ + bin: bin, + cfgFile: cfgFile, + logger: logger, + reload: make(chan realityReload, 1), + stop: make(chan struct{}), + exited: make(chan struct{}), + } + if host, port, err := splitHostPort(cfg.RealityBind); err == nil { + r.host, r.port = host, port + } + go r.supervise() + + r.waitReady() + return r, nil +} + +// renderValidatedServerConfig writes the config to a private temp file and asks +// xray to parse it. A config that does not validate is deleted and reported, so +// a bad change never takes a working front door down. +func renderValidatedServerConfig(bin string, cfg Config, k realityKeys) (string, error) { + data, err := renderRealityServerConfig(cfg, k) + if err != nil { + return "", err + } + file, err := os.CreateTemp("", "xray-reality-*.json") if err != nil { - return nil, fmt.Errorf("write xray config: %w", err) + return "", fmt.Errorf("write xray config: %w", err) } cfgFile := file.Name() if _, err := file.Write(data); err != nil { file.Close() os.Remove(cfgFile) - return nil, fmt.Errorf("write xray config: %w", err) + return "", fmt.Errorf("write xray config: %w", err) } file.Close() // CreateTemp already opens 0600, which matters: the file holds the REALITY // private key and the proxy credentials. - bin := cfg.RealityXrayBin - if bin == "" { - bin = "xray" - } if _, err := runXray(bin, "run", "-c", cfgFile, "--test"); err != nil { // runXray already carries xray's own complaint, which is the part worth // reading ("failed to listen...", "invalid private key", and so on). os.Remove(cfgFile) - return nil, err - } - - pruneStaleRealityConfigs(24 * time.Hour) - - r := &realityRunner{ - bin: bin, - cfgFile: cfgFile, - logger: logger, - stop: make(chan struct{}), - exited: make(chan struct{}), + return "", err } - go r.supervise() - - if host, port, err := splitHostPort(cfg.RealityBind); err == nil { - r.waitReady(host, port, 10*time.Second) - } - return r, nil + return cfgFile, nil } // waitReady logs whether the REALITY port started answering. A failure here is // not fatal: xray may still be retrying, and its own log carries the reason. -func (r *realityRunner) waitReady(host string, port int, timeout time.Duration) { - target := net.JoinHostPort(host, strconv.Itoa(port)) - deadline := time.Now().Add(timeout) +func (r *realityRunner) waitReady() { + if r.host == "" { + return + } + target := net.JoinHostPort(r.host, strconv.Itoa(r.port)) + deadline := time.Now().Add(10 * time.Second) for time.Now().Before(deadline) { conn, err := net.DialTimeout("tcp", target, 300*time.Millisecond) if err == nil { @@ -646,9 +709,19 @@ func (r *realityRunner) waitReady(host string, port int, timeout time.Duration) // supervise keeps xray alive. Without this a single crash would silently remove // the front door while every dashboard still reported a healthy proxy. +// +// It is also the only place the child is started, stopped and re-pointed, which +// is what makes a config swap safe: the new file is validated by the caller +// before it is ever offered here, and this goroutine does the stop-then-start +// with nothing else touching the process. func (r *realityRunner) supervise() { defer close(r.exited) + // A reload waiting for its new child to come up. It is answered once the + // child is running, so the dashboard's reply means "xray is serving the new + // list", not "xray was asked to". + var answered *realityReload + delay := 5 * time.Second for { if r.isStopped() { @@ -656,25 +729,60 @@ func (r *realityRunner) supervise() { } w := &xrayLogWriter{logger: r.logger} - cmd := exec.Command(r.bin, "run", "-c", r.cfgFile) + cmd := exec.Command(r.bin, "run", "-c", r.configFile()) cmd.Stdout, cmd.Stderr = w, w if err := cmd.Start(); err != nil { r.logger.Error("reality: cannot start xray", "error", err) + if answered != nil { + answered.done <- fmt.Errorf("xray did not start: %w", err) + answered = nil + } } else { r.setCmd(cmd) - waitErr := cmd.Wait() - r.setCmd(nil) - if r.isStopped() { + if answered != nil { + r.waitReady() + answered.done <- nil + answered = nil + } + // Wait runs in its own goroutine so the loop can still act on a + // reload or a stop while the child is running. + exited := make(chan error, 1) + go func() { exited <- cmd.Wait() }() + + select { + case waitErr := <-exited: + r.setCmd(nil) + if r.isStopped() { + return + } + r.logger.Error("reality: xray exited, restarting", "error", waitErr) + case req := <-r.reload: + r.logger.Info("reality: reloading client list") + r.stopChild(exited) + r.swapConfig(req.cfgFile) + answered = &req + // A deliberate reload is not a crash: start the new child at + // once instead of serving the backoff first. + continue + case <-r.stop: + r.setCmd(nil) + r.stopChild(exited) return } - r.logger.Error("reality: xray exited, restarting", "error", waitErr) } select { case <-time.After(delay): case <-r.stop: return + case req := <-r.reload: + // No child is running here, so the reply waits for the next + // successful start. Claiming it is applied now would be a lie the + // dashboard would show as "live". + r.swapConfig(req.cfgFile) + answered = &req + continue } if delay < time.Minute { delay *= 2 @@ -685,6 +793,42 @@ func (r *realityRunner) supervise() { } } +// stopChild ends the running child and waits for the process to actually be +// gone, so the port is free before its replacement starts. +func (r *realityRunner) stopChild(exited chan error) { + r.mu.Lock() + cmd := r.cmd + r.mu.Unlock() + + if cmd == nil || cmd.Process == nil { + return + } + _ = cmd.Process.Signal(syscall.SIGTERM) + select { + case <-exited: + case <-time.After(5 * time.Second): + _ = cmd.Process.Kill() + <-exited + } +} + +// swapConfig installs a new config file and deletes the one it replaces. +func (r *realityRunner) swapConfig(next string) { + r.mu.Lock() + old := r.cfgFile + r.cfgFile = next + r.mu.Unlock() + if old != "" && old != next { + _ = os.Remove(old) + } +} + +func (r *realityRunner) configFile() string { + r.mu.Lock() + defer r.mu.Unlock() + return r.cfgFile +} + func (r *realityRunner) setCmd(cmd *exec.Cmd) { r.mu.Lock() r.cmd = cmd @@ -697,6 +841,34 @@ func (r *realityRunner) isStopped() bool { return r.stopped } +// Reload renders a new config and swaps it in. The config is validated by xray +// first, so an invalid change is refused and the running front door keeps +// serving; the previous file is removed only once the new one is accepted. +func (r *realityRunner) Reload(cfg Config, k realityKeys) error { + bin := cfg.RealityXrayBin + if bin == "" { + bin = r.bin + } + next, err := renderValidatedServerConfig(bin, cfg, k) + if err != nil { + return err + } + + req := realityReload{cfgFile: next, done: make(chan error, 1)} + select { + case r.reload <- req: + case <-time.After(10 * time.Second): + _ = os.Remove(next) + return errors.New("xray supervisor is not responding") + } + select { + case err := <-req.done: + return err + case <-time.After(15 * time.Second): + return errors.New("timed out waiting for xray to reload") + } +} + // Stop asks xray to exit, then removes the config holding the private key. func (r *realityRunner) Stop() { r.mu.Lock() @@ -722,23 +894,23 @@ func (r *realityRunner) Stop() { _ = cmd.Process.Kill() } } - _ = os.Remove(r.cfgFile) + _ = os.Remove(r.configFile()) } // ─── Wiring ───────────────────────────────────────────────────────────────── // startRealityForServer resolves keys, starts the child and writes the client // config operators copy to their own devices. -func startRealityForServer(cfg Config, persisted map[string]string, store *Store, logger *slog.Logger) (*realityRunner, error) { +func startRealityForServer(cfg Config, persisted map[string]string, store *Store, logger *slog.Logger) (*realityRunner, realityKeys, error) { if _, err := exec.LookPath(orDefault(cfg.RealityXrayBin, "xray")); err != nil { if _, statErr := os.Stat(orDefault(cfg.RealityXrayBin, "xray")); statErr != nil { - return nil, fmt.Errorf("reality_enabled is set but the xray binary is missing: set XRAY_BIN or install it (Docker images ship it at /usr/local/bin/xray)") + return nil, realityKeys{}, fmt.Errorf("reality_enabled is set but the xray binary is missing: set XRAY_BIN or install it (Docker images ship it at /usr/local/bin/xray)") } } keys, err := resolveRealityKeys(cfg, persisted, store, logger) if err != nil { - return nil, err + return nil, keys, err } if _, port, err := splitHostPort(cfg.RealityBind); err == nil && port == cfg.SinglePort && cfg.SinglePort != 0 { @@ -747,7 +919,7 @@ func startRealityForServer(cfg Config, persisted map[string]string, store *Store runner, err := startReality(cfg, keys, logger) if err != nil { - return nil, err + return nil, keys, err } address := cfg.RealityPublicHost @@ -777,7 +949,87 @@ func startRealityForServer(cfg Config, persisted map[string]string, store *Store "public_key", keys.PublicKey, "short_id", keys.ShortID, "client_id", strings.Join(keys.ClientIDs, ",")) - return runner, nil + return runner, keys, nil +} + +// ─── Live client-list management ─────────────────────────────────────────── + +// generateVlessUUID asks xray for an id, which is the same generator that +// produced the first one. It runs a subprocess because the binary is already a +// dependency of this feature and rolling our own UUID would be one more thing +// to get wrong. +func generateVlessUUID(bin string) (string, error) { + out, err := runXray(orDefault(bin, "xray"), "uuid") + if err != nil { + return "", err + } + fields := strings.Fields(out) + if len(fields) == 0 || !IsUUID(fields[0]) { + return "", fmt.Errorf("xray uuid returned %q", strings.TrimSpace(out)) + } + return fields[0], nil +} + +// realityManager returns the runner and keys when the dashboard is allowed to +// change the client list. +func (s *ProxyServer) realityManager() (*realityRunner, realityKeys, error) { + s.realityMu.Lock() + defer s.realityMu.Unlock() + + if s.reality == nil { + return nil, realityKeys{}, errors.New("REALITY is not enabled, so there is no xray client list to manage") + } + // REALITY_CLIENT_IDS pins the list from configuration, which outranks the + // database everywhere else in this program. Editing the table would then + // look like it worked and change nothing. + s.configMu.RLock() + pinned := len(s.cfg.RealityClientIDs) > 0 + s.configMu.RUnlock() + if pinned { + return nil, realityKeys{}, errors.New("REALITY_CLIENT_IDS is set, which pins the client list; unset it to manage clients here") + } + return s.reality, s.realityKeys, nil +} + +// requireRealityManager is the handler-side guard for the mutating routes. +func (s *ProxyServer) requireRealityManager(w http.ResponseWriter) error { + if _, _, err := s.realityManager(); err != nil { + http.Error(w, err.Error(), http.StatusConflict) + return err + } + return nil +} + +// applyVlessClients re-renders the xray config from the enabled rows and swaps +// it into the running child. The config is validated before xray is restarted, +// so a rejected change leaves the front door serving what it was serving. +func (s *ProxyServer) applyVlessClients() error { + runner, keys, err := s.realityManager() + if err != nil { + return err + } + s.realityMu.Lock() + keys.ClientIDs, err = s.store.EnabledVlessClientUUIDs() + s.realityMu.Unlock() + if err != nil { + return err + } + if len(keys.ClientIDs) == 0 { + return errors.New("this would leave xray with no clients, so the front door would refuse every connection; add one first") + } + + s.configMu.RLock() + cfg := s.cfg + s.configMu.RUnlock() + + if err := runner.Reload(cfg, keys); err != nil { + return err + } + s.realityMu.Lock() + s.realityKeys = keys + s.realityMu.Unlock() + s.logger.Info("reality client list applied", "clients", len(keys.ClientIDs)) + return nil } func orDefault(v, fallback string) string { diff --git a/reality_test.go b/reality_test.go index 506a50d..a77dce5 100644 --- a/reality_test.go +++ b/reality_test.go @@ -336,8 +336,13 @@ func TestResolveRealityKeysPersistsGeneratedValues(t *testing.T) { if saved[dbRealityShortID] != keys.ShortID { t.Errorf("short id not persisted: %v", saved) } - if saved[dbRealityClientIDs] != strings.Join(keys.ClientIDs, ",") { - t.Errorf("client ids not persisted: %v", saved) + // The uuid belongs in the managed table now, not in a comma-joined string. + clients, err := store.ListVlessClients() + if err != nil { + t.Fatalf("list clients: %v", err) + } + if len(clients) != 1 || clients[0].UUID != keys.ClientIDs[0] || !clients[0].Enabled { + t.Fatalf("generated uuid not stored as a managed client: %+v", clients) } // A restart must reuse the persisted pair rather than rotate it. @@ -348,6 +353,9 @@ func TestResolveRealityKeysPersistsGeneratedValues(t *testing.T) { if again.PrivateKey != keys.PrivateKey || again.ShortID != keys.ShortID { t.Errorf("restart rotated the key material: %q/%q", again.PrivateKey, again.ShortID) } + if len(again.ClientIDs) != 1 || again.ClientIDs[0] != keys.ClientIDs[0] { + t.Errorf("restart rotated the client id: %v, want %v", again.ClientIDs, keys.ClientIDs) + } } func TestResolveRealityKeysPrefersOperatorValues(t *testing.T) { @@ -383,7 +391,7 @@ func TestRealityRefusesWithoutXrayBinary(t *testing.T) { cfg.RealityEnabled = true cfg.RealityXrayBin = filepath.Join(t.TempDir(), "definitely-not-here") - _, err := startRealityForServer(cfg, nil, nil, slog.New(slog.NewTextHandler(io.Discard, nil))) + _, _, err := startRealityForServer(cfg, nil, nil, slog.New(slog.NewTextHandler(io.Discard, nil))) if err == nil { t.Fatal("starting REALITY without the xray binary should fail") } diff --git a/vless_test.go b/vless_test.go new file mode 100644 index 0000000..ebd4f02 --- /dev/null +++ b/vless_test.go @@ -0,0 +1,526 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "net/http/httptest" + "net/url" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// ─── Store ────────────────────────────────────────────────────────────────── + +func TestVlessClientCRUD(t *testing.T) { + store := newTestStore(t) + + const uuid = "0cd94710-7290-40da-857d-5f5a7670cd62" + client, err := store.CreateVlessClient(uuid, "alice's phone") + if err != nil { + t.Fatalf("create: %v", err) + } + if !client.Enabled || client.Label != "alice's phone" { + t.Errorf("created client = %+v, want enabled with its label", client) + } + + // The same UUID twice is an error, not a second row: two rows would make + // revocation ambiguous. + if _, err := store.CreateVlessClient(uuid, "impostor"); err == nil { + t.Error("the same uuid was accepted twice") + } + + if _, err := store.CreateVlessClient("not-a-uuid", ""); err == nil { + t.Error("a non-uuid was accepted") + } + + clients, err := store.ListVlessClients() + if err != nil || len(clients) != 1 { + t.Fatalf("list = %+v, %v", clients, err) + } + + disabled := false + if err := store.UpdateVlessClient(client.ID, nil, &disabled); err != nil { + t.Fatalf("disable: %v", err) + } + uuids, err := store.EnabledVlessClientUUIDs() + if err != nil { + t.Fatalf("enabled uuids: %v", err) + } + if len(uuids) != 0 { + t.Errorf("a disabled client is still offered to xray: %v", uuids) + } + + // A label-only edit must not silently re-enable it. + if err := store.UpdateVlessClient(client.ID, stringPtr("renamed"), nil); err != nil { + t.Fatalf("relabel: %v", err) + } + clients, _ = store.ListVlessClients() + if clients[0].Label != "renamed" || clients[0].Enabled { + t.Errorf("relabel changed more than the label: %+v", clients[0]) + } + + if err := store.DeleteVlessClient(client.ID); err != nil { + t.Fatalf("delete: %v", err) + } + if clients, _ := store.ListVlessClients(); len(clients) != 0 { + t.Errorf("delete left rows behind: %+v", clients) + } +} + +func stringPtr(v string) *string { return &v } + +// ─── Where the client list comes from ─────────────────────────────────────── + +func TestResolveRealityKeysUsesManagedClients(t *testing.T) { + bin := fakeXray(t, "private", "public") + store := newTestStore(t) + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + + cfg := DefaultConfig() + cfg.RealityXrayBin = bin + + // An id left behind by an earlier version, in the old comma-joined value. + // Upgrading must adopt it, not drop it: the table would otherwise shadow + // the config and revoke a client that is still in the field. + const legacyID = "11111111-2222-3333-4444-555555555555" + persisted := map[string]string{dbRealityClientIDs: legacyID} + + keys, err := resolveRealityKeys(cfg, persisted, store, log) + if err != nil { + t.Fatalf("resolve: %v", err) + } + if len(keys.ClientIDs) != 1 || keys.ClientIDs[0] != legacyID { + t.Fatalf("client ids = %v, want the legacy id adopted", keys.ClientIDs) + } + clients, _ := store.ListVlessClients() + if len(clients) != 1 || clients[0].Label != "migrated" { + t.Fatalf("legacy id was not adopted into the table: %+v", clients) + } + + // Adding a managed client adds to the list. The adopted id stays: upgrading + // and then adding someone must not quietly revoke the client that was + // already in the field. + const managedID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" + if _, err := store.CreateVlessClient(managedID, "new phone"); err != nil { + t.Fatalf("create managed: %v", err) + } + keys, err = resolveRealityKeys(cfg, persisted, store, log) + if err != nil { + t.Fatalf("resolve again: %v", err) + } + if len(keys.ClientIDs) != 2 { + t.Errorf("client ids = %v, want the adopted and the new client", keys.ClientIDs) + } + found := false + for _, id := range keys.ClientIDs { + if id == managedID { + found = true + } + } + if !found { + t.Errorf("the new client is missing from %v", keys.ClientIDs) + } + + // Disabling one leaves the other alone. + all, _ := store.ListVlessClients() + for _, c := range all { + if c.UUID == managedID { + off := false + if err := store.UpdateVlessClient(c.ID, nil, &off); err != nil { + t.Fatalf("disable: %v", err) + } + } + } + keys, err = resolveRealityKeys(cfg, persisted, store, log) + if err != nil { + t.Fatalf("resolve with one disabled: %v", err) + } + if len(keys.ClientIDs) != 1 || keys.ClientIDs[0] != legacyID { + t.Errorf("client ids = %v, want only the still-enabled one", keys.ClientIDs) + } + + // Configuration still outranks the table, as it does everywhere else. + cfg.RealityClientIDs = []string{legacyID} + keys, err = resolveRealityKeys(cfg, persisted, store, log) + if err != nil { + t.Fatalf("resolve with config: %v", err) + } + if len(keys.ClientIDs) != 1 || keys.ClientIDs[0] != legacyID { + t.Errorf("client ids = %v, want the configured id to win", keys.ClientIDs) + } +} + +// ─── The API ──────────────────────────────────────────────────────────────── + +// adminRequest drives the admin mux the way the dashboard does. +func adminRequest(t *testing.T, s *ProxyServer, method, path string, body string) *httptest.ResponseRecorder { + t.Helper() + var reader io.Reader + if body != "" { + reader = strings.NewReader(body) + } + req := httptest.NewRequest(method, path, reader) + req.RemoteAddr = "127.0.0.1:5000" + rec := httptest.NewRecorder() + s.adminHandler().ServeHTTP(rec, req) + return rec +} + +func TestVlessClientAPIRequiresReality(t *testing.T) { + cfg := DefaultConfig() + cfg.AdminPort = freePort(t) + cfg.AuthEnabled = false + s := NewProxyServer(cfg) + s.store = newTestStore(t) + + // Listing works without xray, so the dashboard can say why it is empty. + rec := adminRequest(t, s, http.MethodGet, "/api/vless-clients", "") + if rec.Code != http.StatusOK { + t.Fatalf("GET with REALITY off = %d, want 200: %s", rec.Code, rec.Body) + } + var listing struct { + Clients []VlessClient `json:"clients"` + RealityEnabled bool `json:"reality_enabled"` + ManagedByConfig bool `json:"managed_by_config"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &listing); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if listing.RealityEnabled { + t.Error("reality_enabled should be false when REALITY is off") + } + + // Mutating is refused rather than accepted-and-ignored. + for _, tc := range []struct{ method, path, body string }{ + {http.MethodPost, "/api/vless-clients", `{"label":"x"}`}, + {http.MethodPut, "/api/vless-clients/1", `{"enabled":false}`}, + {http.MethodDelete, "/api/vless-clients/1", ""}, + } { + rec := adminRequest(t, s, tc.method, tc.path, tc.body) + if rec.Code != http.StatusConflict { + t.Errorf("%s %s with REALITY off = %d, want 409: %s", tc.method, tc.path, rec.Code, rec.Body) + } + } +} + +func TestVlessClientAPIRejectsPinnedListAndLastRemoval(t *testing.T) { + bin := requireXray(t) + store := newTestStore(t) + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + + cfg := DefaultConfig() + cfg.RealityXrayBin = bin + cfg.RealityBind = fmt.Sprintf("127.0.0.1:%d", freePort(t)) + keys, err := resolveRealityKeys(cfg, nil, store, log) + if err != nil { + t.Fatalf("resolve: %v", err) + } + runner, err := startReality(cfg, keys, log) + if err != nil { + t.Fatalf("start reality: %v", err) + } + defer runner.Stop() + + s := NewProxyServer(cfg) + s.store = store + s.reality, s.realityKeys = runner, keys + + // resolveRealityKeys generated and stored one client, which is now the only + // one there is. + clients, err := store.ListVlessClients() + if err != nil || len(clients) != 1 { + t.Fatalf("expected exactly the generated client: %+v, %v", clients, err) + } + created := clients[0] + + // Removing the last client would leave xray with nobody to serve, which + // looks like a successful edit and breaks every client on the planet. + rec := adminRequest(t, s, http.MethodDelete, fmt.Sprintf("/api/vless-clients/%d", created.ID), "") + if rec.Code != http.StatusInternalServerError { + t.Fatalf("removing the last client = %d, want an error: %s", rec.Code, rec.Body) + } + if !strings.Contains(rec.Body.String(), "no clients") { + t.Errorf("error %q should explain that no client would be left", rec.Body) + } + if clients, _ := store.ListVlessClients(); len(clients) != 1 { + t.Fatalf("a refused removal still deleted the row: %+v", clients) + } + + // A pinned list is refused instead of silently doing nothing. + s.configMu.Lock() + s.cfg.RealityClientIDs = []string{keys.ClientIDs[0]} + s.configMu.Unlock() + rec = adminRequest(t, s, http.MethodPost, "/api/vless-clients", `{"label":"ignored"}`) + if rec.Code != http.StatusConflict { + t.Fatalf("POST with a pinned list = %d, want 409: %s", rec.Code, rec.Body) + } + if !strings.Contains(rec.Body.String(), "REALITY_CLIENT_IDS") { + t.Errorf("error %q should name the variable pinning the list", rec.Body) + } +} + +// ─── End to end ───────────────────────────────────────────────────────────── + +// TestRealityClientRevocationTakesEffect runs the whole loop: a UUID is revoked +// from the database, and a REALITY client still configured with it must stop +// working without the proxy being restarted. A management screen that does not +// revoke anything is worse than no management screen. +func TestRealityClientRevocationTakesEffect(t *testing.T) { + bin := requireXray(t) + store := newTestStore(t) + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + + // An origin the client will actually reach. + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, "revocation-e2e-ok") + })) + defer origin.Close() + + proxyCfg := DefaultConfig() + proxyCfg.AuthEnabled = false + proxyCfg.AdminEnabled = false + proxyCfg.SecurityHeadersEnabled = false + proxyCfg.RateLimitEnabled = false + proxyCfg.ProxyPort = freePort(t) + + realityPort := freePort(t) + cfg := proxyCfg + cfg.RealityXrayBin = bin + cfg.RealityEnabled = true + cfg.RealityBind = fmt.Sprintf("127.0.0.1:%d", realityPort) + cfg.RealityPublicHost = "127.0.0.1" + + // One config for the server and the runner: the reload re-renders from + // server.cfg, exactly as runServer does. + server := NewProxyServer(cfg) + ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", proxyCfg.ProxyPort)) + if err != nil { + t.Fatalf("listen socks: %v", err) + } + defer ln.Close() + go func() { + for { + conn, aerr := ln.Accept() + if aerr != nil { + return + } + go server.handleClient(conn, "") + } + }() + + const revokedID = "0cd94710-7290-40da-857d-5f5a7670cd62" + const keptID = "0cd94710-7290-40da-857d-5f5a7670cd63" + for _, id := range []string{revokedID, keptID} { + if _, err := store.CreateVlessClient(id, "test client"); err != nil { + t.Fatalf("seed client %s: %v", id, err) + } + } + + keys, err := resolveRealityKeys(cfg, nil, store, log) + if err != nil { + t.Fatalf("resolve keys: %v", err) + } + if len(keys.ClientIDs) != 2 { + t.Fatalf("client ids = %v, want both managed clients", keys.ClientIDs) + } + + runner, err := startReality(cfg, keys, log) + if err != nil { + t.Fatalf("start reality: %v", err) + } + defer runner.Stop() + + server.store = store + server.reality, server.realityKeys = runner, keys + + // A REALITY client whose config still carries the id about to be revoked. + staleClient := startRealityTestClient(t, bin, cfg, keys, revokedID, freePort(t)) + liveClient := startRealityTestClient(t, bin, cfg, keys, keptID, freePort(t)) + + fetch := func(clientPort int) error { + u, err := url.Parse(fmt.Sprintf("socks5://127.0.0.1:%d", clientPort)) + if err != nil { + return err + } + httpClient := &http.Client{ + Transport: &http.Transport{Proxy: http.ProxyURL(u)}, + Timeout: 25 * time.Second, + } + resp, err := httpClient.Get(origin.URL) + if err != nil { + return err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return err + } + if string(body) != "revocation-e2e-ok" { + return fmt.Errorf("body = %q", body) + } + return nil + } + + // Both work before the change. + if err := fetch(staleClient); err != nil { + t.Fatalf("the client that is about to be revoked should work now: %v", err) + } + if err := fetch(liveClient); err != nil { + t.Fatalf("the client that stays should work now: %v", err) + } + + // Revoke through the same path the dashboard uses. + rec := adminRequest(t, server, http.MethodDelete, fmt.Sprintf("/api/vless-clients/%d", idOfUUID(t, store, revokedID)), "") + if rec.Code != http.StatusOK { + t.Fatalf("revoke = %d: %s", rec.Code, rec.Body) + } + + // No restart, no waiting: the revoked UUID must already be refused. + if err := fetch(staleClient); err == nil { + t.Error("a revoked uuid still works; the dashboard change did not reach xray") + } + // The other client is untouched. + if err := fetch(liveClient); err != nil { + t.Errorf("revoking one client broke another: %v", err) + } +} + +// startRealityTestClient runs a second xray as the client and returns the port +// of its local SOCKS5 inbound. +func startRealityTestClient(t *testing.T, bin string, cfg Config, keys realityKeys, uuid string, clientPort int) int { + t.Helper() + + clientKeys := keys + clientKeys.ClientIDs = []string{uuid} + data, err := renderRealityClientConfig(cfg.RealityPublicHost, portOf(t, cfg.RealityBind), "127.0.0.1", clientPort, clientKeys) + if err != nil { + t.Fatalf("render client: %v", err) + } + file := filepath.Join(t.TempDir(), "client.json") + if err := os.WriteFile(file, data, 0o600); err != nil { + t.Fatalf("write client config: %v", err) + } + + cmd := exec.Command(bin, "run", "-c", file) + // The client's own log is the only place a refusal shows up, and a silent + // skip here would look like a flaky proxy rather than a rejected UUID. + cmd.Stdout, cmd.Stderr = &testWriter{t: t, tag: "client"}, &testWriter{t: t, tag: "client"} + if err := cmd.Start(); err != nil { + t.Fatalf("start client xray: %v", err) + } + t.Cleanup(func() { + cmd.Process.Kill() + cmd.Wait() + }) + + deadline := time.Now().Add(15 * time.Second) + for { + conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", clientPort), 200*time.Millisecond) + if err == nil { + conn.Close() + return clientPort + } + if time.Now().After(deadline) { + t.Fatalf("client socks port %d never opened: %v", clientPort, err) + } + time.Sleep(100 * time.Millisecond) + } +} + +// testWriter routes a subprocess log into the test output. +type testWriter struct { + t *testing.T + tag string + buf string +} + +func (w *testWriter) Write(p []byte) (int, error) { + w.buf += string(p) + for { + i := strings.IndexByte(w.buf, '\n') + if i < 0 { + break + } + w.t.Logf("[%s] %s", w.tag, w.buf[:i]) + w.buf = w.buf[i+1:] + } + return len(p), nil +} + +func portOf(t *testing.T, addr string) int { + t.Helper() + _, port, err := splitHostPort(addr) + if err != nil { + t.Fatalf("split %q: %v", addr, err) + } + return port +} + +func idOfUUID(t *testing.T, store *Store, uuid string) int64 { + t.Helper() + clients, err := store.ListVlessClients() + if err != nil { + t.Fatalf("list clients: %v", err) + } + for _, c := range clients { + if c.UUID == uuid { + return c.ID + } + } + t.Fatalf("no managed client with uuid %s", uuid) + return 0 +} + +// The dashboard is one HTML file with inline script, so the cheapest honest +// check is that the panel is wired to the endpoints this build serves. +func TestDashboardVlessPanelWiring(t *testing.T) { + data, err := os.ReadFile("web/index.html") + if err != nil { + t.Fatalf("read dashboard: %v", err) + } + html := string(data) + + for _, id := range []string{"vless-body", "v-label", "v-uuid", "vless-msg"} { + if !strings.Contains(html, `id="`+id+`"`) { + t.Errorf("dashboard has no element with id %q", id) + } + } + for _, fn := range []string{"loadVlessClients", "createVlessClient", "toggleVlessClient", "deleteVlessClient"} { + if !strings.Contains(html, "function "+fn+"(") { + t.Errorf("dashboard has no %s function", fn) + } + } + if !strings.Contains(html, "/api/vless-clients") { + t.Error("dashboard never talks to /api/vless-clients") + } + // Defined is not wired: the list has to load on startup. + if !strings.Contains(html, "\nloadVlessClients();") { + t.Error("loadVlessClients() is not called on startup") + } + + cfg := DefaultConfig() + cfg.AuthEnabled = false + s := NewProxyServer(cfg) + s.store = newTestStore(t) + rec := adminRequest(t, s, http.MethodGet, "/api/vless-clients", "") + if rec.Code != http.StatusOK { + t.Fatalf("GET /api/vless-clients = %d", rec.Code) + } + var listing struct { + Clients []VlessClient `json:"clients"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &listing); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if listing.Clients == nil { + t.Error("clients must serialise as [], not null, so the panel can loop over it") + } +} diff --git a/web/index.html b/web/index.html index 2b983d3..eb1018c 100644 --- a/web/index.html +++ b/web/index.html @@ -155,6 +155,7 @@ .theme-toggle:hover{color:var(--accent);border-color:var(--accent);box-shadow:0 0 10px var(--shadow)} .theme-toggle:focus-visible{outline:2px solid var(--accent);outline-offset:2px} .actions{display:flex;gap:5px;flex-wrap:wrap} + .uuid{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px} .form-box{background:var(--bg-elevated);border:1px solid var(--border);box-shadow:0 1px 2px var(--shadow);border-radius:12px;padding:20px;position:relative;overflow:hidden} .form-box::before{content:'';position:absolute;top:0;left:0;right:0;height:2px;background:linear-gradient(90deg,transparent,var(--accent),transparent)} .form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:15px} @@ -259,6 +260,46 @@

User Management

+
+

REALITY Clients (VLESS UUIDs)

+
+
+

+ Each UUID is one client allowed through the REALITY front door. Changes are + applied to xray immediately: a deleted or disabled UUID stops working + within a second, with no restart. +

+
+
+ + +
+
+ + +
+
+ +
+ +
+ + + + + + + + + + + + + +
IDLabelUUIDStatusActions
Loading...
+
+
+

Settings

@@ -537,10 +578,113 @@

Settings

}catch(e){msg.textContent='Network error: '+e.message;msg.className='msg msg-err';msg.style.display='block'} } +function el(tag,text){var e=document.createElement(tag);if(text!==undefined)e.textContent=text;return e} + +async function loadVlessClients(){ + var msg=document.getElementById('vless-msg'); + var tbody=document.getElementById('vless-body'); + try{ + var r=await fetch('/api/vless-clients',{credentials:'same-origin'}); + var data=await r.json(); + if(!data.reality_enabled){ + tbody.innerHTML=''; + var row=el('tr'),cell=el('td',''); + cell.colSpan=5; + cell.style.color='#555'; + cell.textContent='REALITY is not enabled, so there is no client list to manage.'; + row.appendChild(cell);tbody.appendChild(row); + document.querySelector('#v-label').disabled=true; + document.querySelector('#v-uuid').disabled=true; + return; + } + if(data.managed_by_config){ + msg.textContent='REALITY_CLIENT_IDS is set, which pins the list. Unset it to manage clients here.'; + msg.className='msg msg-err';msg.style.display='block'; + } + tbody.innerHTML=''; + if(!data.clients||data.clients.length===0){ + var empty=el('tr'),ecell=el('td','No clients. Add one above.'); + ecell.colSpan=5;ecell.style.color='#555'; + empty.appendChild(ecell);tbody.appendChild(empty); + return; + } + for(var i=0;i Date: Sat, 17 Oct 2026 18:57:49 +0500 Subject: [PATCH 2/2] Store passwords as hashes, and upgrade old rows on login users.password_hash held the password verbatim, so any copy of the database -- a backup, a stray file, a support attachment -- was a list of working credentials, for the service and for whatever else those people reuse the same password on. PBKDF2-HMAC-SHA256 at 600k iterations, which is the OWASP figure for that pair, from the standard library. No new dependency for the one thing in a proxy that must not be improvised, and the cost is paid per login attempt on an endpoint that already rate-limits guesses. The parameters are recorded in each stored hash rather than assumed at verify time, so they can be raised later without invalidating what is on disk. That also means the stored value chooses the cost, so parsing refuses anything implausible instead of letting a corrupt or hostile record turn one login into a memory-exhaustion attack. Existing installs need no migration: a row from before hashing is verified against the value it holds, and rewritten on the next successful login. An install cleans itself up one account at a time. PROXY_USER/PROXY_PASS and the admin pair are untouched -- they come from the environment, not the database, so there is nothing to hash and the file is already a secret the operator controls. Verified against a running server: a user created through the API lands in the file as pbkdf2-sha256$iter=600000$..., the plaintext is absent from the database bytes, the correct password authenticates and a wrong one does not, a seeded pre-hashing row logs in and is rewritten on the spot, and a backup of the result contains neither the old nor the new plaintext -- VACUUM INTO leaves no stale copies behind, though the live WAL keeps the old value until it is checkpointed. --- README.md | 25 ++++-- database.go | 27 +++++- main.go | 14 ++- password.go | 107 +++++++++++++++++++++++ password_test.go | 215 +++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 379 insertions(+), 9 deletions(-) create mode 100644 password.go create mode 100644 password_test.go diff --git a/README.md b/README.md index 2d45693..44cb2f3 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Deploys on any PaaS, including the ones that expose only a single HTTP endpoint. - **User Management** - Create, update, delete users with tier-based limits - **Tier System** - Free, Basic, Pro, and Unlimited tiers with connection/data/bandwidth limits - **Rate Limiting** - Token-bucket rate limiting with configurable RPS +- **Hashed Passwords** - PBKDF2-HMAC-SHA256 in the database; a stolen file is not a list of credentials - **Message Padding** - Optional uniform-size framing so a 2-byte SOCKS5 reply is indistinguishable from bulk traffic - **Security Headers** - CSP, XSS protection, frame options, and more - **Admin Dashboard** - Full management UI with charts and user CRUD @@ -448,8 +449,8 @@ Client flags: `-url` (required; `https://` is accepted and mapped to `wss://`, a # Take a backup. Works while the server is running. socks5-proxy backup -out socks5-20261017.tar.gz -# Encrypt it. A backup contains every user password and, with REALITY enabled, -# the private key -- so encryption is worth the passphrase. +# Encrypt it. A backup holds password hashes and, with REALITY enabled, the +# private key -- so encryption is worth the passphrase. socks5-proxy backup -out socks5-20261017.tar.gz -passphrase 'a good passphrase' # Look inside without restoring anything. @@ -526,9 +527,19 @@ go test -run TestRealityEndToEnd -v ./... # needs xray on PATH on shutdown. Its own log lines are relayed into this server's log. - `whitelist` and `blacklist` apply to the SOCKS5 port, the HTTP proxy (`CONNECT` and forward) and the tunnel alike. -- A backup contains every user password in the clear, plus the REALITY private - key when it is enabled. Use `-passphrase` for anything that leaves the machine, - and keep the passphrase somewhere other than the backup directory. +- User passwords are stored as **PBKDF2-HMAC-SHA256 hashes** (600k iterations, + per-user salt), never as text, so a database file or a backup does not hand + over working credentials. Accounts created before hashing existed keep + working: their password is verified against the old value and the row is + rewritten on the next successful login, so an install upgrades itself one + account at a time with no migration to run. +- `PROXY_USER`/`PROXY_PASS` and `ADMIN_USER`/`ADMIN_PASS` come from the + environment or config file and stay as they are — there is nothing in the + database to hash, and the file is already a secret you control. +- A backup contains password **hashes**, not passwords, plus the REALITY private + key when it is enabled. The key is the reason to use `-passphrase` for + anything that leaves the machine; keep the passphrase somewhere other than the + backup directory. - `/health` is the only endpoint reachable without admin credentials, and it returns `{"status":"ok"}` with no uptime or version: on a public port it is the one thing a scanner can read, so it says nothing. `/metrics`, @@ -600,6 +611,10 @@ at `/prometheus` with `basic_auth` configured. | PUT | `/api/users/:id` | Update user | | DELETE | `/api/users/:id` | Delete user | | POST | `/api/users/:id/reset` | Reset a user's data usage | +| GET | `/api/vless-clients` | REALITY client UUIDs, and whether they can be managed | +| POST | `/api/vless-clients` | Add a client; the UUID is generated if omitted | +| PUT | `/api/vless-clients/:id` | Relabel, or enable/disable, a client | +| DELETE | `/api/vless-clients/:id` | Revoke a client, effective immediately | | GET | `/api/top-destinations?n=10` | Most-visited destinations | | GET | `/api/history/stats?n=60` | Historical connection/byte counters | | GET | `/api/history/destinations` | Destination history | diff --git a/database.go b/database.go index ec18546..9c89337 100644 --- a/database.go +++ b/database.go @@ -416,6 +416,14 @@ func (s *Store) CreateUser(username, password, tier string) (*User, error) { return nil, fmt.Errorf("unknown tier: %s", tier) } + // Hash before the row exists, so no code path can write a plaintext + // password by accident. The caller keeps the plaintext it passed in and is + // the one that may show it once. + hashed, err := HashPassword(password) + if err != nil { + return nil, err + } + var expiry *string if t.DaysExpiry > 0 { e := time.Now().AddDate(0, 0, t.DaysExpiry).Format("2006-01-02 15:04:05") @@ -428,7 +436,7 @@ func (s *Store) CreateUser(username, password, tier string) (*User, error) { result, err := s.db.Exec( `INSERT INTO users (username, password_hash, tier, max_connections, bandwidth_mbps, data_limit_bytes, expiry) VALUES (?, ?, ?, ?, ?, ?, ?)`, - username, password, tier, t.MaxConnections, t.BandwidthMbps, t.DataLimitBytes, expiry, + username, hashed, tier, t.MaxConnections, t.BandwidthMbps, t.DataLimitBytes, expiry, ) if err != nil { return nil, fmt.Errorf("insert user: %w", err) @@ -537,7 +545,11 @@ func (s *Store) UpdateUser(id int64, tier *string, password *string, enabled *bo } } if password != nil { - _, err := s.db.Exec("UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?", *password, id) + hashed, err := HashPassword(*password) + if err != nil { + return err + } + _, err = s.db.Exec("UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?", hashed, id) if err != nil { return err } @@ -580,6 +592,17 @@ func (s *Store) DeleteUser(id int64) error { return tx.Commit() } +// UpgradeUserPassword rewrites a row that still holds a pre-hashing password. +// It is called after a successful login, so an install cleans itself up one +// account at a time instead of needing a migration over every credential. +func (s *Store) UpgradeUserPassword(id int64, hash string) error { + s.mu.Lock() + defer s.mu.Unlock() + + _, err := s.db.Exec("UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?", hash, id) + return err +} + func (s *Store) ResetUserData(id int64) error { s.mu.Lock() defer s.mu.Unlock() diff --git a/main.go b/main.go index 36f7f73..5205b2f 100644 --- a/main.go +++ b/main.go @@ -889,8 +889,18 @@ func (s *ProxyServer) authenticateUser(conn net.Conn, cfg *Config) (*User, error return nil, fmt.Errorf("user %s is disabled", string(username)) } - // Constant-time password comparison - if subtle.ConstantTimeCompare(password, []byte(user.PasswordHash)) == 1 { + if ok, legacy := VerifyPassword(user.PasswordHash, string(password)); ok { + // A row from before hashing matched in the clear. Rewrite it now + // that the password has been proven, so the install tidies + // itself up one login at a time. + if legacy { + if hash, herr := HashPassword(string(password)); herr == nil { + if uerr := s.store.UpgradeUserPassword(user.ID, hash); uerr != nil { + s.logger.Warn("could not upgrade a stored password hash", + "user", user.Username, "error", uerr) + } + } + } if _, err := conn.Write([]byte{socksAuthVersion, authStatusSuccess}); err != nil { return nil, fmt.Errorf("write auth success: %w", err) } diff --git a/password.go b/password.go new file mode 100644 index 0000000..993a32e --- /dev/null +++ b/password.go @@ -0,0 +1,107 @@ +package main + +import ( + "crypto/pbkdf2" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "fmt" + "strings" +) + +// ─── Password hashing ────────────────────────────────────────────────────── +// +// The users table used to hold passwords verbatim, which turns any copy of the +// database -- a stolen backup, a stray file, a support ticket attachment -- into +// a list of working credentials, for every deployment that shares one. Those +// are also the passwords operators reuse elsewhere. +// +// PBKDF2-HMAC-SHA256 at 600k iterations, which is the OWASP figure for that +// combination, from the standard library: no new dependency for the one thing +// in a proxy that must not be improvised. It costs about 0.3s per login here, +// which is a feature on an endpoint that accepts password guesses. +// +// The parameters are recorded in every stored hash rather than assumed at +// verify time, so they can be raised later without invalidating what is +// already on disk: each hash keeps verifying at its own cost, and a successful +// login can rewrite it at the new one. +const ( + pbkdf2Iterations = 600_000 + pbkdf2SaltLen = 16 + pbkdf2KeyLen = 32 + + // passwordScheme tags the stored value, so a future scheme is + // distinguishable from this one rather than being guessed at. + passwordScheme = "pbkdf2-sha256" +) + +// HashPassword returns a self-describing PBKDF2 hash. The password itself is +// not retained anywhere. +func HashPassword(plain string) (string, error) { + if plain == "" { + return "", fmt.Errorf("refusing to hash an empty password") + } + salt := make([]byte, pbkdf2SaltLen) + if _, err := rand.Read(salt); err != nil { + return "", fmt.Errorf("generate salt: %w", err) + } + key, err := pbkdf2.Key(sha256.New, plain, salt, pbkdf2Iterations, pbkdf2KeyLen) + if err != nil { + return "", fmt.Errorf("hash password: %w", err) + } + return fmt.Sprintf("%s$iter=%d$%s$%s", + passwordScheme, pbkdf2Iterations, + base64.RawStdEncoding.EncodeToString(salt), + base64.RawStdEncoding.EncodeToString(key)), nil +} + +// VerifyPassword reports whether plain matches the stored value. +// +// legacy is true when the stored value predates hashing, meaning it matched +// because it was the password in the clear. The caller uses that to rewrite the +// row, so an install upgrades one account per login instead of needing a +// migration that has to touch every credential at once. +func VerifyPassword(stored, plain string) (ok bool, legacy bool) { + if stored == "" || plain == "" { + return false, false + } + if !strings.HasPrefix(stored, passwordScheme+"$") { + // Pre-hashing value: the stored text was the password itself. + return subtle.ConstantTimeCompare([]byte(stored), []byte(plain)) == 1, true + } + iter, salt, key, ok := parseHashedPassword(stored) + if !ok { + return false, false + } + got, err := pbkdf2.Key(sha256.New, plain, salt, iter, len(key)) + if err != nil { + return false, false + } + return subtle.ConstantTimeCompare(got, key) == 1, false +} + +func parseHashedPassword(stored string) (iter int, salt, key []byte, ok bool) { + // scheme$iter=..$salt$key + parts := strings.Split(stored, "$") + if len(parts) != 4 || parts[0] != passwordScheme { + return 0, nil, nil, false + } + if _, err := fmt.Sscanf(parts[1], "iter=%d", &iter); err != nil { + return 0, nil, nil, false + } + // The stored value chooses the cost, so a corrupt or hostile record must + // not be able to turn one login into a denial of service. + if iter < 1 || iter > 10_000_000 { + return 0, nil, nil, false + } + salt, err := base64.RawStdEncoding.DecodeString(parts[2]) + if err != nil || len(salt) < 8 { + return 0, nil, nil, false + } + key, err = base64.RawStdEncoding.DecodeString(parts[3]) + if err != nil || len(key) < 16 { + return 0, nil, nil, false + } + return iter, salt, key, true +} diff --git a/password_test.go b/password_test.go new file mode 100644 index 0000000..ba3b855 --- /dev/null +++ b/password_test.go @@ -0,0 +1,215 @@ +package main + +import ( + "fmt" + "net" + "strings" + "testing" + "time" +) + +func TestHashPasswordRoundTrip(t *testing.T) { + const secret = "correct horse battery staple" + + hash, err := HashPassword(secret) + if err != nil { + t.Fatalf("hash: %v", err) + } + if strings.Contains(hash, secret) { + t.Fatal("the hash contains the password") + } + if !strings.HasPrefix(hash, passwordScheme+"$") { + t.Errorf("hash %q does not name its scheme and parameters", hash) + } + if !strings.Contains(hash, "iter=600000") { + t.Errorf("hash %q does not record its cost", hash) + } + + if ok, legacy := VerifyPassword(hash, secret); !ok || legacy { + t.Errorf("verify(correct) = %v, legacy=%v; want true, false", ok, legacy) + } + if ok, _ := VerifyPassword(hash, "wrong password"); ok { + t.Error("a wrong password verified") + } + if ok, _ := VerifyPassword(hash, ""); ok { + t.Error("an empty password verified") + } + + // Two hashes of the same password must differ, or the salt is not doing + // its job and one rainbow table would open every account. + other, err := HashPassword(secret) + if err != nil { + t.Fatalf("hash again: %v", err) + } + if other == hash { + t.Error("hashing is deterministic; the salt is not being applied") + } + if ok, _ := VerifyPassword(other, secret); !ok { + t.Error("a hash made with a different salt did not verify") + } + + if _, err := HashPassword(""); err == nil { + t.Error("an empty password was hashed") + } +} + +// A password stored before hashing existed must keep working, and must be +// reported as legacy so the caller can upgrade it. +func TestVerifyPasswordAcceptsLegacyPlaintext(t *testing.T) { + if ok, legacy := VerifyPassword("oldpassword", "oldpassword"); !ok || !legacy { + t.Errorf("legacy verify = %v, legacy=%v; want true, true", ok, legacy) + } + if ok, legacy := VerifyPassword("oldpassword", "guess"); ok || !legacy { + t.Errorf("wrong password against a legacy row = %v, legacy=%v; want false, true", ok, legacy) + } + // An empty stored value must never verify, whatever is offered. + if ok, _ := VerifyPassword("", ""); ok { + t.Error("an empty stored password verified against an empty offer") + } +} + +// A corrupt or hostile record must be refused rather than believed. The stored +// value chooses the iteration count, so an absurd one would turn a login into a +// denial of service. +func TestVerifyPasswordRejectsCorruptHashes(t *testing.T) { + good, err := HashPassword("secret") + if err != nil { + t.Fatalf("hash: %v", err) + } + parts := strings.Split(good, "$") + + for _, bad := range []string{ + "", + "pbkdf2-sha256", + "pbkdf2-sha256$", + "pbkdf2-sha256$iter=0$" + parts[2] + "$" + parts[3], + "pbkdf2-sha256$iter=99999999$" + parts[2] + "$" + parts[3], + "pbkdf2-sha256$iter=" + parts[2] + "$" + parts[3], + "pbkdf2-sha256$iter=600000$!!!$" + parts[3], + "pbkdf2-sha256$iter=600000$" + parts[2] + "$", + "pbkdf2-sha512$iter=600000$" + parts[2] + "$" + parts[3], + "scrypt$N=32768,r=8,p=1$" + parts[2] + "$" + parts[3], + parts[0] + "$iter=600000$" + parts[2] + "$" + parts[3] + "$extra", + } { + if ok, legacy := VerifyPassword(bad, "secret"); ok { + t.Errorf("corrupt hash %q verified (legacy=%v)", bad, legacy) + } + } +} + +// The point of the whole change: what lands in the database is not the password. +func TestStoredPasswordIsNotThePassword(t *testing.T) { + store := newTestStore(t) + + user, err := store.CreateUser("alice", "swordfish-123", "pro") + if err != nil { + t.Fatalf("create user: %v", err) + } + stored, err := store.GetUser(user.Username) + if err != nil { + t.Fatalf("get user: %v", err) + } + if strings.Contains(stored.PasswordHash, "swordfish-123") { + t.Fatal("the password is stored in the clear") + } + if ok, legacy := VerifyPassword(stored.PasswordHash, "swordfish-123"); !ok || legacy { + t.Errorf("the stored hash does not verify: ok=%v legacy=%v", ok, legacy) + } + + // Changing a password through the admin path must hash as well. + newPass := "a different one" + if err := store.UpdateUser(user.ID, nil, &newPass, nil); err != nil { + t.Fatalf("update password: %v", err) + } + stored, _ = store.GetUser(user.Username) + if strings.Contains(stored.PasswordHash, newPass) { + t.Fatal("the new password is stored in the clear") + } + if ok, _ := VerifyPassword(stored.PasswordHash, newPass); !ok { + t.Error("the new password does not verify against its stored hash") + } + if ok, _ := VerifyPassword(stored.PasswordHash, "swordfish-123"); ok { + t.Error("the old password still verifies after a change") + } +} + +// A row written before hashing existed authenticates, and is rewritten on the +// way through -- which is how an existing install cleans itself up without a +// migration that has to touch every credential at once. +func TestLoginUpgradesLegacyPasswordRow(t *testing.T) { + store := newTestStore(t) + + user, err := store.CreateUser("legacy", "still-works", "basic") + if err != nil { + t.Fatalf("create user: %v", err) + } + // Put the row back the way an older release would have left it. + store.mu.Lock() + _, err = store.db.Exec("UPDATE users SET password_hash=? WHERE id=?", "still-works", user.ID) + store.mu.Unlock() + if err != nil { + t.Fatalf("seed legacy row: %v", err) + } + + cfg := DefaultConfig() + cfg.AuthEnabled = true + cfg.AdminEnabled = false + cfg.SecurityHeadersEnabled = false + cfg.RateLimitEnabled = false + cfg.ProxyPort = freePort(t) + // Credentials that are not the user's, so success can only come from the + // database path. + cfg.Username = "nobody" + cfg.Password = "nothing" + + s := NewProxyServer(cfg) + s.store = store + + ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", cfg.ProxyPort)) + if err != nil { + t.Fatalf("listen: %v", err) + } + defer ln.Close() + go func() { + for { + conn, aerr := ln.Accept() + if aerr != nil { + return + } + go s.handleClient(conn, "") + } + }() + + conn, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(30 * time.Second)) + + if err := socks5ConnectAndAuth(t, conn, "legacy", "still-works", "example.com", 80); err != nil { + t.Fatalf("a pre-hashing password no longer authenticates: %v", err) + } + + stored, err := store.GetUser("legacy") + if err != nil { + t.Fatalf("get user: %v", err) + } + if stored.PasswordHash == "still-works" { + t.Fatal("the row still holds the password in the clear after a successful login") + } + if ok, legacy := VerifyPassword(stored.PasswordHash, "still-works"); !ok || legacy { + t.Errorf("upgraded row does not verify: ok=%v legacy=%v", ok, legacy) + } + + // And the upgraded row still authenticates on the next connection. + conn2, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatalf("dial again: %v", err) + } + defer conn2.Close() + conn2.SetDeadline(time.Now().Add(30 * time.Second)) + if err := socks5ConnectAndAuth(t, conn2, "legacy", "still-works", "example.com", 80); err != nil { + t.Fatalf("the upgraded row no longer authenticates: %v", err) + } +}