Repository navigation
Add backup/restore, and fix database pragmas that were never applied - #8
Merged
Merged
Conversation
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.
|
Note Currently processing new changes in this PR. This may take a few minutes, please wait... ⚙️ Run configuration
📒 Files selected for processing: 11
✨ Finishing Touches
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. Comment |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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-sqlite3spelling withmodernc.org/sqliteas the driver. That driver wants_pragma=name(value)and silently drops what it does not recognise. Measured on both spellings:journal_modedeletewalbusy_timeout05000foreign_keys0synchronous2(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_BUSYimmediately instead of waiting 5s, theuser_connectionsforeign key is unenforced so orphans accumulate silently, and every commit pays an fsync thatsynchronous=NORMALwas 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.
DeleteUsernow removes the dependent rows first, in one transaction. There is a regression test for exactly that.The feature
The snapshot uses
VACUUM INTO, never a file copy. In WAL mode the newest commits live in the-walsidecar, so readingsocks5.dbcan 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.restoreis built to be safe to run badly:-forceoverrides)../somethingcannot write outside the data directorysocks5.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
17 new tests; full suite green with and without xray;
gofmtandgo vetclean.One operational note
A backup contains every user password in the clear and, with REALITY enabled, the private key. Use
-passphrasefor anything that leaves the machine, and keep that passphrase somewhere other than the backup directory — the docs say so.Summary by CodeRabbit
New Features
Documentation
Bug Fixes