This commit is contained in:
Mateusz Gruszczyński committed 2026-11-15 13:45:15 +01:00
1 parent df0e39b899
commit 21aef61dd5
35 files changed
+1360 -100

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
# RustProxy source and documentation maintenance
Current source version: **0.37.3**. The Cargo package and binary are named `rust-proxy`.
Current source version: **0.38.0**. The Cargo package and binary are named `rust-proxy`.
Before editing, read [README.md](README.md), the relevant [documentation guide](docs/README.md) and the actual code and tests. Historical release experiments are not current specifications. Use the bundled `src/admin/openapi.json` for API routes and payloads; the source implementation is authoritative for runtime behavior.
+12
View File
@@ -2,6 +2,18 @@
Release history focused on **features, settings, default behavior, compatibility and fixes**. Changes to internal code structure and preliminary performance experiments are intentionally omitted. Historical descriptions reflect their respective releases; consult the current documentation for the settings available in the latest release.
## 0.38.0 — headless mode and catch-all host
- **Headless mode:** `rust-proxy --headless --config /etc/rustproxy/config.json serve …` (or `RUST_PROXY_HEADLESS=1` with `RUST_PROXY_CONFIG` in `/etc/rustproxy/environment`, which the packaged unit already reads) runs RustProxy as a plain reverse proxy and load balancer configured only from a JSON file. No administration listener, API or administrator account; RustProxy never writes the file. Everything that serves traffic works as in panel mode. See [Headless mode](docs/HEADLESS.md).
- **Short configuration files:** in headless mode a file without `listeners` gets the `--proxy-listen` / `--tls-listen` addresses as listeners `http` / `https`, a vhost without `frontend.listener_ids` is bound to every enabled listener, and GeoIP downloads stay off unless `geoip_updates` is set. A working load balancer is a single vhost with its backends.
- **Reload without an account:** `systemctl reload rustproxy`, `rust-proxy --headless reload` or `kill -HUP` apply the edited file without dropping connections or the cache. An invalid file is rejected and logged and the running configuration stays active. The process id is kept in `<data-dir>/rustproxy.pid`.
- **Full configuration format:** every section of the panel configuration works in headless mode (cache and cache rules, COLD tier, compression, ACLs, login providers, Web Server, streams, Docker agents, logging, Prometheus); a panel export can be used unchanged. Examples: `examples/headless-minimal.json` and `examples/headless-production.json` (ten backends, HTTPS, two-tier cache with rules, rate limit, protected `/admin`, logs and metrics), both documented step by step.
- **Offline check:** `rust-proxy --headless config validate FILE` applies the same defaults and compiles the file without touching the data directory.
- **Health endpoint:** `--health-listen ADDR` (`RUST_PROXY_HEALTH_LISTEN`, both modes) serves `GET /healthz`: `200` while every vhost with backends has a healthy backend, `503` otherwise, with per-vhost counts, the configuration revision and the result of the last reload.
- **Catch-all host:** a vhost host of just `*` answers every hostname and IP address on its listeners that no exact or wildcard host claims, so a server without a domain can be published (HTTPS uses the default certificate). Works in panel mode too.
- **Not available in headless mode:** the panel and live logs, the configuration API and cache invalidation API, ACME issuance and auto-renewal (certificates with `issuer.auto_renew` are refused; renew externally and reference the files), the software update check and the ACME runtime preparation.
- **Compatibility:** without `--headless` nothing changes. No configuration migration.
## 0.37.3 — lower memory and CPU use with Docker agents
- **Docker discovery no longer rebuilds the configuration on every poll:** each agent poll (default every 5 s) used to recompile the whole runtime configuration — re-reading every certificate file, building new TLS server configurations for every vhost, re-resolving dynamic ACL names and allocating and discarding the full compiled configuration — even when nothing had changed. RustProxy now compares the generated configuration (and the size, modification time and inode of the configured certificate files) with the last applied one and only recompiles when something actually changed: a container address, port, label publication, assignment, configuration save, certificate reload or a certificate file replaced on disk. On the test machine (51 vhosts, two agents, 5 s poll) idle CPU use dropped by about 45% and process memory under 500 keep-alive TLS connections by about 12%; the effect grows with the number of vhosts, certificates and backends.
Generated
+1 -1
View File
@@ -1943,7 +1943,7 @@ dependencies = [
[[package]]
name = "rust-proxy"
version = "0.37.3"
version = "0.38.0"
dependencies = [
"anyhow",
"arc-swap",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rust-proxy"
version = "0.37.3"
version = "0.38.0"
edition = "2021"
rust-version = "1.99.1"
description = "RustProxy - independent reverse proxy with local administration"
+34 -28
View File
@@ -1,10 +1,10 @@
61bf40a0572889dc8b0dda9eae4e93e44b0de9364b3c798106c85700ffb37c23 .dockerignore
4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example
e76e688874828e3743d03693b1d2872b9633b4db09909673786caf30f7cfe489 .gitignore
a3f8a7f33789a5e3c0b9830878b825eb3f8b5d2d9adaa9a706d042694a350d01 AGENTS.md
a2301446d4e490a4cc5230cf77d6035b8bca9758d86cfa3ccf56454ed7ce3354 CHANGELOG.md
f91f8d0b3e588f50bec26134a73ea7e7e6c9d9ff1bbc11216ab8e582ac6e660b Cargo.lock
39e599669ff1ea1e24e93888fcaf4cd89e09abce31a0d8c8314431004ac022eb Cargo.toml
f3549b7a74b9d902672d1637bfbbd70df7f47cd7a69a7b15d0fdcb78704ea3b2 AGENTS.md
c68b2d4f4e1cca986225ab94d34687cb85a75084375eebc33af5776137d79e08 CHANGELOG.md
cffd1a831775774a1d2c3f8a9e5c1fc462e9737b7f5f5438ed5045d756482b0a Cargo.lock
48e85b34ba68a97a0b22a978c69aa84f72c3d2323cd1672952fc7516fc345f19 Cargo.toml
788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile
0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 LICENSE
82d1dee2fc68158f0ea73259151461e64c8b18d807cd1fecfb1ed99dc30cf5f4 README.md
@@ -28,7 +28,7 @@ e9f18b358a740f1fe16e369ed16ee37581b8ce4c94ddeb34a1a37b89a49b5a06 docker-agent/c
b849d39e94878c5a754c3d109d8e4b5e37609cfd2a0e05601a35271f4d95271e docker-agent/install.sh
56d6acd675c44c3a39538b321d2057cf251a6a27b0ad634d827eb7d6a20de8c0 docker-agent/main.go
d660f46f7ef8c539dd3f5486a31d5a1254b9737be8a278c7f9352c254558f8ac docker-agent/main_test.go
0d5c31214aa70e1da86b7854e8f979a2dded345b876271812f1d489f25fe0b7d docker-agent/model.go
c007fd51220b372ffa5c5760fa7a2f2c50d1b926dc269fdb64baf37166905ba9 docker-agent/model.go
e7d2ef3cc83d8089d3b5eb2154c113d82bbab5e7bac0b9077785d5ab92f48df2 docker-agent/network.go
6e2e13136fd8198c2d64dfd0612dfc91c4a9c0a952e71b3b24c9614a72b083aa docker-agent/network_proc_test.go
021e0799a95a7c76bc245ff464d94b4495ce0d22555ca202579bd5f45e4be794 docker-agent/provision.go
@@ -42,25 +42,26 @@ c0940a4b323d71931cf2ad4ad24d58b6d6bfd49af90c6e3fc91fcbe2b4cf312f docs/ACCESS.md
728b15b9825f547f34c4121219784798dd046fbbdd72ece8906d0cd77e8efc64 docs/BACKUP.md
79c767197bec37787af7d949b7134cefe1e0d22c1d0b8a801eceafcf69e7599d docs/CACHE.md
375241ef87cff34c0bda5b771ee474a402f24ae8fb00e97f601b1a5060690508 docs/CERTIFICATES.md
9c9e6c56ae9d714a5a99bffd39cb2d506991af5e67f034d41fe45210c95ac5ca docs/CONFIGURATION.md
6aa83366ad45227d10ebe121ed2c4f690ebcb826939ec2b2eafb40bfd714ac69 docs/CONFIGURATION.md
fec29ce846d6705eb45819d85d382f28e28a146b265feab2e4c7cce2a35e5883 docs/CUSTOM_LOCATIONS.md
5776a6e59df079a8788df00f031cb366f12718f5336ddabd90a953aed2f8b1f7 docs/DASHBOARD.md
40de73f749877b1a371b48be2f43422b8598c59a2e8768c9d2d986a35c693cdf docs/DOCKER_DISCOVERY.md
bd0bb5583bf171dc2cf73b56492184f6d7a69bf33db5f25c5396ed6c3300b400 docs/FEATURES.md
2c5f97b12be53db32c7e2888d23c0ef1d82d1742df44f7e60ea818dc801a719a docs/INSTALL.md
1ea47fbdc41b28024d57af9280f5c07ab92f08a38ff011fc3b978e579c2cb188 docs/FEATURES.md
3e6d8c03095af2328d1c4a15f7bb1834ef9b554ad588bd714b40d6d79754a2a2 docs/HEADLESS.md
4282602f0b814841f71282040003bec91c24611e5152b33407b76e62357f8d3a docs/INSTALL.md
6e37859bf0dced99d4a7db93790cb38fcd90191932827946d5223eaa4c784fce docs/LOGS.md
0e9ae9509a78d00951d2c7c3f13eaf518d1f3448a29b048f5933e1f5f8440275 docs/MIGRATION.md
a7717c4ab03417914805527e573ea1dfd5d35295bf7b347d0c098bda6d469850 docs/MONITORING.md
6d3937088eeb67a9f690d44ebe0b6e660b68116dbf69091ac7816bdc52cec2b6 docs/PERFORMANCE.md
d5894c07c68ec4230987767198434abee13b0e525842fea21bcbe752fa82742b docs/PHP_FPM.md
954b1602c865e157c867f1c81dca615f2beaa33c34de0b0fa8a6069db2aae7d0 docs/README.md
c1cd9e321ee4a570001e254b53a0e617310c8915da8117d470577528bcf03461 docs/README.md
490a6dbe870f2b1fd4ec7816768dde6c86fa7957fc9de2d2f075e123c9222222 docs/RESPONSE_DELIVERY.md
95ab4786792d5920a2e109b7d196838057f24b512a69d713fb5884dc75c84339 docs/SCREENSHOTS.md
3a48184b36d225757fc5e2d22c629f89bfe5d4007ff087f0be0ce02a5fb04c28 docs/SECURITY.md
bbef60ff1771da9f48af812987766e1e479408873ae2f079b13f1d5c62ecc6ff docs/STREAMS.md
978097cf53314ad573583d7176491d984b9dbb22295df2b00168a28b14184c4a docs/TRANSPORT.md
be6e8af62a7bf958b94ec15e9e3263263e511d1d33abae4e45d114833fa52b07 docs/TROUBLESHOOTING.md
b4abb86942f665230904fad570c1487bc173aa84633801e2999f2bfa197de4a7 docs/VHOSTS.md
c8483143f91e42f81cebdf3cf0b46fa68a6b9d20f0142a4d3e957eeb0d7e495b docs/VHOSTS.md
e67928a9d044e71b681c3e52f9dd8b151d6b72f965d16d5da8b0eadde98b70e9 docs/WEB_SERVER.md
42822b1c9801bcadb0e2d785cb91883ca2df1da141222631f153030c95f5e197 docs/images/about.png
deff2393a987ac7102179dc85b48baf2c4a3882291bb8c7c584d760cc497c631 docs/images/api.png
@@ -80,6 +81,8 @@ dcdd387384037c7a1a32f6a4d948a182e44bea472542b8fe4e9b6c917edcf551 docs/images/ov
2431dd88a2d9ad2cf3cd4b8fcdfa602563ab1013c612d8917fddbe7febfb2dc3 examples/cache-dashboard.json
e31ac05a99615e4ea6c4c9a8b2e090968583fe3959f838a600b5740cb170f8c5 examples/config.json
39cad993003930febf98460311d185a278e7a9508b6b591299d9339d0f0c51cf examples/empty.json
50d9799a6fa7e4bbf754937f9741459392fa93eabe8fe3b892671a31f59fd505 examples/headless-minimal.json
3bbf64c65dd770f05af0eeecc2a5d6eb88149e35163f491f5f9eabb6f586c2a8 examples/headless-production.json
695cc7621aa403148fcd0868f351b6e9ccc076fe35610e779af4a72f94d7d5f4 examples/http3-vhost.json
b26833cb4251f9390a44192ecc827ff7f052fd19016a5ccf7498c94503ab4ce3 examples/mock-vhost.json
a6b835dc07defc12b8f0e48491d5f413843c8be2ba4501d7c28140a2822b034f examples/oidc-vhost.json
@@ -100,7 +103,7 @@ c720a4426d7b4dc52048077157dd05aefa427ae78ca811afc3b7b9cbbe875cae grafana/rustpr
e9cbb0224c4a3d23a6019ba557e0cd568c1ad5e1582ff1e335fb7d99b7a1055d integrations/routeros-oci-build/.gitignore
14025f0cad10e1b89f366977123e4cebb68ae59df892d4eed29b6171e63ae908 integrations/routeros-oci-build/Dockerfile.routeros
7c7a3e51f43b43e1c962a4b0bb591f99c1f06977bf77f23719f7f867dfe7eb8e integrations/routeros-oci-build/Dockerfile.routeros.dockerignore
31dc057054b2b7f2ea3b826f2c4b6bd7b43a82327781ec54486bb5072889d4be integrations/routeros-oci-build/README.md
eb9225830f344886ce57c51fbf9ded7bfd525a2ede71a5f67ce81f7c01348a6d integrations/routeros-oci-build/README.md
3f092a9ab80221eddd67be4d1a776acbc6e04c1eb6011b588280c28e83b2582f integrations/routeros-oci-build/build-routeros-oci.sh
3f267cafa16006e5456ade78ee2d5fae02cc7ce747839523068ffd8d7c98798a integrations/routeros-oci-build/docker-entrypoint.sh
ae2ee2887fcba096d0de25edcc18faa1ffec35759274518db1bf6d6982f7176c langs/README.md
@@ -171,7 +174,7 @@ aefbef9839f9914ba05ea62bceff1463da3042b52ee851181ee39d4fbf7b91c3 src/admin/cert
7cac90d705a201b764d283e06774744e4b358eb157a8c492357bfc21aed37543 src/admin/config_sections.rs
c51f725075b5c4fc3fb7fb8b8b5f73987bff698a400e8950e968068b97a77631 src/admin/dashboard_presets.rs
aae1ca0e70d987830bd63948d431f54302083148177c1b551565be12df7fe771 src/admin/documentation.rs
6f58f821ea9a1686fc5130336ac82f06d5914b3642088641b5d036df6304c671 src/admin/documentation/documents.rs
fda952396c0c06a1deb474c66a27ea12ca4a4892d8412d7d7fcd80e814dde23e src/admin/documentation/documents.rs
b9c2952e3fcfca540d0ad64f2d3acc5c1f5240e707f4f23ef4d452f46fcb520f src/admin/documentation/tests.rs
1ce779b84aa8f47bdb3c34f83593c1f2f06d2235f0319847096cfcd035434168 src/admin/file_log_search.rs
059218501907355b22bc84e7e0c41ec72565af283f5e97170ce7707ea5874009 src/admin/file_logs.rs
@@ -179,7 +182,7 @@ d58a2ed83319176de4e66790ed292447c9497ae031464ec55cfe27174acb639a src/admin/file
77b8c05645969834cc8a58e249a7b60a57d6c47ad1c5cd92ffa5e4a9b5a8e73c src/admin/file_logs_query.rs
743bb7436f77e04015328a0e7e7d425e43ef8aa8d61467bde157e462c1dcdc2e src/admin/logging_api.rs
51228956c33358278ebed62941da273e1e87d0b5c5d1c40cc0d2c91aec9d7362 src/admin/mod.rs
dcfa7a6ececbb803ba48bb971fab3367eb1f97f2d68d9cbcb092b601ce6753c6 src/admin/openapi.json
98bdd2811c608ef6caacc695075e717829e3774ff594d29dcf18905396bbbc6a src/admin/openapi.json
f7a356109786635dd58cba590c71c796dbf36b47f25845190c75ee5c6a9fcb86 src/admin/operations.rs
257d93a29d0bda96462bcf695aba8d0ec0f9412c379e066ec46ae8ee034e3a53 src/admin/panel_assets.rs
f5127855c2994d052678865df36d703b74f4a0afc633daf7718b10da18d26e37 src/admin/panel_content.rs
@@ -287,7 +290,7 @@ fca28ef97ffee213bd854ded4acdd90f8a55d269ee730b4e15ba1aebcf50fbd0 src/admin/web/
3776f72d7051af86ac5fbdd4581040dd88a424c0c6cde789301b032b159094d8 src/admin/web/vhosts/health.js
b3239e67901f1796d7a974ade0796f2e3590ff8064628a5629b78c7f6ce2f32e src/admin/web/vhosts/protocol.js
8c3da49973c62333559b0e3588c02beb0b425c025eac5cfa82a1bb968f70d9dd src/admin/web/vhosts/rates.js
9ae02166d190fd3ea0f2946912df6edd036f3c2727950277ae1a31768e2133f2 src/admin/web/vhosts/render.js
4eb23a1b5d78dc44e1cb8c2e56588d0be0f3c3e089339c5d2f495b4cd63a6013 src/admin/web/vhosts/render.js
4dfdeb7c73c2775eacaca65fd8ef1dc80b275421b15522d319d338f5b96288cc src/admin/web/web-server-profiles.js
f9854526ff1567de47ecb02af872bca6e13c0adb984ad5ef0c256e5fdbb3902e src/admin/web/web-server.js
36f11beed56711640bb56bb6f452bf76dec2ce4be6a57e8abc19560af477c870 src/alerts.rs
@@ -371,9 +374,9 @@ e0542812b82c31481e18de2bf50e0f00ec0608be47c48aeb4b2b8429dd9a6e39 src/config/bac
fbea01fea1213d98aea812c1b78d5db289e09200b98ae514d742235cd3fa70e1 src/config/internal_routing.rs
c0446a45e3bc8547dcce51579ea137e5c0e1e89f17d4dada950382909ee85745 src/config/model.rs
75839458ddbc7480ec4492a95eeb67b617ba7d62f7b67e7a767a3453b74dbcbc src/config/route_policy_tests.rs
0353322f4e265e1b2d36a7ac863953daff5f06072797f26c74d01b1865b44faa src/config/routing.rs
b33c45184e6451e15ce238cc922d2116269a1bf1d72093c2cdc068c4386a35bd src/config/snapshot.rs
477cddaa1e1c0b9b605a2f550971a04cf30287519cba70cfbb2e1860e3a93ff2 src/config/tests.rs
067743d11f1747c4f46296e08174c4f03c3aea9f2d025f23eecda940e0c1fcb3 src/config/routing.rs
f191b518f90c8cc70461ab1db1ab4616f5ce4604de2214d8943d1e76ceabd65f src/config/snapshot.rs
de7bb81b93662ce1dd78b7da4d38fb4b56568b269791090faeb2a3b83e5e285d src/config/tests.rs
f35de0ee1516ece6bbfd2b2a7db7d1e0f5048b0ec47cf2a3765dffb799abfd93 src/config/transport_tests.rs
a09f361d70510d6226f4dd6785e649c3dc01ccafc70a4c8b0dcd098e224129b7 src/db.rs
c290d0cb02dfa5d2c60ecabac1cfb20c8884e3d14cca1944906c6d8e677f1784 src/db/api_tokens.rs
@@ -415,9 +418,10 @@ e9795eaa3e743c09f5ab0e18e6d359bc97a3aee55510c74923532d64df90c873 src/logging/fo
66c4596e644d9dd539d468575e2de6459bac2624fb1e1064cdae61a21c2e0240 src/logging/model.rs
bf898b318feb9bd3dd2c335b6b1bad172da63fd5cefbff3e267421ce37c076fb src/logging/runtime.rs
3d6ea5508bc9609c6ce99a3a1d3fec2fafb95a2a8de579a80262b73c6eed3a63 src/logging/tests.rs
cdcb3806669207c17279da959bbfcfacf18cc192f24e862c0afa0c389a41631a src/main.rs
87e69b46c548b861e9d90d9d2e42dfc2630891f4583800b1942f9065d25e29cd src/main/admin_runtime.rs
224da3127b5f846a8932fb7f4b6e23d0dd590dc0170506267381d66042c64666 src/main/bootstrap.rs
560c3a022a163a751d7b568d9493076500effdac34dc29cf5aa2954487504619 src/main.rs
df3e99ab116de049afd3d9c9bc8226d316ae7e24399de95156a5008d139e5467 src/main/admin_runtime.rs
40e3316e52958cac5f1c6f9300604cb9e3b0f54e7c30076ad5b5b2b811b8ceb1 src/main/bootstrap.rs
277530c83e2e00235ed9a844df92dadf5967b8e3530a470344e72c8326de00bb src/main/headless.rs
5a98d0e249338e73aa57ae2e352dc16db2f79c2d042c1544ce1c2022da76a31c src/main/proxy_runtime.rs
b240033715323e7cb7b9bcaf92edd481f7089b4da6bab25005ca6733da8756dc src/main/shutdown/mod.rs
0a6578a0f4023b9f8d73043bf942dc5e096ef9afb8c0d2f131c14f65d08ac01d src/main/shutdown/tests.rs
@@ -485,14 +489,16 @@ a44421714aab37f7ceda19e3ec2512c645d2a3ce5dcb3da5bc7a0d87a442d6a8 src/proxy/webs
c85c9f05dac65cde6878bef3ef7258eb9de79ca14c26ca2492e0e13839c40fc3 src/rate_limit/tests.rs
db254128c8013adaad7280f40a0edd8b196083afef299cd9e193e6db1d698b82 src/redirect/mod.rs
811c83ae9fd0f5a13d35b5443cd37843f82b9d600bee4bb136ba9b87732a5347 src/redirect/tests.rs
244d72b3dab36ec505c96d26a967420714fd3807268820f680fb3dcea0e88c0f src/runtime.rs
5c45188935aeb827a589cfe92fbd9697336d1229e94cfbc2d1f329693360b8b3 src/runtime.rs
e2a5367eb4e9b35e58acacb2390cc859e7ee5b59379b79e302018737028a90a7 src/runtime/certificates.rs
16f0d8f6255204b758ab5584098b220e109ffaa271d28b31d5b7f189b0b2e804 src/runtime/constructors.rs
d9017b6ca3a624b6883f696337471d513fbf2e96a90c92b184a895c72a16ccf0 src/runtime/constructors.rs
a868442930930eeb71aeb2e14274bb69497ecbc4d844879e3666b636c7c993d9 src/runtime/docker.rs
18f7460e3738386e070f66932cd77240001255447a769d6e19a40573254a1473 src/runtime/external_config.rs
5999d7e91ee4231da88c5e9c6d8a12ea9f92d20d6dcdb24319f9f90891d7253b src/runtime/tests.rs
1d7a091fc0eed612818aaed9e124315a7bce321542f554af901046f4f148f070 src/runtime/external_config.rs
66a6f30dee7df4514a75643889be0f8da17f977475cd680fd9e17b8a5d9233da src/runtime/headless.rs
ecef7027b177061325e5af6d8891b431b7b837aa36d2faa5b3d4d9757d2e6c8b src/runtime/health_endpoint.rs
35449acc2b03c49067bed581537515726f95033714fc8dac0f7df15ad265a6d3 src/runtime/tests.rs
3eb734dcdd16eeb8585fe79df4909d36f06c057fdb2815e2d8abc7745b0a3039 src/runtime/types.rs
f30e64fb6f4dc70602b1460f7e289be69fea0fff507d8ef47f7608a5e1fad3b9 src/runtime/updates.rs
bfda11f72647e0062524ec30b1c8a3951ceef744657be7b721edcc9868f70598 src/runtime/updates.rs
e3dbd60953db5a976985dd796e4268b41a0f3df59764c4664015bd41e2578058 src/secret_store/mod.rs
b0c4a46b40b09794fd8a037afca380ee3b95941bf75a0e1102a4e520a4bd8be3 src/secret_store/tests.rs
53bc7b1fcc1eab8860ebafccd0c9ed2aadf75363323891a4a4a22114c323b22a src/security/mod.rs
@@ -522,7 +528,7 @@ e0676801259fb09a73825d959b89630bfa0b6f1fd1efd3006af29f60537a2fdf src/system_sta
3d40febfbaf38ca2725630eed6b33106e353086081ea811107e4ec9d24f7de11 src/tinyauth/tests.rs
df98becda799b6bf4ff5e2fec7d0e0a486e6b7eca6f9f5ad49ffdafd49a4f498 src/tls.rs
2af2164ecdf2b7fd9eef7c6e358dec053dfac9aedaa501dbb75df742d18638b2 src/tls/acme_tests.rs
93e0576ac9077e645a72d164bad34cd75fe6032dd0516284d08bddd2fbda4b7c src/tls/certificates.rs
d9ed71762081732fee3c79192a96a36c744f499e308f74c6d12fd5d7a7679d15 src/tls/certificates.rs
a71f20dbec5802dffe9d51a78b931062b5abdec2bc82ad6fe98abd9c7b5abd7b src/tls/external_paths.rs
937b95bb8621ab98d7cad3d223e4dee305350fbd0149b7527396d3bdcc28a68b src/tls/external_paths_tests.rs
90ed8c34b49096cf78f50dd014f9e2968942b142ca95d28307f269e3fe5a0fc1 src/tls/server_config.rs
@@ -558,7 +564,7 @@ d61c427c1e9cf457f1232b822d73e846e9f329cfbe61215e7ca061d53762155d src/vhost.rs
a8c5ec5095178a0656a001b0d7100e240d1f32b052ea60df37f8681269638ab3 src/vhost/model.rs
fc8af7342a3b147921e9040116af5dfe680b3df910db2416ada18198bbeea7df src/vhost/redirect.rs
2651d7e3e3fadf3de74a75eafe2bbad8d02939551ccc0504c1a092a0b33b0db5 src/vhost/tests.rs
c32ff8fae0c291bf072404aa118cb81016752b2929c89c7ec845d97006e677ce src/vhost/validation.rs
99702a17866be0f21bac2c71b2fc6fe4fdce093a6fa54a056ecc08706cb0706c src/vhost/validation.rs
8d1eff4b24f01d137414ef5419f75dd281879228adb70409645b11b3c78c20e9 src/web_server/config.rs
9744e8c29ae72a4d9fbc9a76166a97f8292c4c312295ea40d1cb699e03d80a9d src/web_server/config/compile.rs
5ed79fa5b9c53f95ca200d89a9ba927dda816b61fbdf3b852bd3c9670e3d2d4f src/web_server/config/model.rs
@@ -588,7 +594,7 @@ f00743af2cf4a5952caef7a1dcf68e7817b5599a252a9973e1c22045517c0b0e tests/fixtures
102b83171a6429b6375d8001d6c5294702385cd58ee55727cb657b1f3566e877 tests/panel_icons_browser.py
c4030b7d224553312012b1f25153dd3545e83de7bccff2894c0e8f7e0e84b721 tests/panel_icons_contract.js
886c89e8517f34af5e2aef9672a8de559f94c536b028f1b9cadf2a2a7220d826 tests/panel_interface_contract.py
1b07b3809ca3bb2d931dda61528d820ea21423a6642f4686985a5042663ea204 tests/panel_refresh_contract.js
e55a1b77d66f7a1b588b96c34a1d33351b9d10d296745215046a00904b35c4a0 tests/panel_refresh_contract.js
e24a0f84f1bfc46964df865ac387d651f7b384d781cbc8f3a9a5b0b60f3d69ca tests/vhost_auth_selection.js
cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 third_party/swagger-ui-5.33.1/LICENSE
0d20d1adef18aee3f40dd258172155521ce702ac445cb5f7b7d60ed32dad2fb2 third_party/swagger-ui-5.33.1/NOTICE
+1 -1
View File
@@ -1,6 +1,6 @@
package main
var version = "0.37.3" // overridden by the package builder using -ldflags -X main.version
var version = "0.38.0" // overridden by the package builder using -ldflags -X main.version
type config struct {
Listen string
+2
View File
@@ -25,6 +25,8 @@ For a systemd deployment, use `systemctl edit rustproxy` to add `--config /etc/r
Check the effective unit with `systemctl cat rustproxy`, paths/ACLs with `getfacl`, and storage mode under **Settings → Manual config**. Manual file edits require `systemctl reload rustproxy` to import changes; a successful panel save already updates the file. Listener binds/ALPN still require a restart. Back up both the JSON source **and** the SQLite database/other private state; history is not a complete backup.
Without the panel: [Headless mode](HEADLESS.md) runs from a JSON file only, fills in listeners and `listener_ids` from the startup addresses and never writes the file.
## Configuration map
| Panel area | Main settings | Operational note |
+1
View File
@@ -91,6 +91,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se
## Operations
- Configuration stored in SQLite or in a JSON file, with validation before activation and hot reload.
- Headless mode without the panel: configuration from a read-only JSON file, catch-all `*` host, reload by `SIGHUP`/`systemctl reload` and a `/healthz` endpoint ([Headless mode](HEADLESS.md)).
- Revision history with diff and one-click restore.
- Encrypted full backups and validated offline restore; encrypted Secret Store for credentials.
- Docker and Podman discovery through a separate agent: publish containers as Vhosts with one switch, one-time agent provisioning codes, publishing from container labels, multiple domains and certificate lists per agent, host and container diagnostics with history, Docker alerts, Prometheus host metrics and optional Docker Overview cards; the Grafana dashboard covers several RustProxy servers.
+211
View File
@@ -0,0 +1,211 @@
# Headless mode (no panel)
Headless mode runs RustProxy as a plain reverse proxy and load balancer configured only from a JSON file. There is no administration panel, no administration API and no administrator account. It suits small, repeatable installations: a load balancer in front of a few application replicas, a server managed with Ansible or a configuration kept in Git.
Available since 0.38.0.
## What changes compared to the panel mode
| Area | Panel mode | Headless mode |
|---|---|---|
| Configuration source | SQLite or `--config` JSON, edited in the panel | `--config` JSON only; RustProxy **never writes** the file |
| Administration listener | `--admin-listen` (default `127.0.0.1:9090`) | not opened; `--admin-listen` is ignored |
| Administrator account / setup token | required for the panel and CLI reload | not needed; no setup token is kept |
| Applying changes | panel save, `config reload` | edit the file, then `systemctl reload rustproxy` (SIGHUP) |
| Listeners | must be declared in the configuration | taken from `--proxy-listen` / `--tls-listen` when the file declares none |
| Vhost `frontend.listener_ids` | required | optional; defaults to every enabled listener |
| GeoIP downloads | on by default | off unless the file sets `geoip_updates` |
| ACME issuance and auto-renewal | panel and renewal pipeline | not available; use external certificate files (for example Certbot) |
| Software update check | on | off |
| Health endpoint | optional `--health-listen` | optional `--health-listen` |
Everything that proxies traffic works the same: vhosts, backends and load balancing, health checks, WebSockets, HTTP/2 and HTTP/3, TLS with imported or external certificate files, cache, compression, ACLs, Basic/Forward Auth, OIDC, streams, Docker agents, Prometheus and file/Logstash logging. A SQLite database in the data directory still records each applied revision.
## The configuration file
Headless mode reads the **same configuration format** as the panel mode: every section works, including cache settings and cache rules, compression and transformations, ACL profiles and host policies, Basic Auth, Forward Auth and OIDC, web services and PHP-FPM, streams, Docker agents with their assignments, logging sinks and Prometheus. Only these fields get a default when they are missing, and only in headless mode:
| Missing field | Headless default |
|---|---|
| `listeners` (or an empty `endpoints` list) | `http` from `--proxy-listen` and `https` from `--tls-listen` |
| `frontend.listener_ids` of a vhost, redirect or 404 host | every enabled listener |
| `geoip_updates` | `{"enabled": false}` |
Anything you write explicitly is kept. A configuration exported from the panel (about 176 KB, 31 vhosts, cache rules, Docker agents) was tested unchanged in headless mode, both on a copy of its data directory and on an empty one.
### From an existing panel installation
The panel export already is a complete headless file:
```bash
sudo -u rustproxy rust-proxy --data-dir /var/lib/rustproxy config get > config.json
```
(or **Settings → Manual config → Export JSON**). Validate it with `--headless`, install it as `/etc/rustproxy/config.json` and switch the service as shown in [Running with systemd](#running-with-systemd-debrpm-package). Certificates referenced by file name stay in `<data-dir>/certs`; keep the data directory.
### Secrets in the file
The file can contain secrets: Docker agent tokens, client secrets of login providers and Basic Auth password hashes. Keep it `0600`, owned by root or the service account, and out of public repositories. Values that support it can come from the environment instead, for example the Prometheus token (`bearer_token_env`) or the Loki token, which you set in `/etc/rustproxy/environment`.
## Minimal configuration
The smallest useful file is a single vhost ([`examples/headless-minimal.json`](../examples/headless-minimal.json)). `"*"` as the host makes it answer every hostname and IP address that no other vhost claims, so no domain is needed:
```json
{
"vhosts": [
{
"id": "app",
"websockets": true,
"frontend": { "hosts": ["*"] },
"backends": [
{ "id": "app-1", "url": "http://127.0.0.1:3101", "allow_private": true },
{ "id": "app-2", "url": "http://127.0.0.1:3102", "allow_private": true },
{ "id": "app-3", "url": "http://127.0.0.1:3103", "allow_private": true }
],
"load_balancing": {
"algorithm": "round_robin",
"health_check": { "mode": "http", "path": "/health", "interval_ms": 5000, "timeout_ms": 2000, "fall": 2, "rise": 1 }
},
"cache": { "enabled": true }
}
],
"cache": { "enabled": true, "max_bytes": 268435456 }
}
```
- Up to 32 backends per vhost. `allow_private` is required for loopback and private addresses.
- `algorithm`: `round_robin`, `least_connections` (default), `least_traffic`, `adaptive` or `ip_hash`; `sticky` sessions are configured as in [Vhosts](VHOSTS.md).
- By default requests with cookies or `Authorization` and responses with `Set-Cookie` are not cached, so enabling the cache for an application with logins only stores public responses and static files.
- With an HTTPS listener and the `*` host, clients that use an IP address or an unknown name receive the default certificate (self-signed unless `tls.default_certificate` points to your own).
## Production example
[`examples/headless-production.json`](../examples/headless-production.json) is a complete load balancer for one application with a domain, ten backends, HTTPS, a two-tier cache and monitoring. It was validated with `config validate --headless` and run against ten test backends: HTTP and `www` redirect to `https://app.example.com` (308), static files are `MISS` then `HIT` with a 30-day `Cache-Control`, tracking parameters do not split the cache, `/api` is `BYPASS`, `/admin` answers `403` outside the allowed networks, `X-Powered-By` is removed, HSTS is sent, the access log is written and `/metrics` answers with the token.
What each part does:
| Part | Setting | Purpose |
|---|---|---|
| Listeners | `http` on `0.0.0.0:80`, `https` on `0.0.0.0:443` with HTTP/2 and HTTP/3 | Explicit, so the file documents the bindings. They must match `--proxy-listen` / `--tls-listen` of the service. |
| TLS | `tls.certificates` with `cert_file` / `key_file`, `default_certificate` | Files in `<data-dir>/certs`, or absolute paths to a Certbot lineage (see below). |
| Vhost | `force_ssl`, `www_redirect` + `www_redirect_target`, `websockets`, `forward_client_ip` | One canonical HTTPS address; WebSockets proxied; client IP forwarded in `X-Forwarded-For`. |
| Backends | 10 × `http://10.0.0.x:3001`, `protocol: http1` | One entry per replica. |
| Balancing | `least_connections`, active HTTP check every 5 s, `passive_health`, `retry` once on connect errors / 502 / 503 | A replica that fails two checks or keeps failing real requests is taken out; it returns after one good check. |
| Keep-alive | `idle_timeout_seconds: 60`, `max_idle_per_host: 32` | Reuses backend connections instead of opening one per request. |
| Timeouts | connect 3 s, headers 120 s, read/send 300 s | Raise read/send for large downloads, uploads or long polling. |
| Security | HSTS, `nosniff`, `frame_options`, `referrer_policy`, `rate_limit` 600/min with burst 120 | Per client IP. |
| Routes | `/admin` with an ACL (private networks only) and no cache, `/api` without cache | Location rules are checked before the vhost defaults. |
| Compression | gzip, Brotli, zstd from 1 KiB | Applied to compressible responses according to the client's `Accept-Encoding`. |
| Logs | JSON access log in `/var/log/rustproxy/access.jsonl` | Rotation as described in [Logs](LOGS.md); warnings and errors also go to the journal. |
| Prometheus | `127.0.0.1:9191/metrics`, CIDR list and `bearer_token_env: RUSTPROXY_METRICS_TOKEN` | Put `RUSTPROXY_METRICS_TOKEN=<32+ characters>` in `/etc/rustproxy/environment`. |
### Production cache
The cache is controlled globally (`cache`) and enabled per vhost (`vhosts[].cache.enabled`) and per route (`routes[].cache`). The example uses:
| Setting | Value | Meaning |
|---|---|---|
| `max_bytes` | 512 MiB | HOT tier in RAM. Process memory is always larger than this (connections, TLS, allocator); see [Performance: where the memory goes](PERFORMANCE.md#where-the-memory-goes). |
| `max_object_bytes` | 16 MiB | Larger responses are streamed and not stored. |
| `max_entries` | 16384 | Upper limit of objects (1..16384). |
| `cold_enabled`, `cold_path`, `cold_max_bytes` | on, `cache/cold` (inside the data directory), 10 GiB | COLD tier on disk: objects leave RAM after inactivity or under pressure and are read back on the next hit. Survives restarts. |
| `default_ttl_seconds` | 0 | Only responses that the backend marks cacheable (`Cache-Control`, `Expires`) are stored, unless a rule sets a TTL. |
| `max_ttl_seconds` | 86400 | Caps any TTL, also from rules. |
| `varnish_grace_seconds` | 60 | A just-expired object is served while it is refreshed in the background. |
| `bypass_prefixes` | `/api/`, `/admin/`, `/login` | Never cached, regardless of headers. |
| `static_ignore_cookies` | true | Static extensions (`static_extensions`) are cached even when the browser sends cookies. Turn off if your static files depend on the session. |
| `collapse_enabled` | true | Concurrent misses for the same URL wait for one backend request. |
| `stale_if_error_*` | timeouts, connection errors, 500/502/503/504 | Serve the last good copy when the backend fails. |
| `expose_status` | true | `X-Cache` / `X-Cache-Reason` in responses; switch off once tuned. |
Cache rules in the example (same format as **Settings → Cache rules** in the panel, see [Cache](CACHE.md)):
1. **Request:** `strip_query` removes `utm_*`, `fbclid`, `gclid`, `msclkid`, `_ga`, so marketing links share one cached object.
2. **Response:** static extensions get a 30-day TTL even when the backend sends no caching headers.
3. **Deliver:** `default_header` adds `Cache-Control: public, max-age=2592000` for browsers when the backend sent none.
4. **Deliver:** `remove_header` drops `X-Powered-By`.
Check the result with `curl -sI https://app.example.com/static/app.css` (look at `X-Cache`, `Age`) and the `rust_proxy_cache_*` metrics. Without the panel there is no cache page or invalidation API; to remove objects, enable HTTP `PURGE`/`BAN` for trusted addresses with `"http_invalidation_allowed_cidrs": ["10.0.0.0/8"]` in `cache` (see [Cache](CACHE.md)), for example `curl -X PURGE https://app.example.com/static/app.css` from a deploy script. On a clean stop HOT objects are moved to the COLD tier (`cold_on_shutdown`), so the cache survives restarts.
### HTTPS with Certbot
Point the certificate at the lineage and reload RustProxy after each renewal:
```json
"tls": {
"default_certificate": "app",
"certificates": [
{ "id": "app", "hosts": ["app.example.com", "www.app.example.com"],
"cert_file": "/etc/letsencrypt/live/app.example.com/fullchain.pem",
"key_file": "/etc/letsencrypt/live/app.example.com/privkey.pem" }
]
}
```
```bash
# /etc/letsencrypt/renewal-hooks/deploy/rustproxy
#!/bin/sh
systemctl reload rustproxy
```
The service account needs read access to the files and the directories must pass the trusted-path checks; see [Certificates: existing local files](CERTIFICATES.md) and [Installation: external paths](INSTALL.md#linux-debrpm-read-only-access-to-external-paths). Certbot's DNS-01 plugins work without touching RustProxy. HTTP-01 needs `/.well-known/acme-challenge/` on port 80 to reach Certbot, for example a route with a Web Service that serves the Certbot webroot.
## Validate before starting
```bash
rust-proxy --headless --data-dir /var/lib/rustproxy config validate /etc/rustproxy/config.json
```
The check applies the same defaults as the running service and compiles the configuration without touching the data directory. Set `RUST_PROXY_PROXY_LISTEN` / `RUST_PROXY_TLS_LISTEN` to the service addresses when they differ from the defaults, so listener conflicts are checked against the real bindings.
## Running with systemd (DEB/RPM package)
The packaged unit already reads `/etc/rustproxy/environment`, so headless mode needs no unit edit:
```bash
sudo install -d -m 0700 /etc/rustproxy
sudo install -o rustproxy -g rustproxy -m 0600 config.json /etc/rustproxy/config.json
printf 'RUST_PROXY_HEADLESS=1\nRUST_PROXY_CONFIG=/etc/rustproxy/config.json\n' | sudo tee -a /etc/rustproxy/environment
sudo systemctl restart rustproxy
sudo journalctl -u rustproxy -n 30 --no-pager
```
Optional health endpoint for an external balancer or keepalived: add `RUST_PROXY_HEALTH_LISTEN=127.0.0.1:9091` to the same file.
After editing the configuration:
```bash
rust-proxy --headless --data-dir /var/lib/rustproxy config validate /etc/rustproxy/config.json
sudo systemctl reload rustproxy
```
`systemctl reload` runs `rust-proxy reload`, which in headless mode sends `SIGHUP` to the service (the process id is kept in `<data-dir>/rustproxy.pid`). `kill -HUP <pid>` does the same. A valid file is applied without dropping connections or the cache; an invalid one is rejected, logged, and the running configuration stays active. Listener address or protocol changes still need a restart.
## Running directly or in a container
```bash
rust-proxy --headless --config /etc/rustproxy/config.json --data-dir /var/lib/rustproxy \
serve --proxy-listen 0.0.0.0:80 --tls-listen 0.0.0.0:443 --health-listen 127.0.0.1:9091
```
In a container, mount the file read-only (RustProxy never writes it) and keep `/var/lib/rustproxy` on a volume for certificates, secrets and the optional COLD cache. Backends in the same Compose network can be addressed by service name, for example `http://app-1:3001`. Give each replica its own service and backend entry: one name that resolves to several container addresses is treated as a single backend.
## Health endpoint
`GET /healthz` on `--health-listen` answers `200` while every vhost with backends has at least one healthy backend and `503` otherwise:
```json
{"status":"ok","mode":"headless","version":"0.38.0","revision":4,"uptime_seconds":120,
"last_reload":{"ok":true,"at_unix":1794743660,"error":null},
"vhosts_without_healthy_backends":[],
"pools":[{"vhost":"app","healthy":3,"backends":3}]}
```
`last_reload` reports the result of the last reload (`null` before the first one). Keep the listener on loopback or a private network.
## Limits
- No panel, live logs (`--livelogs`), configuration history browser or cache invalidation API. Use stored log files, the journal and Prometheus instead; HTTP `PURGE`/`BAN` from allowed addresses still works for the cache.
- Certificates with ACME auto-renewal are refused; renew externally and reference the files in `cert_file` / `key_file`. A replaced certificate file is loaded on the next reload.
- To manage a headless file in the panel later, first add `listeners` and every `listener_ids` explicitly (panel mode requires them and enables GeoIP downloads by default), then restart without `RUST_PROXY_HEADLESS`, create the administrator and keep `--config`: panel saves then write the complete configuration to the file.
+2
View File
@@ -230,6 +230,8 @@ This is **optional**. Without `--config`, RustProxy keeps its active configurati
Confirm in **Settings → Manual config** that the source is **JSON file** and the path is `/etc/rustproxy/config.json`. Save a harmless edit and confirm that the file is rewritten and readable by `rustproxy`; check that a revision appears in SQLite. To import a deliberate external file edit without restarting, run `sudo systemctl reload rustproxy` (if the unit has `ExecReload`) or `rust-proxy --data-dir /var/lib/rustproxy --admin-listen 127.0.0.1:9090 config reload`. The file is not watched automatically. An incompatible external edit must fail validation rather than silently overwrite the live configuration.
To run without the panel at all, configured only from that file, see [Headless mode](HEADLESS.md).
For the alternate environment-variable method, set `RUST_PROXY_CONFIG=/etc/rustproxy/config.json` in the service's protected EnvironmentFile. Do not set **both** unrelated config paths. See [Configuration](CONFIGURATION.md) and the [deployment example](../deploy/README.md).
## Docker / OCI container
+1
View File
@@ -16,6 +16,7 @@ Guides for operating RustProxy: installation, publishing services, security, cer
- [Installation and updates](INSTALL.md) — packages, source build, Docker image, first administrator, systemd and updates.
- [Configuration](CONFIGURATION.md) — SQLite or JSON configuration source, configuration map and changes that need a restart.
- [Headless mode](HEADLESS.md) — proxy and load balancer configured only from a JSON file, without the panel.
- [Troubleshooting](TROUBLESHOOTING.md) — symptom-based checks and a rollout checklist.
## Publishing services
+1 -1
View File
@@ -4,7 +4,7 @@ A **Vhost** publishes one or more hostnames on named HTTP/HTTPS listeners. Its s
## Publish a site
1. Enter an ID and the exact domain (`app.example.com`) or supported wildcard (`*.example.com`). Exact names win over wildcards. Configure DNS independently.
1. Enter an ID and the exact domain (`app.example.com`) or supported wildcard (`*.example.com`). Exact names win over wildcards. Configure DNS independently. A host of just `*` (since 0.38.0) is a catch-all: the Vhost answers every hostname and IP address on its listeners that no exact or wildcard host claims, which is handy for a server without a domain. Over HTTPS such requests receive the default certificate; a catch-all host is never assigned to a certificate.
2. Choose the enabled HTTP/HTTPS frontend listeners. Select a certificate for HTTPS.
3. Choose **Reverse Proxy** and add an upstream address such as `http://10.0.0.20:3000`, or select an existing **Web Service**.
4. Check backend reachability and TLS policy; configure health checks and load balancing for multiple origins.
+48
View File
@@ -0,0 +1,48 @@
{
"vhosts": [
{
"id": "app",
"websockets": true,
"frontend": {
"hosts": [
"*"
]
},
"backends": [
{
"id": "app-1",
"url": "http://127.0.0.1:3101",
"allow_private": true
},
{
"id": "app-2",
"url": "http://127.0.0.1:3102",
"allow_private": true
},
{
"id": "app-3",
"url": "http://127.0.0.1:3103",
"allow_private": true
}
],
"load_balancing": {
"algorithm": "round_robin",
"health_check": {
"mode": "http",
"path": "/health",
"interval_ms": 5000,
"timeout_ms": 2000,
"fall": 2,
"rise": 1
}
},
"cache": {
"enabled": true
}
}
],
"cache": {
"enabled": true,
"max_bytes": 268435456
}
}
+359
View File
@@ -0,0 +1,359 @@
{
"listeners": {
"endpoints": [
{
"id": "http",
"name": "HTTP",
"scope": "public",
"enabled": true,
"binding": {
"address": "0.0.0.0:80",
"tls": false,
"http2": false
}
},
{
"id": "https",
"name": "HTTPS",
"scope": "public",
"enabled": true,
"binding": {
"address": "0.0.0.0:443",
"tls": true,
"http2": true,
"http3": {}
}
}
]
},
"tls": {
"default_certificate": "app",
"certificates": [
{
"id": "app",
"hosts": [
"app.example.com",
"www.app.example.com"
],
"cert_file": "app.pem",
"key_file": "app.key"
}
]
},
"cache": {
"enabled": true,
"max_bytes": 536870912,
"max_object_bytes": 16777216,
"max_entries": 16384,
"cold_enabled": true,
"cold_path": "cache/cold",
"cold_max_bytes": 10737418240,
"cold_max_entries": 100000,
"default_ttl_seconds": 0,
"max_ttl_seconds": 86400,
"varnish_grace_seconds": 60,
"bypass_prefixes": [
"/api/",
"/admin/",
"/login"
],
"static_ignore_cookies": true,
"collapse_enabled": true,
"stale_if_error_timeout": true,
"stale_if_error_connection": true,
"stale_if_error_statuses": [
500,
502,
503,
504
],
"expose_status": true,
"rules": [
{
"id": "strip-tracking",
"name": "Ignore tracking parameters",
"enabled": true,
"stage": "request",
"match": "all",
"conditions": [],
"actions": [
{
"type": "strip_query",
"params": [
"utm_*",
"fbclid",
"gclid",
"msclkid",
"_ga"
]
}
]
},
{
"id": "static-30d",
"name": "Static files: 30 days in cache and browser",
"enabled": true,
"stage": "response",
"match": "all",
"conditions": [
{
"field": "extension",
"operator": "equals",
"values": [
"css",
"js",
"mjs",
"woff2",
"woff",
"svg",
"png",
"jpg",
"jpeg",
"webp",
"avif",
"ico"
]
}
],
"actions": [
{
"type": "ttl",
"seconds": 2592000
}
]
},
{
"id": "static-browser",
"name": "Browser cache for static files",
"enabled": true,
"stage": "deliver",
"match": "all",
"conditions": [
{
"field": "extension",
"operator": "equals",
"values": [
"css",
"js",
"mjs",
"woff2",
"woff",
"svg",
"png",
"jpg",
"jpeg",
"webp",
"avif",
"ico"
]
}
],
"actions": [
{
"type": "default_header",
"name": "Cache-Control",
"value": "public, max-age=2592000"
}
]
},
{
"id": "hide-powered-by",
"name": "Hide X-Powered-By",
"enabled": true,
"stage": "deliver",
"match": "all",
"conditions": [],
"actions": [
{
"type": "remove_header",
"name": "X-Powered-By"
}
]
}
]
},
"compression": {
"gzip": true,
"br": true,
"zstd": true,
"deflate": false,
"min_bytes": 1024
},
"logging": {
"file": {
"enabled": true,
"path": "/var/log/rustproxy/access.jsonl",
"per_vhost": false,
"directory": "/var/log/rustproxy/vhosts"
}
},
"prometheus": {
"enabled": true,
"listen": "127.0.0.1:9191",
"path": "/metrics",
"allowed_cidrs": [
"127.0.0.0/8",
"10.0.0.0/8"
],
"bearer_token_env": "RUSTPROXY_METRICS_TOKEN"
},
"vhosts": [
{
"id": "app",
"websockets": true,
"force_ssl": true,
"forward_client_ip": true,
"frontend": {
"hosts": [
"app.example.com",
"www.app.example.com"
]
},
"www_redirect": true,
"www_redirect_target": "app.example.com",
"backends": [
{
"id": "app-1",
"url": "http://10.0.0.11:3001",
"allow_private": true,
"protocol": "http1"
},
{
"id": "app-2",
"url": "http://10.0.0.12:3001",
"allow_private": true,
"protocol": "http1"
},
{
"id": "app-3",
"url": "http://10.0.0.13:3001",
"allow_private": true,
"protocol": "http1"
},
{
"id": "app-4",
"url": "http://10.0.0.14:3001",
"allow_private": true,
"protocol": "http1"
},
{
"id": "app-5",
"url": "http://10.0.0.15:3001",
"allow_private": true,
"protocol": "http1"
},
{
"id": "app-6",
"url": "http://10.0.0.16:3001",
"allow_private": true,
"protocol": "http1"
},
{
"id": "app-7",
"url": "http://10.0.0.17:3001",
"allow_private": true,
"protocol": "http1"
},
{
"id": "app-8",
"url": "http://10.0.0.18:3001",
"allow_private": true,
"protocol": "http1"
},
{
"id": "app-9",
"url": "http://10.0.0.19:3001",
"allow_private": true,
"protocol": "http1"
},
{
"id": "app-10",
"url": "http://10.0.0.20:3001",
"allow_private": true,
"protocol": "http1"
}
],
"load_balancing": {
"algorithm": "least_connections",
"health_check": {
"mode": "http",
"path": "/health",
"interval_ms": 5000,
"timeout_ms": 2000,
"fall": 2,
"rise": 1,
"expected_status_min": 200,
"expected_status_max": 299
},
"passive_health": {
"enabled": true
},
"keepalive": {
"enabled": true,
"idle_timeout_seconds": 60,
"max_idle_per_host": 32
},
"retry": {
"max_retries": 1,
"retry_connect_errors": true,
"retry_timeouts": false,
"retry_statuses": [
502,
503
]
}
},
"proxy_timeouts": {
"connect_timeout_seconds": 3,
"response_header_timeout_seconds": 120,
"read_timeout_seconds": 300,
"send_timeout_seconds": 300
},
"cache": {
"enabled": true
},
"security_headers": {
"hsts": {
"enabled": true,
"max_age_seconds": 31536000,
"include_subdomains": false,
"preload": false
},
"nosniff": true,
"frame_options": "sameorigin",
"referrer_policy": "strict-origin-when-cross-origin"
},
"rate_limit": {
"enabled": true,
"requests": 600,
"window_seconds": 60,
"burst": 120
},
"routes": [
{
"id": "admin",
"path_prefix": "/admin",
"cache": false,
"acl": {
"default": "deny",
"rules": [
{
"network": "10.0.0.0/8",
"action": "allow"
},
{
"network": "192.168.0.0/16",
"action": "allow"
}
]
}
},
{
"id": "api",
"path_prefix": "/api",
"cache": false
}
]
}
]
}
+2 -2
View File
@@ -77,10 +77,10 @@ ENV_FILE=integrations/routeros-oci-build/.env \
bash integrations/routeros-oci-build/build-routeros-oci.sh push
```
For example, with RustProxy version `0.37.3` and the defaults this publishes:
For example, with RustProxy version `0.38.0` and the defaults this publishes:
```text
oci.example.net/network/rustproxy:0.37.3
oci.example.net/network/rustproxy:0.38.0
oci.example.net/network/rustproxy:latest
oci.example.net/network/rustproxy:routeros
```
+1
View File
@@ -17,6 +17,7 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[
reader_doc!("docs/SCREENSHOTS.md", "guides"),
reader_doc!("docs/INSTALL.md", "guides"),
reader_doc!("docs/CONFIGURATION.md", "guides"),
reader_doc!("docs/HEADLESS.md", "guides"),
reader_doc!("docs/VHOSTS.md", "guides"),
reader_doc!("docs/CUSTOM_LOCATIONS.md", "guides"),
reader_doc!("docs/ACCESS.md", "guides"),
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.0.3",
"info": {
"title": "RustProxy Administration API",
"version": "0.37.3",
"version": "0.38.0",
"description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only."
},
"servers": [
+2 -2
View File
@@ -619,7 +619,7 @@ function render() {
identity.append(title, el("div", (v.frontend?.hosts || []).join(", ") || "-", "vhost-hosts")); head.append(identity);
const actions = el("div", undefined, "entity-actions");
const configuredHosts = (v.frontend?.hosts || []).filter(Boolean);
const browseHost = configuredHosts.find(host => !host.startsWith("*.")) || configuredHosts.find(host => host.startsWith("*."))?.slice(2) || null;
const browseHost = configuredHosts.find(host => !host.startsWith("*")) || configuredHosts.find(host => host.startsWith("*."))?.slice(2) || null;
const configuredEndpoints = (v.frontend?.listener_ids || []).map(id => config.listeners?.endpoints?.find(endpoint => endpoint.id === id)).filter(Boolean);
const browseTls = configuredEndpoints.some(endpoint => endpoint.binding?.tls === true);
const openButton = button("vhOpenBrowser", () => { if (browseHost) window.open(`${browseTls ? "https" : "http"}://${browseHost}/`, "_blank", "noopener,noreferrer"); });
@@ -701,7 +701,7 @@ function render() {
if (v.acl_profile_id) policy.append(el("small", `${t("vhAclProfile")}: ${v.acl_profile_id}`, "pill"));
if (v.force_ssl) policy.append(el("small", t("vhForceSsl"), "pill"));
if (v.www_redirect) {
const destination = v.www_redirect_target || (v.frontend?.hosts || []).find(host => !host.startsWith("*.")) || "";
const destination = v.www_redirect_target || (v.frontend?.hosts || []).find(host => !host.startsWith("*")) || "";
policy.append(el("small", `WWW 308 \u2192 ${destination}`, "pill"));
}
if (v.forward_client_ip === false) policy.append(el("small", t("vhClientIpHidden"), "pill"));
+1 -1
View File
@@ -178,7 +178,7 @@ fn compile_routing(
.hosts
.iter()
.find(|name| {
!name.starts_with("*.") && name.parse::<std::net::IpAddr>().is_err()
!name.starts_with('*') && name.parse::<std::net::IpAddr>().is_err()
})
.cloned();
}
+13 -2
View File
@@ -3,7 +3,9 @@ impl Snapshot {
if let Some(value) = lookup(host) {
return Some(value);
}
let last_dot = host.rfind('.')?;
let Some(last_dot) = host.rfind('.') else {
return lookup(CATCH_ALL_HOST);
};
let mut wildcard = [0u8; 256];
wildcard[..2].copy_from_slice(b"*.");
for (index, _) in host.match_indices('.') {
@@ -23,7 +25,7 @@ impl Snapshot {
return Some(value);
}
}
None
lookup(CATCH_ALL_HOST)
}
pub fn host_allowed(&self, host: &str, peer: IpAddr) -> bool {
if self.host_acls.is_empty() {
@@ -431,6 +433,15 @@ pub fn normalize_host(value: &str) -> Result<String> {
);
Ok(host)
}
pub const CATCH_ALL_HOST: &str = "*";
pub fn normalize_frontend_host(value: &str) -> Result<String> {
if value.trim() == CATCH_ALL_HOST {
return Ok(CATCH_ALL_HOST.into());
}
normalize_host_pattern(value)
}
pub fn normalize_host_pattern(value: &str) -> Result<String> {
let value = value.trim();
if let Some(base) = value.strip_prefix("*.") {
+27
View File
@@ -25,6 +25,33 @@ mod tests {
config
}
#[test]
fn catch_all_host_serves_unmatched_names_after_exact_and_wildcard_hosts() {
let mut config = demo_config("127.0.0.1:9000".parse().unwrap());
let mut catch_all = config.vhosts[0].clone();
catch_all.id = "catch-all".into();
catch_all.frontend.hosts = vec![" * ".into()];
config.vhosts.push(catch_all);
let snapshot = compile(config, 1, &policy()).unwrap();
let local = "127.0.0.1:8080".parse().unwrap();
let vhost = |host: &str| snapshot.frontend(host, local, false).map(|f| f.id.clone());
assert_eq!(vhost("localhost").as_deref(), Some("demo"));
assert_eq!(vhost("demo.localhost").as_deref(), Some("demo"));
for host in ["192.168.1.50", "app.example.org", "intranet"] {
assert_eq!(vhost(host).as_deref(), Some("catch-all"), "{host}");
assert!(snapshot.select_on(host, "/", local, false).is_some());
}
}
#[test]
fn catch_all_host_is_only_valid_alone() {
let mut config = demo_config("127.0.0.1:9000".parse().unwrap());
config.vhosts[0].frontend.hosts = vec!["*.*".into()];
assert!(compile(config.clone(), 1, &policy()).is_err());
config.vhosts[0].frontend.hosts = vec!["*".into(), "*".into()];
assert!(compile(config, 1, &policy()).is_err());
}
#[test]
fn configuration_above_legacy_limit_compiles() {
let config = config_with_large_responses(5);
+1
View File
@@ -9,4 +9,5 @@ include!("main/bootstrap.rs");
include!("main/admin_runtime.rs");
include!("main/proxy_runtime.rs");
include!("main/tasks.rs");
include!("main/headless.rs");
include!("main/shutdown/mod.rs");
+131 -40
View File
@@ -5,11 +5,34 @@ async fn run(
file_config: Option<PathBuf>,
startup_locks: rust_proxy::settings::StartupLocks,
update_check: rust_proxy::update_check::Config,
headless: bool,
) -> Result<()> {
ensure!(
startup_admin_addr.port() > 0 && options.proxy_listen.port() > 0,
"listener ports must be nonzero"
);
if headless {
ensure!(
file_config.is_some(),
"--headless requires --config /absolute/path/config.json (or RUST_PROXY_CONFIG)"
);
ensure!(!options.demo, "--headless cannot be combined with --demo");
rust_proxy::runtime::enable_headless(rust_proxy::settings::Listeners::from_startup(
options.proxy_listen,
options.tls_listen,
));
}
if let Some(health) = options.health_listen {
ensure!(
health.port() > 0
&& health.port() != options.proxy_listen.port()
&& options
.tls_listen
.is_none_or(|tls| tls.port() != health.port())
&& (headless || health.port() != startup_admin_addr.port()),
"health listener port must be nonzero and differ from the other listeners"
);
}
ensure!(
(1..=4096).contains(&options.max_connections) && (1..=4096).contains(&options.max_inflight),
"limits must be 1..4096"
@@ -22,14 +45,14 @@ async fn run(
"timeouts must be positive"
);
ensure!(
startup_admin_addr.port() != options.proxy_listen.port(),
headless || startup_admin_addr.port() != options.proxy_listen.port(),
"admin and proxy ports must differ"
);
if let Some(tls) = options.tls_listen {
ensure!(
tls.port() > 0
&& tls.port() != options.proxy_listen.port()
&& tls.port() != startup_admin_addr.port(),
&& (headless || tls.port() != startup_admin_addr.port()),
"TLS listener port must be nonzero and differ from HTTP/admin"
);
}
@@ -75,10 +98,13 @@ async fn run(
let store = Store::open(&data_dir.join("config.sqlite3"), &initial).await?;
let mut saved = store.load().await?;
let external = if let Some(path) = file_config {
Some((
path.clone(),
rust_proxy::runtime::external_config::read(&path)?,
))
let loaded = match rust_proxy::runtime::headless_listeners() {
Some(listeners) => {
rust_proxy::runtime::external_config::read_headless(&path, listeners)?
}
None => rust_proxy::runtime::external_config::read(&path)?,
};
Some((path.clone(), loaded))
} else {
None
};
@@ -87,6 +113,9 @@ async fn run(
if let Some((_, (config, _))) = &external {
saved.config = config.clone();
}
if headless {
rust_proxy::runtime::ensure_headless_supported(&saved.config)?;
}
startup_locks.ensure_config(&mut saved.config);
let changed_on_disk =
external.is_some() && serde_json::to_value(&saved.config)? != stored_document;
@@ -100,15 +129,16 @@ async fn run(
.config
.administration
.resolved_listen(startup_admin_addr);
let admin_tls_enabled = saved.config.administration.tls;
let remote_admin =
validate_admin_binding(admin_addr, admin_tls_enabled, options.allow_remote_admin)?;
let admin_tls_enabled = saved.config.administration.tls && !headless;
let remote_admin = !headless
&& validate_admin_binding(admin_addr, admin_tls_enabled, options.allow_remote_admin)?;
ensure!(
admin_addr.port() != options.proxy_listen.port()
&& options
.tls_listen
.is_none_or(|tls| tls.port() != admin_addr.port())
&& (!options.demo || options.demo_listen.port() != admin_addr.port()),
headless
|| admin_addr.port() != options.proxy_listen.port()
&& options
.tls_listen
.is_none_or(|tls| tls.port() != admin_addr.port())
&& (!options.demo || options.demo_listen.port() != admin_addr.port()),
"active administration port conflicts with another startup listener"
);
let resolved_policy = ValidationPolicy {
@@ -154,7 +184,9 @@ async fn run(
);
}
rust_proxy::logging::configure_error_log(snapshot.envelope.config.error_log.clone());
let admin_tls_config = {
let admin_tls_config = if headless {
None
} else {
let tls = snapshot.envelope.config.tls.clone();
let administration = snapshot.envelope.config.administration.clone();
let cert_dir = policy.cert_dir.clone();
@@ -165,7 +197,7 @@ async fn run(
};
let setup_required = store.admin_record().await?.is_none();
let authentication = auth::Auth::new(store.clone(), data_dir.clone()).await?;
if !setup_required {
if !setup_required || headless {
authentication.remove_bootstrap_files().await;
}
let renewal_observations = store.load_certificate_renewals().await?;
@@ -175,6 +207,10 @@ async fn run(
geoip_format,
) {
Ok(database) => std::sync::Arc::new(database),
Err(error) if headless && !snapshot.envelope.config.geoip_updates.enabled => {
tracing::debug!(%error, "GeoIP country database not installed");
std::sync::Arc::new(rust_proxy::geoip::Database::empty())
}
Err(error) => {
tracing::warn!(%error, "GeoIP country database unavailable; country allow lists fail closed");
std::sync::Arc::new(rust_proxy::geoip::Database::empty())
@@ -273,9 +309,23 @@ async fn run(
} else {
None
};
let admin_listener = TcpListener::bind(admin_addr)
.await
.context("cannot bind admin listener")?;
let admin_listener = if headless {
None
} else {
Some(
TcpListener::bind(admin_addr)
.await
.context("cannot bind admin listener")?,
)
};
let health_listener = match options.health_listen {
Some(address) => Some(
TcpListener::bind(address)
.await
.with_context(|| format!("cannot bind health listener {address}"))?,
),
None => None,
};
let demo_listener = if options.demo {
Some(
TcpListener::bind(options.demo_listen)
@@ -287,7 +337,9 @@ async fn run(
};
state.start_geoip_updates();
state.start_dns_acl_updates();
state.start_update_check(update_check);
if !headless {
state.start_update_check(update_check);
}
let shutdown = state.shutdown.clone();
let grace = Duration::from_secs(options.shutdown_timeout_secs);
let mut tasks = JoinSet::new();
@@ -332,26 +384,46 @@ async fn run(
metrics,
));
}
if let Some(tls) = admin_tls_config {
tasks.spawn(rust_proxy::server::serve_tls_with_plain_redirect(
admin_listener,
rust_proxy::admin::router(state.clone()),
rust_proxy::admin::https_redirect_router(),
shutdown.clone(),
32,
grace,
tls,
));
} else {
if let Some(listener) = health_listener {
tasks.spawn(rust_proxy::server::serve(
admin_listener,
rust_proxy::admin::router(state.clone()),
listener,
rust_proxy::runtime::health_router(state.clone()),
shutdown.clone(),
32,
16,
grace,
None,
));
}
let _pid_file = if headless {
Some(HeadlessPidFile::create(&data_dir)?)
} else {
None
};
if headless {
tasks.spawn(headless_reload_loop(state.clone(), shutdown.clone()));
}
if let Some(admin_listener) = admin_listener {
if let Some(tls) = admin_tls_config {
tasks.spawn(rust_proxy::server::serve_tls_with_plain_redirect(
admin_listener,
rust_proxy::admin::router(state.clone()),
rust_proxy::admin::https_redirect_router(),
shutdown.clone(),
32,
grace,
tls,
));
} else {
tasks.spawn(rust_proxy::server::serve(
admin_listener,
rust_proxy::admin::router(state.clone()),
shutdown.clone(),
32,
grace,
None,
));
}
}
if let Some(listener) = metrics_listener {
tasks.spawn(rust_proxy::server::serve(
listener,
@@ -403,10 +475,26 @@ async fn run(
stream.id
);
}
println!(
" Panel: {}://{admin_addr}",
if admin_tls_enabled { "https" } else { "http" }
);
if headless {
if let Some(path) = state
.config_file
.lock()
.await
.as_ref()
.map(|(path, _)| path.clone())
{
println!(" Mode: headless, configuration {}", path.display());
}
println!(
" Reload: systemctl reload rustproxy, kill -HUP {}, or rust-proxy --headless reload",
std::process::id()
);
} else {
println!(
" Panel: {}://{admin_addr}",
if admin_tls_enabled { "https" } else { "http" }
);
}
if remote_admin && !admin_tls_enabled {
tracing::warn!(
"REMOTE ADMIN ENABLED OVER PLAIN HTTP: credentials and session cookies can be exposed; restrict access with a firewall/private network and prefer a protected tunnel"
@@ -418,7 +506,10 @@ async fn run(
state.active_prometheus.listen, state.active_prometheus.path
);
}
if setup_required {
if let Some(address) = options.health_listen {
println!(" Health: http://{address}/healthz");
}
if !headless && setup_required {
println!(
" Setup: rust-proxy --data-dir {} admin setup-token",
data_dir.display()
@@ -427,7 +518,7 @@ async fn run(
" Or: rust-proxy --data-dir {} admin init --username YOUR_NAME",
data_dir.display()
);
} else {
} else if !headless {
println!(" Sign in with your administrator account.");
}
println!(" Source: https://git.linuxiarz.pl/gru/RustProxy");
+29
View File
@@ -70,6 +70,14 @@ struct Cli {
_accept_remote_admin_risk: bool,
#[arg(long, global = true)]
livelogs: bool,
#[arg(
long,
global = true,
env = "RUST_PROXY_HEADLESS",
action = clap::ArgAction::SetTrue,
value_parser = clap::builder::BoolishValueParser::new()
)]
headless: bool,
#[command(subcommand)]
command: Option<Command>,
}
@@ -183,6 +191,8 @@ struct ServeOptions {
shutdown_timeout_secs: u64,
#[arg(long)]
allow_remote_admin: bool,
#[arg(long, env = "RUST_PROXY_HEALTH_LISTEN")]
health_listen: Option<SocketAddr>,
}
#[cfg(target_os = "linux")]
fn disable_transparent_huge_pages() {
@@ -316,6 +326,24 @@ async fn application() -> Result<()> {
.command
.context("a subcommand is required (or use --livelogs)")?;
match command {
Command::Reload if cli.headless => {
signal_headless_reload(&resolve_installed_data_dir(cli.data_dir, data_dir_explicit))
}
Command::Config {
action: ConfigCommand::Reload,
} if cli.headless => {
signal_headless_reload(&resolve_installed_data_dir(cli.data_dir, data_dir_explicit))
}
Command::Config {
action: ConfigCommand::Validate { file },
} if cli.headless => {
validate_headless_file(
resolve_installed_data_dir(cli.data_dir, data_dir_explicit),
cli.admin_listen,
file,
)
.await
}
Command::Reload => {
config_command(
resolve_installed_data_dir(cli.data_dir, data_dir_explicit),
@@ -374,6 +402,7 @@ async fn application() -> Result<()> {
cli.config,
startup_locks,
update_check,
cli.headless,
)
.await
}
+169
View File
@@ -0,0 +1,169 @@
const HEADLESS_PID_FILE: &str = "rustproxy.pid";
struct HeadlessPidFile(PathBuf);
impl HeadlessPidFile {
fn create(data_dir: &Path) -> Result<Self> {
let path = data_dir.join(HEADLESS_PID_FILE);
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
}
let mut file = options
.open(&path)
.with_context(|| format!("cannot write {}", path.display()))?;
writeln!(file, "{}", std::process::id())?;
Ok(Self(path))
}
}
impl Drop for HeadlessPidFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
async fn headless_reload_loop(
state: Arc<App>,
shutdown: tokio_util::sync::CancellationToken,
) -> Result<()> {
#[cfg(unix)]
{
let mut hangup = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())?;
loop {
tokio::select! {
_ = shutdown.cancelled() => return Ok(()),
_ = hangup.recv() => {
let revision = state.config.load().envelope.revision;
match state.reload_from_file(revision).await {
Ok(envelope) => {
rust_proxy::runtime::record_headless_reload(None);
tracing::info!(
revision = envelope.revision,
"headless configuration reloaded; listener changes need a restart"
)
}
Err(error) => {
rust_proxy::runtime::record_headless_reload(Some(error.1.clone()));
tracing::error!(
error = %error.1,
"headless configuration reload rejected; the running configuration is unchanged"
)
}
}
}
}
}
}
#[cfg(not(unix))]
{
let _ = state;
shutdown.cancelled().await;
Ok(())
}
}
fn signal_headless_reload(data_dir: &Path) -> Result<()> {
let path = data_dir.join(HEADLESS_PID_FILE);
let text = std::fs::read_to_string(&path).with_context(|| {
format!(
"{} not found; is rust-proxy serve --headless running with --data-dir {}?",
path.display(),
data_dir.display()
)
})?;
let pid: i32 = text
.trim()
.parse()
.with_context(|| format!("invalid process id in {}", path.display()))?;
ensure!(pid > 1, "invalid process id in {}", path.display());
#[cfg(target_os = "linux")]
{
let command = std::fs::read(format!("/proc/{pid}/cmdline")).unwrap_or_default();
ensure!(
String::from_utf8_lossy(&command).contains("rust-proxy"),
"process {pid} from {} is not a running RustProxy; remove the stale file",
path.display()
);
}
#[cfg(unix)]
{
let result = unsafe { libc::kill(pid, libc::SIGHUP) };
ensure!(
result == 0,
"cannot signal RustProxy process {pid}: {}",
io::Error::last_os_error()
);
println!(
"Reload requested (SIGHUP to process {pid}); the result is written to the service log."
);
Ok(())
}
#[cfg(not(unix))]
{
let _ = pid;
bail!("headless reload by signal is only available on Unix")
}
}
async fn validate_headless_file(
data_dir: PathBuf,
admin_addr: SocketAddr,
file: PathBuf,
) -> Result<()> {
let proxy_addr: SocketAddr = std::env::var("RUST_PROXY_PROXY_LISTEN")
.unwrap_or_else(|_| "127.0.0.1:8080".into())
.parse()?;
let tls_addr: Option<SocketAddr> = std::env::var("RUST_PROXY_TLS_LISTEN")
.ok()
.filter(|value| !value.is_empty())
.map(|value| value.parse())
.transpose()?;
let listeners = rust_proxy::settings::Listeners::from_startup(proxy_addr, tls_addr);
let file = if file.is_absolute() {
file
} else {
std::env::current_dir()?.join(file)
};
let (config, _) = tokio::task::spawn_blocking(move || {
rust_proxy::runtime::external_config::read_headless(&file, &listeners)
})
.await??;
rust_proxy::runtime::ensure_headless_supported(&config)?;
let cert_path = data_dir.join("certs");
let scratch = if cert_path.is_dir() {
None
} else {
let scratch = std::env::temp_dir().join(format!(
"rustproxy-validate-{}",
rust_proxy::auth::random_secret()
));
let directory = scratch.clone();
tokio::task::spawn_blocking(move || rust_proxy::tls::initialize_default(&directory))
.await??;
Some(scratch)
};
let policy = ValidationPolicy {
proxy_addr,
admin_addr,
tls_addr,
cert_dir: Some(scratch.clone().unwrap_or(cert_path)),
data_dir: Some(data_dir),
};
let compiled = tokio::task::spawn_blocking(move || config::compile(config, 0, &policy)).await?;
if let Some(scratch) = scratch {
let _ = std::fs::remove_dir_all(scratch);
}
let snapshot = compiled?;
let config = &snapshot.envelope.config;
println!(
"Headless configuration valid: {} listener(s), {} vhost(s), {} backend(s). Nothing was changed.",
config.listeners.endpoints.len(),
config.vhosts.len(),
config.vhosts.iter().map(|vhost| vhost.backends.len()).sum::<usize>()
);
Ok(())
}
+2
View File
@@ -4,6 +4,8 @@ include!("runtime/constructors.rs");
include!("runtime/updates.rs");
include!("runtime/certificates.rs");
include!("runtime/docker.rs");
include!("runtime/headless.rs");
include!("runtime/health_endpoint.rs");
#[cfg(test)]
include!("runtime/tests.rs");
+9 -7
View File
@@ -203,13 +203,15 @@ impl App {
let shutdown = app.shutdown.clone();
app.tunnels
.spawn(crate::balance::health_loop(weak, shutdown));
app.tunnels.spawn(crate::acme::renewal_loop(
Arc::downgrade(&app),
app.shutdown.clone(),
));
if !cfg!(test) {
app.tunnels
.spawn(crate::acme::runtime_setup_once(Arc::downgrade(&app)));
if !headless_enabled() {
app.tunnels.spawn(crate::acme::renewal_loop(
Arc::downgrade(&app),
app.shutdown.clone(),
));
if !cfg!(test) {
app.tunnels
.spawn(crate::acme::runtime_setup_once(Arc::downgrade(&app)));
}
}
app.tunnels.spawn(crate::docker::poll_loop(
Arc::downgrade(&app),
+79 -4
View File
@@ -10,6 +10,77 @@ use std::{
pub type Fingerprint = [u8; 32];
pub fn read(path: &Path) -> Result<(Config, Fingerprint)> {
let (contents, fingerprint) = read_bytes(path)?;
let config = serde_json::from_slice(&contents).context("invalid --config JSON")?;
Ok((config, fingerprint))
}
pub fn fingerprint(path: &Path) -> Result<Fingerprint> {
Ok(read_bytes(path)?.1)
}
pub fn read_headless(
path: &Path,
listeners: &crate::settings::Listeners,
) -> Result<(Config, Fingerprint)> {
let (contents, fingerprint) = read_bytes(path)?;
Ok((headless_config(&contents, listeners)?, fingerprint))
}
pub fn headless_config(contents: &[u8], listeners: &crate::settings::Listeners) -> Result<Config> {
let mut value: serde_json::Value =
serde_json::from_slice(contents).context("invalid --config JSON")?;
let object = value
.as_object_mut()
.context("configuration file must contain a JSON object")?;
let declared = object
.get("listeners")
.and_then(|item| item.get("endpoints"))
.and_then(serde_json::Value::as_array)
.is_some_and(|endpoints| !endpoints.is_empty());
if !declared {
object.insert("listeners".into(), serde_json::to_value(listeners)?);
}
let listener_ids: Vec<serde_json::Value> = object
.get("listeners")
.and_then(|item| item.get("endpoints"))
.and_then(serde_json::Value::as_array)
.map(|endpoints| {
endpoints
.iter()
.filter(|endpoint| {
endpoint
.get("enabled")
.and_then(serde_json::Value::as_bool)
.unwrap_or(true)
})
.filter_map(|endpoint| endpoint.get("id").cloned())
.collect()
})
.unwrap_or_default();
for section in ["vhosts", "redirects", "not_found_hosts"] {
let Some(items) = object
.get_mut(section)
.and_then(serde_json::Value::as_array_mut)
else {
continue;
};
for frontend in items.iter_mut().filter_map(|item| {
item.get_mut("frontend")
.and_then(serde_json::Value::as_object_mut)
}) {
frontend
.entry("listener_ids")
.or_insert_with(|| serde_json::Value::Array(listener_ids.clone()));
}
}
object
.entry("geoip_updates")
.or_insert_with(|| serde_json::json!({ "enabled": false }));
serde_json::from_value(value).context("invalid --config JSON")
}
fn read_bytes(path: &Path) -> Result<(Vec<u8>, Fingerprint)> {
ensure!(path.is_absolute(), "--config requires an absolute filename");
let mut options = fs::OpenOptions::new();
options.read(true);
@@ -33,12 +104,16 @@ pub fn read(path: &Path) -> Result<(Config, Fingerprint)> {
contents.len() <= MAX_CONFIG_BYTES,
"configuration file exceeds size limit"
);
let config = serde_json::from_slice(&contents).context("invalid --config JSON")?;
Ok((config, Sha256::digest(&contents).into()))
let fingerprint = Sha256::digest(&contents).into();
Ok((contents, fingerprint))
}
pub fn save(path: &Path, expected: Fingerprint, config: &Config) -> Result<Fingerprint> {
let (_, actual) = read(path)?;
ensure!(
!crate::runtime::headless_enabled(),
"headless mode never writes the configuration file"
);
let actual = fingerprint(path)?;
if actual != expected {
bail!("configuration file changed externally; reload before saving");
}
@@ -69,7 +144,7 @@ pub fn save(path: &Path, expected: Fingerprint, config: &Config) -> Result<Finge
let mut file = options.open(&temp)?;
file.write_all(&bytes)?;
file.sync_all()?;
if read(path)?.1 != expected {
if fingerprint(path)? != expected {
bail!("configuration file changed during save");
}
fs::rename(&temp, path)?;
+43
View File
@@ -0,0 +1,43 @@
static HEADLESS: std::sync::OnceLock<crate::settings::Listeners> = std::sync::OnceLock::new();
pub fn enable_headless(listeners: crate::settings::Listeners) -> bool {
HEADLESS.set(listeners).is_ok()
}
pub fn headless_enabled() -> bool {
HEADLESS.get().is_some()
}
pub fn headless_listeners() -> Option<&'static crate::settings::Listeners> {
HEADLESS.get()
}
pub fn ensure_headless_supported(config: &config::Config) -> anyhow::Result<()> {
if let Some(certificate) = config.tls.certificates.iter().find(|certificate| {
certificate
.issuer
.as_ref()
.is_some_and(|issuer| issuer.auto_renew)
}) {
anyhow::bail!(
"certificate {} uses ACME auto-renewal, which needs the administration panel; in headless mode renew it externally (for example with certbot) and reference the files in cert_file/key_file",
certificate.id
);
}
Ok(())
}
static LAST_RELOAD: std::sync::Mutex<Option<(i64, Option<String>)>> = std::sync::Mutex::new(None);
pub fn record_headless_reload(error: Option<String>) {
if let Ok(mut slot) = LAST_RELOAD.lock() {
*slot = Some((crate::auth::now(), error));
}
}
fn last_headless_reload() -> serde_json::Value {
match LAST_RELOAD.lock().ok().and_then(|slot| slot.clone()) {
Some((at, error)) => json!({ "ok": error.is_none(), "at_unix": at, "error": error }),
None => serde_json::Value::Null,
}
}
+54
View File
@@ -0,0 +1,54 @@
pub fn health_router(state: Arc<App>) -> axum::Router {
axum::Router::new()
.route("/healthz", axum::routing::get(health_status))
.with_state(state)
}
async fn health_status(axum::extract::State(state): axum::extract::State<Arc<App>>) -> Response {
let snapshot = state.config.load();
let pools: Vec<_> = snapshot
.pools
.iter()
.map(|pool| {
let enabled: Vec<_> = pool
.members
.iter()
.filter(|member| member.definition.enabled)
.collect();
let healthy = enabled
.iter()
.filter(|member| member.state.healthy())
.count();
(pool.id.clone(), healthy, enabled.len())
})
.collect();
let degraded: Vec<_> = pools
.iter()
.filter(|(_, healthy, total)| *total > 0 && *healthy == 0)
.map(|(id, _, _)| id.clone())
.collect();
let status = if degraded.is_empty() {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
};
let body = json!({
"status": if degraded.is_empty() { "ok" } else { "degraded" },
"version": env!("CARGO_PKG_VERSION"),
"mode": if headless_enabled() { "headless" } else { "panel" },
"revision": snapshot.envelope.revision,
"last_reload": last_headless_reload(),
"uptime_seconds": state.started.elapsed().as_secs(),
"vhosts_without_healthy_backends": degraded,
"pools": pools
.iter()
.map(|(id, healthy, total)| json!({ "vhost": id, "healthy": healthy, "backends": total }))
.collect::<Vec<_>>(),
});
let mut response = (status, Json(body)).into_response();
response.headers_mut().insert(
http::header::CACHE_CONTROL,
http::HeaderValue::from_static("no-store"),
);
response
}
+94
View File
@@ -215,3 +215,97 @@ mod cache_revision_tests {
));
}
}
#[cfg(test)]
mod headless_config_tests {
use super::*;
fn startup() -> crate::settings::Listeners {
crate::settings::Listeners::from_startup(
"127.0.0.1:8080".parse().unwrap(),
Some("127.0.0.1:8443".parse().unwrap()),
)
}
fn policy() -> ValidationPolicy {
ValidationPolicy {
tls_addr: Some("127.0.0.1:8443".parse().unwrap()),
cert_dir: None,
data_dir: None,
proxy_addr: "127.0.0.1:8080".parse().unwrap(),
admin_addr: "127.0.0.1:9090".parse().unwrap(),
}
}
#[test]
fn minimal_document_gets_startup_listeners_and_all_listener_ids() {
let document = br#"{"vhosts":[{"id":"app","frontend":{"hosts":["*"]},
"backends":[{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}]}]}"#;
let config = external_config::headless_config(document, &startup()).unwrap();
let ids: Vec<_> = config
.listeners
.endpoints
.iter()
.map(|endpoint| endpoint.id.as_str())
.collect();
assert_eq!(ids, ["http", "https"]);
assert_eq!(config.vhosts[0].frontend.listener_ids, ["http", "https"]);
assert!(!config.geoip_updates.enabled);
let http_only =
crate::settings::Listeners::from_startup("127.0.0.1:8080".parse().unwrap(), None);
let config = external_config::headless_config(document, &http_only).unwrap();
let mut policy = policy();
policy.tls_addr = None;
let snapshot = config::compile(config, 1, &policy).unwrap();
assert!(snapshot
.frontend("10.1.2.3", "127.0.0.1:8080".parse().unwrap(), false)
.is_some());
}
#[test]
fn declared_listeners_and_explicit_choices_are_kept() {
let document = br#"{"listeners":{"endpoints":[
{"id":"web","name":"Web","scope":"internal","enabled":true,"binding":{"address":"127.0.0.1:8080","tls":false,"http2":false}},
{"id":"off","name":"Off","scope":"internal","enabled":false,"binding":{"address":"127.0.0.1:8081","tls":false,"http2":false}}]},
"geoip_updates":{"enabled":true},
"vhosts":[
{"id":"a","frontend":{"hosts":["a.example"]},"backends":[{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}]},
{"id":"b","frontend":{"hosts":["b.example"],"listener_ids":["web"]},"backends":[{"id":"b","url":"http://127.0.0.1:9002","allow_private":true}]}]}"#;
let config = external_config::headless_config(document, &startup()).unwrap();
assert_eq!(config.listeners.endpoints.len(), 2);
assert_eq!(config.vhosts[0].frontend.listener_ids, ["web"]);
assert_eq!(config.vhosts[1].frontend.listener_ids, ["web"]);
assert!(config.geoip_updates.enabled);
assert!(config::compile(config, 1, &policy()).is_ok());
}
#[test]
fn non_object_documents_are_rejected() {
assert!(external_config::headless_config(b"[]", &startup()).is_err());
assert!(external_config::headless_config(b"{\"vhosts\": [", &startup()).is_err());
}
#[test]
fn acme_auto_renewal_is_refused_in_headless_mode() {
let mut config = config::Config::default();
config.tls.certificates.push(crate::tls::Certificate {
id: "site".into(),
covered_hosts: Vec::new(),
hosts: vec!["example.org".into()],
cert_file: "site.pem".into(),
key_file: "site.key".into(),
issuer: Some(crate::tls::Issuer {
provider: "cloudflare".into(),
environment: "staging".into(),
auto_renew: true,
}),
});
assert!(ensure_headless_supported(&config).is_err());
config.tls.certificates[0]
.issuer
.as_mut()
.unwrap()
.auto_renew = false;
assert!(ensure_headless_supported(&config).is_ok());
}
}
+17 -4
View File
@@ -30,10 +30,17 @@ impl App {
.await;
};
let (config, fingerprint) =
tokio::task::spawn_blocking(move || external_config::read(&file))
.await
.map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
tokio::task::spawn_blocking(move || match headless_listeners() {
Some(listeners) => external_config::read_headless(&file, listeners),
None => external_config::read(&file),
})
.await
.map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
.map_err(|e| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{e:#}")))?;
if headless_enabled() {
ensure_headless_supported(&config)
.map_err(|e| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{e:#}")))?;
}
self.update_as_action(
Update {
expected_revision,
@@ -98,6 +105,12 @@ impl App {
source_revision: Option<u64>,
reload_hash: Option<external_config::Fingerprint>,
) -> Result<config::Envelope, ApiError> {
if headless_enabled() && reload_hash.is_none() {
return Err(ApiError(
StatusCode::FORBIDDEN,
"headless mode: the configuration file is read-only for RustProxy; edit it and reload".into(),
));
}
let slot = self.update_slots.clone().try_acquire_owned().map_err(|_| {
ApiError(
StatusCode::TOO_MANY_REQUESTS,
@@ -164,7 +177,7 @@ impl App {
let target = path.clone();
let result = tokio::task::spawn_blocking(move || {
if let Some(reloaded) = reload_hash {
if external_config::read(&target)?.1 != reloaded {
if external_config::fingerprint(&target)? != reloaded {
anyhow::bail!("configuration file changed during reload");
}
Ok(reloaded)
+8 -2
View File
@@ -253,7 +253,10 @@ pub fn for_all_frontends(
certificate_ids.contains(id),
"{owner} references unknown certificate id"
);
for host in hosts {
for host in hosts
.iter()
.filter(|host| host.as_str() != crate::config::CATCH_ALL_HOST)
{
if let Some(old) = assignments.insert(host.clone(), id.to_owned()) {
ensure!(
old == id,
@@ -268,7 +271,10 @@ pub fn for_all_frontends(
let hosts = vhost.routing_hosts()?;
assign(&hosts, id, "vhost")?;
if vhost.allow_certificate_mismatch {
for host in hosts {
for host in hosts
.into_iter()
.filter(|host| host != crate::config::CATCH_ALL_HOST)
{
result.forced_mismatches.insert((id.clone(), host));
}
}
+1 -1
View File
@@ -77,7 +77,7 @@ impl Vhost {
);
let mut hosts = std::collections::HashSet::new();
for host in &mut self.frontend.hosts {
*host = crate::config::normalize_host_pattern(host)?;
*host = crate::config::normalize_frontend_host(host)?;
ensure!(
hosts.insert(host.clone()),
"hostname {} is listed twice in this vhost",
+1 -1
View File
@@ -51,5 +51,5 @@ const events = openapi.paths["/api/events"].get;
const logsFlag = (events.parameters || []).find(parameter => parameter.name === "logs");
assert.equal(logsFlag?.schema?.type, "boolean");
assert.equal(logsFlag?.schema?.default, true);
assert.equal(openapi.info.version, "0.37.3");
assert.equal(openapi.info.version, "0.38.0");
console.log("Panel refresh/API contract checks: OK");