Skip to content

Add backup/restore, and fix database pragmas that were never applied - #8

Merged
GlobalTechInfo merged 3 commits into
mainfrom
feat/backup-restore
Oct 17, 2026
Merged

GlobalTechInfo merged 3 commits into
mainfrom
feat/backup-restore

Conversation

@GlobalTechInfo

@GlobalTechInfo GlobalTechInfo commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

Two things: a backup/restore feature, and a bug it found while being written that matters more than the feature.

The bug: no database pragma was ever applied

The connection string used the mattn/go-sqlite3 spelling with modernc.org/sqlite as the driver. That driver wants _pragma=name(value) and silently drops what it does not recognise. Measured on both spellings:

Pragma Was Intended
journal_mode delete wal
busy_timeout 0 5000
foreign_keys 0 on
synchronous 2 (FULL) 1 (NORMAL)

So the code, the comments and this README have claimed a WAL database for the life of the project, and it has never been one. In practice: readers block the writer, a concurrent write returns SQLITE_BUSY immediately instead of waiting 5s, the user_connections foreign key is unenforced so orphans accumulate silently, and every commit pays an fsync that synchronous=NORMAL was meant to avoid.

Turning the foreign key on would have broken the dashboard's delete-user button for anyone with connection history — the child rows reference the parent. DeleteUser now removes the dependent rows first, in one transaction. There is a regression test for exactly that.

The feature

socks5-proxy backup  -out FILE [-passphrase P]
socks5-proxy restore -in FILE [-list] [-force]

The snapshot uses VACUUM INTO, never a file copy. In WAL mode the newest commits live in the -wal sidecar, so reading socks5.db can produce a backup that restores cleanly and has quietly lost data. A test writes without checkpointing, asserts the WAL sidecar is non-empty, and then proves the restored database contains that row.

With -passphrase: AES-256-GCM under PBKDF2-SHA256, fresh salt and nonce per backup. A wrong passphrase fails on the GCM tag — authentication, not a checksum discovered three steps later — and nothing is written.

restore is built to be safe to run badly:

  • refuses while the server is running, via a pid file written at startup (a pid from a crash doesn't count; -force overrides)
  • decrypts and verifies every member against the manifest checksum before writing anything, so a failure cannot half-restore
  • restores only the exact member names this tool writes, so an archive naming ../something cannot write outside the data directory
  • keeps the existing database as socks5.db.pre-restore-<timestamp>

A hazard the tests hit for real

SQLite does its close-time WAL cleanup by path. A test helper still holding the old file, after a restore installed a new database at the same path, rewrote the new file on close — which is exactly what an operator would suffer restoring over a live server. It is why the pid check exists, and why the helpers close before returning.

Verified live, not just by unit test

  • Backup taken while the proxy was serving (online snapshot)
  • Database deleted → restored → restarted → the pre-backup user account authenticates
  • Restore over the running server → refused with the pid and the remedy
  • Wrong passphrase → refused, nothing changed
  • Encrypted archive → no plaintext credentials inside it

17 new tests; full suite green with and without xray; gofmt and go vet clean.

One operational note

A backup contains every user password in the clear and, with REALITY enabled, the private key. Use -passphrase for anything that leaves the machine, and keep that passphrase somewhere other than the backup directory — the docs say so.

Summary by CodeRabbit

  • New Features

    • Added commands to create, inspect, and restore server backups, with optional encryption and safeguards against restoring while the server is running.
    • Added per-client-IP rate limiting and bandwidth enforcement for user connections, with a brief burst allowance.
    • Environment-provided settings now take precedence over saved settings.
  • Documentation

    • Expanded guidance on backup security, restore precautions, IPv6-only configuration, rate limits, and bandwidth tiers.
  • Bug Fixes

    • Improved user deletion so associated connection history is removed consistently.

Three things the README has been claiming since the tier system landed, and
which no test caught because nobody checked the claims against the code:

1. "RATE_LIMIT_RPS: admin requests per second per client". There was one
   token bucket for the whole process. One noisy client spent everyone's
   budget: two administrators sharing a dashboard, or a dozen phones behind
   one carrier NAT, could throttle each other. rateLimiterSet now keys
   buckets by client IP and sweeps idle ones so memory stays bounded, with a
   hard ceiling that drops the least recently used half if a flood of
   distinct addresses outruns the sweep.

   The same bucket guarded the tunnel, the CONNECT path and the forward
   path, so all three gained per-client limits too. The tunnel handler now
   resolves the client IP before it refuses anything, because a refusal must
   not depend on reaching the line that needs the key.

2. "Bandwidth 1 / 5 / 50 Mbps" per tier. BandwidthMbps has been stored in
   SQLite since the beginning and read exactly never: relay() was a plain
   io.Copy in both directions, so the Free tier ran at line speed like every
   other tier. pacer.go is the token bucket that finally reads it, one per
   direction, with a one-second burst so short transfers are not punished.
   A nil pacer is the Unlimited tier and costs nothing to check.

   The first implementation credited the sleeping interval as idle time,
   which paid each debt twice and ran the link at twice the configured rate.
   The test asserting 256 KiB at 1 Mbps takes at least 900ms is what caught it.

3. Configuration precedence. Resolution was defaults < config.json <
   environment < database, so editing PROXY_PASS in .env did nothing on any
   install where somebody had ever saved settings in the dashboard -- and
   since .env is the documented way to configure the service, the natural
   conclusion was that the deployment ignored you. LoadConfig now records
   which variables were explicitly set and applyDBOverrides skips those keys.
   The dashboard still beats config.json, because clicking save is a
   statement of intent made a moment ago.

Also: a build-only Docker workflow. The image was the one artifact people
deploy and nothing had ever built it. It never pushes -- no registry, no
credentials, no tags -- and the smoke test is the part worth having: it runs
the image, waits for /health, asserts the response carries no version or
uptime, asserts /metrics is 401 without credentials, and checks xray is in
the image so enabling REALITY later cannot fail at startup. Single
architecture on purpose; the xray pin changes rarely and verifying both legs
on every run doubles the build for no extra signal.

Verified live, not just by unit test: a 20 MB download through a
single-credential session runs at 77 MB/s, and the same transfer as a
Free-tier database user runs at 148 KB/s -- about 1.19 Mbps, which is 1 Mbps
plus the documented one-second burst. After saving a different password from
the dashboard and restarting with .env unchanged, the .env password works and
the stored one is refused.
…applied

Two things here. The feature is backup/restore. The other is a bug the feature
found while being written, which matters more.

Every pragma in the SQLite connection string was being ignored. The DSN used
the mattn/go-sqlite3 spelling (`_journal_mode=WAL`) with modernc.org/sqlite as
the driver, which wants `_pragma=name(value)` and silently drops what it does
not recognise. Measured on both spellings:

    journal_mode   delete  (wanted wal)
    busy_timeout   0       (wanted 5000)
    foreign_keys   0       (wanted on)
    synchronous    2/FULL  (wanted 1/NORMAL)

So the code, the comments and this README have all claimed a WAL database for
the life of the project, and it has never been one. Readers blocking writers,
a concurrent write getting SQLITE_BUSY immediately instead of waiting 5s, an
unenforced foreign key on user_connections, and an fsync per commit that
synchronous=NORMAL was supposed to avoid.

Fixing that turned the foreign key on, which would have broken the dashboard's
delete-user button for anyone with connection history: the child rows reference
the parent, so deleting the parent now fails. DeleteUser removes the dependent
rows first, in one transaction.

backup and restore

    socks5-proxy backup  -out FILE [-passphrase P]
    socks5-proxy restore -in FILE [-list] [-force]

The snapshot uses VACUUM INTO rather than copying the file. That is the whole
reason it exists: in WAL mode the newest commits live in the -wal sidecar, so
reading socks5.db can yield a backup that restores cleanly and has quietly lost
data. There is a test that writes without checkpointing, confirms the WAL sidecar
has content, and then proves the restored database contains the row.

With -passphrase the archive is AES-256-GCM under PBKDF2-SHA256, with a fresh
salt and nonce per backup, so two backups of identical data do not look alike. A
wrong passphrase fails on the GCM tag, which is authentication rather than a
checksum discovered three steps later, and the message names the passphrase as
the likely cause.

restore is written to be safe to run badly. It refuses while the server is
running, detected through a pid file the server writes at startup (a pid left by
a crash does not count, and -force overrides). It decrypts and verifies every
member against the manifest checksum before writing anything, so a failure
cannot leave a half-restored installation. Only the exact member names this tool
writes are restored, so an archive naming ../something cannot write outside the
data directory. The existing database is kept as socks5.db.pre-restore-<stamp>.

That last hazard is not hypothetical, and the tests hit it: SQLite does its
close-time WAL cleanup by path, so a test helper still holding the old file
after a restore installed a new database at the same path rewrote the new file
on close. It is the same failure an operator would get by restoring over a live
server, which is what the pid check exists to prevent.

Verified live, not only by unit test: a backup taken while the proxy was
serving, then the database deleted, then restored and restarted -- the user
accounted for before the backup authenticated afterwards. Restoring over the
running server was refused; a wrong passphrase was refused with nothing
changed; the encrypted archive contains no plaintext credentials.
@coderabbitai

coderabbitai Bot commented Oct 17, 2026

Copy link
Copy Markdown

Review in Change Stack →

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c1f564b2-8770-471f-af57-b9714291ba3f
📥 Commits

Reviewing files that changed from the base of the PR and between 828e045 and a20ecb8.

📒 Files selected for processing: 11
  • .env.example
  • .github/workflows/docker.yml
  • README.md
  • backup.go
  • backup_test.go
  • database.go
  • limits_test.go
  • main.go
  • multiplex.go
  • multiplex_test.go
  • pacer.go
+-----------------------------------------------------------------------------------------------------------------------------------+
| Finish what you start. Where possible, the routine or object that allocates a resource should be responsible for deallocating it. |
+-----------------------------------------------------------------------------------------------------------------------------------+
  \
   \   (\__/)
       (•ㅅ•)
       /   づ
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@GlobalTechInfo
GlobalTechInfo merged commit 8b51baf into main Oct 17, 2026
2 checks passed
@GlobalTechInfo
GlobalTechInfo deleted the feat/backup-restore branch October 17, 2026 12:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant