Serve the authenticated catalog independently of proxy forwarding
CI / validate (push) Successful in 33s
CI / gateway-contract (push) Successful in 1m58s
CI / images (deploy/Dockerfile.api, api) (push) Successful in 1m8s
CI / images (deploy/Dockerfile.checker, checker) (push) Successful in 1m14s
CI / images (deploy/Dockerfile.web, web) (push) Successful in 1m12s
CI / images (deploy/Dockerfile.http-gateway, http-gateway) (push) Successful in 1m17s
CI / validate (push) Successful in 33s
CI / gateway-contract (push) Successful in 1m58s
CI / images (deploy/Dockerfile.api, api) (push) Successful in 1m8s
CI / images (deploy/Dockerfile.checker, checker) (push) Successful in 1m14s
CI / images (deploy/Dockerfile.web, web) (push) Successful in 1m12s
CI / images (deploy/Dockerfile.http-gateway, http-gateway) (push) Successful in 1m17s
This commit is contained in:
1 parent
4499a6ee37
commit
3967d14f00
9 files changed
+498
-38
No files matched your search
+7
-2
@@ -21,11 +21,15 @@ WEB_PORT=8088
|
||||
# TAG=latest
|
||||
|
||||
# --- Optional private HTTP gateway (docker compose --profile gateway) ---
|
||||
# Publish on loopback or on an explicit VPN interface; never on all interfaces.
|
||||
# Empty starts the full gateway; catalog-only serves the API without forwarding or probes.
|
||||
GATEWAY_MODE=
|
||||
# Bind the forwarding ports to loopback or an explicit VPN interface, not a wildcard.
|
||||
GATEWAY_BIND_IP=127.0.0.1
|
||||
GATEWAY_PROXY_PORT=8081
|
||||
# API binding is independent. For 0.0.0.0, restrict ingress and use a VPN or TLS.
|
||||
GATEWAY_API_BIND_IP=127.0.0.1
|
||||
GATEWAY_API_PORT=8082
|
||||
# Published and advertised SOCKS5 port; the container always listens on 1080.
|
||||
# Published and advertised SOCKS5 port; the full gateway listens on 1080.
|
||||
GATEWAY_SOCKS_PORT=1080
|
||||
# HTTP proxy address clients can reach; SOCKS5 exports reuse its host.
|
||||
# For example, 127.0.0.1:8081 or a private VPN name:port.
|
||||
@@ -35,6 +39,7 @@ GATEWAY_DB_DSN=
|
||||
# Generate each independently: openssl rand -base64 32 | tr '/+' '_-' | tr -d '=\n'
|
||||
GATEWAY_API_TOKEN=
|
||||
GATEWAY_NODE_SECRET=
|
||||
# The three forwarding settings below are required in full mode only.
|
||||
# Fixed HTTPS control endpoint with valid TLS and a stable 204 response.
|
||||
GATEWAY_PROBE_URL=
|
||||
# Comma-separated exact DNS names and TCP ports, including the probe authority.
|
||||
|
||||
@@ -60,23 +60,50 @@ working proxies from the current session are ever shown or served.
|
||||
|
||||
## Private HTTP gateway
|
||||
|
||||
The optional `gateway` Compose profile publishes three separate private ports:
|
||||
By default the optional `gateway` Compose profile runs the full gateway, with
|
||||
three separate private ports:
|
||||
|
||||
- **8081** for plain HTTP and HTTPS through HTTP CONNECT.
|
||||
- **8082** for the catalog and status API.
|
||||
- **1080** for authenticated SOCKS5 TCP CONNECT.
|
||||
|
||||
All three bind to host loopback by default. For remote clients, bind them to
|
||||
the host's private VPN interface and restrict ingress to authorized VPN
|
||||
clients with the host firewall. Never bind to a wildcard or expose any port
|
||||
on the WAN: client credentials are cleartext on the hop to the gateway.
|
||||
Public nginx does not route any of these ports.
|
||||
All three publish to host loopback by default. `GATEWAY_BIND_IP` controls
|
||||
the HTTP and SOCKS5 proxy ports; `GATEWAY_API_BIND_IP` independently controls
|
||||
the API port. For remote forwarding clients, publish only on a private VPN
|
||||
interface and restrict ingress to authorized VPN clients with the host firewall.
|
||||
Never expose the forwarding ports on a wildcard or on the WAN: proxy credentials
|
||||
are cleartext on the hop to the gateway. Public nginx does not route these ports.
|
||||
The normal stack does not require any `GATEWAY_*` variables.
|
||||
|
||||
### Catalog-only mode
|
||||
|
||||
Set `GATEWAY_MODE=catalog-only` to run just the API. Provision the real
|
||||
PostgreSQL database, API token, node secret, and advertised proxy addresses as
|
||||
described in provisioning steps 3 and 4 below. Leave `GATEWAY_PROBE_URL`,
|
||||
`GATEWAY_ALLOWED_DESTINATIONS`, and `GATEWAY_UPSTREAM_NETWORKS` empty if
|
||||
forwarding is not configured. An empty or unset `GATEWAY_MODE` still means the
|
||||
full gateway, which refuses to start without complete forwarding configuration.
|
||||
|
||||
In catalog-only mode the process listens only on `:8082`; it does not open HTTP
|
||||
or SOCKS5 forwarding listeners or run probes, regardless of which Compose ports
|
||||
are mapped. Requests to `GET /v1/proxies` and `GET /v1/status` still require
|
||||
`Authorization: Bearer <GATEWAY_API_TOKEN>`. The API reads the same PostgreSQL
|
||||
catalog and status as full mode; `/readyz` indicates database/schema readiness,
|
||||
not forwarding availability. Previously successful checks still expire, so a
|
||||
catalog with no fresh checks is empty. Exported proxy URLs do not enable
|
||||
forwarding on this instance.
|
||||
|
||||
Keep `GATEWAY_API_BIND_IP=127.0.0.1` for local access or a local TLS reverse
|
||||
proxy. For LAN access, preferably bind to the VPN interface. To publish the
|
||||
API on all host IPv4 interfaces, set `GATEWAY_API_BIND_IP=0.0.0.0`, restrict
|
||||
ingress to trusted clients, and use a VPN or a private HTTPS reverse proxy;
|
||||
do not send bearer tokens or catalog exports over unprotected LAN or WAN links.
|
||||
|
||||
### Provisioning
|
||||
|
||||
1. **Enroll only authorized peers.** The gateway considers every member of the
|
||||
last completed, current checker session, across all its sources. Use only
|
||||
1. **Enroll only authorized peers (full gateway only).** The gateway considers
|
||||
every member of the last completed, current checker session across all its
|
||||
sources. Use only
|
||||
operator-owned peers or peers whose operator has explicitly authorized
|
||||
relay use. If the existing snapshot mixes authorized and unauthorized
|
||||
peers, use a separate checker/database; do not enable the gateway on that
|
||||
@@ -85,7 +112,7 @@ The normal stack does not require any `GATEWAY_*` variables.
|
||||
IPv6 `/64` or narrower. Prefer individual `/32` or `/128` addresses. These
|
||||
limits apply to the actual TCP peer, not the exit IP or destination. Do not
|
||||
add external proxy pools or unrelated addresses to those networks.
|
||||
2. **Configure the destination allowlist and probe.** Set
|
||||
2. **Configure the destination allowlist and probe (full gateway only).** Set
|
||||
`GATEWAY_ALLOWED_DESTINATIONS` to exact comma-separated DNS names with ports,
|
||||
for example `origin.example:80,origin.example:443,probe.example:443`. Include
|
||||
the probe authority in the list even if it uses a port other than 443.
|
||||
@@ -129,8 +156,9 @@ The normal stack does not require any `GATEWAY_*` variables.
|
||||
client-reachable `host:port`, for example `127.0.0.1:8081` for local clients
|
||||
or `[fd12:3456::9]:8081` on a private VPN. HTTP exports use this address;
|
||||
SOCKS5 exports use its host with `GATEWAY_SOCKS_PORT` (default `1080`).
|
||||
`GATEWAY_BIND_IP`, `GATEWAY_PROXY_PORT`, `GATEWAY_API_PORT`, and
|
||||
`GATEWAY_SOCKS_PORT` control host publication (bracket an IPv6 bind IP).
|
||||
`GATEWAY_BIND_IP`, `GATEWAY_API_BIND_IP`, `GATEWAY_PROXY_PORT`,
|
||||
`GATEWAY_API_PORT`, and `GATEWAY_SOCKS_PORT` control host publication (bracket
|
||||
an IPv6 bind IP).
|
||||
Generate two independent
|
||||
32-byte random base64url strings without padding for `GATEWAY_API_TOKEN`
|
||||
and `GATEWAY_NODE_SECRET`:
|
||||
@@ -160,14 +188,15 @@ docker compose --profile gateway up -d --no-deps http-gateway
|
||||
For a local build, include `-f docker-compose.yml -f docker-compose.build.yml`
|
||||
and add `--build` to `up`. For a standalone binary, build with
|
||||
`go build -o http-gateway ./cmd/http-gateway` and set the required environment
|
||||
from [`.env.example`](./.env.example). The binary listens on container ports
|
||||
from [`.env.example`](./.env.example). In full mode the binary listens on ports
|
||||
8081, 8082, and 1080 on all interfaces; the Compose host bind settings do not
|
||||
change these sockets. Keep the host private and restrict all three ports at
|
||||
change these sockets. Keep the host private and restrict all listening ports at
|
||||
the firewall if running without Compose.
|
||||
|
||||
Check both unauthenticated health endpoints on the **private API port** (`GET`,
|
||||
not `HEAD`): `/healthz` means the process can answer; `/readyz` means the HTTP,
|
||||
SOCKS5, and API listeners, DB/schema and the single-instance advisory lock are usable.
|
||||
not `HEAD`): `/healthz` means the process can answer. In full mode, `/readyz`
|
||||
means the HTTP, SOCKS5, and API listeners, DB/schema and the single-instance
|
||||
advisory lock are usable.
|
||||
Readiness can be `503` during initialization or on DB/lease failure. It does not
|
||||
require a session or any working peers. Use authenticated `GET /v1/status` or
|
||||
**Settings → HTTP gateway** for monitor state, ready/candidate counts and last
|
||||
|
||||
@@ -41,6 +41,10 @@ func run(ctx context.Context) error {
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
if cfg.CatalogOnly {
|
||||
return gateway.RunCatalogOnly(ctx, store, cfg, ":8082")
|
||||
}
|
||||
|
||||
// Run binds all listeners and waits for the checker schema and lease.
|
||||
return gateway.Run(ctx, store, cfg, gateway.RuntimeOptions{
|
||||
Build: func(_ context.Context, endpoints gateway.RuntimeEndpoints) (gateway.RuntimeComponents, error) {
|
||||
|
||||
+2
-1
@@ -64,6 +64,7 @@ services:
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 15s
|
||||
environment:
|
||||
GATEWAY_MODE: ${GATEWAY_MODE:-}
|
||||
GATEWAY_DB_DSN: ${GATEWAY_DB_DSN:-}
|
||||
GATEWAY_PUBLIC_PROXY_ADDR: ${GATEWAY_PUBLIC_PROXY_ADDR:-}
|
||||
GATEWAY_API_TOKEN: ${GATEWAY_API_TOKEN:-}
|
||||
@@ -74,7 +75,7 @@ services:
|
||||
GATEWAY_SOCKS_PORT: ${GATEWAY_SOCKS_PORT:-1080}
|
||||
ports:
|
||||
- "${GATEWAY_BIND_IP:-127.0.0.1}:${GATEWAY_PROXY_PORT:-8081}:8081"
|
||||
- "${GATEWAY_BIND_IP:-127.0.0.1}:${GATEWAY_API_PORT:-8082}:8082"
|
||||
- "${GATEWAY_API_BIND_IP:-127.0.0.1}:${GATEWAY_API_PORT:-8082}:8082"
|
||||
- "${GATEWAY_BIND_IP:-127.0.0.1}:${GATEWAY_SOCKS_PORT:-1080}:1080"
|
||||
depends_on:
|
||||
postgres:
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
|
||||
)
|
||||
|
||||
const catalogOnlyDBTimeout = 2 * time.Second
|
||||
|
||||
// RunCatalogOnly serves the authenticated PostgreSQL catalog without owning
|
||||
// forwarding listeners, a database lease, or monitor state. The caller owns
|
||||
// the opened store and supplies validated catalog configuration.
|
||||
func RunCatalogOnly(ctx context.Context, store *db.DB, cfg Config, addr string) error {
|
||||
return runCatalogOnly(ctx, store, cfg, addr, new(net.ListenConfig).Listen)
|
||||
}
|
||||
|
||||
func runCatalogOnly(ctx context.Context, store *db.DB, cfg Config, addr string, listen func(context.Context, string, string) (net.Listener, error)) error {
|
||||
if store == nil {
|
||||
return errors.New("gateway database is required")
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
if addr == "" {
|
||||
addr = "0.0.0.0" + defaultAPIAddr
|
||||
}
|
||||
listener, err := listen(ctx, "tcp4", addr)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return errors.New("could not bind gateway API listener")
|
||||
}
|
||||
api := &catalogOnlyAPI{store: store, cfg: cfg}
|
||||
server := gatewayHTTPServer(ctx, gatewayAPIHandler(cfg.APIToken, api.serveReady, api.serveStatus, api.serveCatalog))
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- server.Serve(listener) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
_ = server.Close()
|
||||
if !errors.Is(err, http.ErrServerClosed) {
|
||||
return errors.New("gateway API listener stopped")
|
||||
}
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
_ = server.Close()
|
||||
<-done
|
||||
return errors.New("gateway HTTP shutdown deadline expired")
|
||||
}
|
||||
if err := <-done; !errors.Is(err, http.ErrServerClosed) {
|
||||
return errors.New("gateway API listener stopped")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type catalogOnlyAPI struct {
|
||||
store *db.DB
|
||||
cfg Config
|
||||
catalog atomic.Pointer[http.Handler]
|
||||
}
|
||||
|
||||
func (a *catalogOnlyAPI) loadCatalog(parent context.Context) (http.Handler, error) {
|
||||
if cached := a.catalog.Load(); cached != nil {
|
||||
return *cached, nil
|
||||
}
|
||||
// Schema installation may happen after the listener comes up. Cache only
|
||||
// a handler built from a real store UUID, not a failed initialization.
|
||||
ctx, cancel := context.WithTimeout(parent, catalogOnlyDBTimeout)
|
||||
defer cancel()
|
||||
storeUUID, err := a.store.GatewayStoreUUID(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
creds, err := NewCredentials(storeUUID, a.cfg.NodeSecret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
catalog := NewCatalog(a.store, a.cfg, creds)
|
||||
if a.catalog.CompareAndSwap(nil, &catalog) {
|
||||
return catalog, nil
|
||||
}
|
||||
return *a.catalog.Load(), nil
|
||||
}
|
||||
|
||||
func (a *catalogOnlyAPI) serveReady(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), catalogOnlyDBTimeout)
|
||||
defer cancel()
|
||||
if _, err := a.store.GatewayStatus(ctx, time.Time{}); err != nil {
|
||||
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if _, err := a.loadCatalog(ctx); err != nil {
|
||||
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (a *catalogOnlyAPI) serveStatus(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), catalogOnlyDBTimeout)
|
||||
defer cancel()
|
||||
status, err := a.store.GatewayStatus(ctx, time.Time{})
|
||||
if err != nil {
|
||||
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
writeGatewayStatus(w, status)
|
||||
}
|
||||
|
||||
func (a *catalogOnlyAPI) serveCatalog(w http.ResponseWriter, r *http.Request) {
|
||||
catalog, err := a.loadCatalog(r.Context())
|
||||
if err != nil {
|
||||
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
catalog.ServeHTTP(w, r)
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
|
||||
)
|
||||
|
||||
func TestCatalogOnlyPostgres(t *testing.T) {
|
||||
store := newRuntimeTestDatabase(t).store(t)
|
||||
cfg := Config{
|
||||
APIToken: identityTestToken(1),
|
||||
NodeSecret: identityTestKey(2),
|
||||
PublicProxyHost: "proxy.example",
|
||||
PublicProxyPort: 8081,
|
||||
PublicSOCKSPort: 1080,
|
||||
}
|
||||
ctx, stop := context.WithCancel(t.Context())
|
||||
type binding struct{ network, requested, address string }
|
||||
bound := make(chan binding, 4)
|
||||
done := make(chan struct{})
|
||||
var runErr error
|
||||
go func() {
|
||||
defer close(done)
|
||||
runErr = runCatalogOnly(ctx, store, cfg, "", func(ctx context.Context, network, requested string) (net.Listener, error) {
|
||||
listener, err := new(net.ListenConfig).Listen(ctx, network, "127.0.0.1:0")
|
||||
if err == nil {
|
||||
bound <- binding{network, requested, listener.Addr().String()}
|
||||
}
|
||||
return listener, err
|
||||
})
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
stop()
|
||||
waitRuntimeEvent(t, done)
|
||||
})
|
||||
var api string
|
||||
select {
|
||||
case b := <-bound:
|
||||
if b.network != "tcp4" || b.requested != "0.0.0.0:8082" {
|
||||
t.Fatalf("unexpected API bind %s %s", b.network, b.requested)
|
||||
}
|
||||
api = b.address
|
||||
case <-done:
|
||||
t.Fatalf("catalog-only exited before bind: %v", runErr)
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("timed out waiting for catalog-only bind")
|
||||
}
|
||||
|
||||
assertRuntimeHTTP(t, api, http.MethodGet, "/healthz", "", http.StatusOK)
|
||||
assertRuntimeHTTP(t, api, http.MethodGet, "/readyz", "", http.StatusServiceUnavailable)
|
||||
for _, path := range []string{"/v1/status", "/v1/proxies"} {
|
||||
for _, authorization := range []string{"", "Authorization: Bearer invalid\r\n"} {
|
||||
h, _ := assertRuntimeHTTP(t, api, http.MethodGet, path, authorization, http.StatusUnauthorized)
|
||||
if h.Get("WWW-Authenticate") != "Bearer" || h.Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("missing challenge or cache policy on unauthorized response")
|
||||
}
|
||||
}
|
||||
assertRuntimeHTTP(t, api, http.MethodGet, path, runtimeBearer(cfg), http.StatusServiceUnavailable)
|
||||
h, _ := assertRuntimeHTTP(t, api, http.MethodPost, path, runtimeBearer(cfg), http.StatusMethodNotAllowed)
|
||||
if h.Get("Allow") != http.MethodGet {
|
||||
t.Fatal("API method error did not advertise GET")
|
||||
}
|
||||
}
|
||||
assertRuntimeHTTP(t, api, http.MethodGet, "http://origin.test/v1/proxies", runtimeBearer(cfg), http.StatusBadRequest)
|
||||
assertRuntimeHTTP(t, api, http.MethodConnect, "origin.test:443", runtimeBearer(cfg), http.StatusBadRequest)
|
||||
|
||||
applyRuntimeSchema(t, store)
|
||||
assertRuntimeHTTP(t, api, http.MethodGet, "/readyz", "", http.StatusOK)
|
||||
status := catalogOnlyStatus(t, api, cfg)
|
||||
if status.State != "not_started" || status.SessionID != nil || status.CandidateCount != 0 || status.ReadyCount != 0 || status.IntervalMinutes == nil || *status.IntervalMinutes != 20 {
|
||||
t.Fatal("catalog-only did not expose the real unstarted database state")
|
||||
}
|
||||
assertRuntimeHTTP(t, api, http.MethodGet, "/v1/proxies?unknown=1", runtimeBearer(cfg), http.StatusBadRequest)
|
||||
|
||||
t.Run("exports with another lease owner", func(t *testing.T) {
|
||||
dbCtx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
lease, err := store.AcquireGatewayLease(dbCtx)
|
||||
if err != nil {
|
||||
t.Fatalf("catalog-only owns the forwarding lease: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
if err := lease.Close(ctx); err != nil {
|
||||
t.Errorf("close fixture lease: %v", err)
|
||||
}
|
||||
})
|
||||
sessionID, readyID := seedCatalogOnly(t, dbCtx, store)
|
||||
assertRuntimeHTTP(t, api, http.MethodGet, "/readyz", "", http.StatusOK)
|
||||
status := catalogOnlyStatus(t, api, cfg)
|
||||
if status.State != "offline" || status.SessionID == nil || *status.SessionID != sessionID || status.CandidateCount != 2 || status.ReadyCount != 1 {
|
||||
t.Fatal("status did not reflect a published snapshot with a stale heartbeat and one fresh node")
|
||||
}
|
||||
|
||||
h, body := assertRuntimeHTTP(t, api, http.MethodGet, "/v1/proxies", runtimeBearer(cfg), http.StatusOK)
|
||||
var catalog struct {
|
||||
SessionID int64 `json:"session_id"`
|
||||
Total int64 `json:"total"`
|
||||
Items []struct {
|
||||
ID string `json:"proxy_id"`
|
||||
Country string `json:"country"`
|
||||
Latency int `json:"latency_ms"`
|
||||
URL string `json:"proxy_url"`
|
||||
Password string `json:"password"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &catalog); err != nil || catalog.SessionID != sessionID || catalog.Total != 1 || len(catalog.Items) != 1 {
|
||||
t.Fatal("catalog did not return exactly the one fresh node in the published snapshot")
|
||||
}
|
||||
if h.Get("Content-Type") != "application/json" || h.Get("Cache-Control") != "no-store" || bytes.Contains(body, []byte("upstream.example")) {
|
||||
t.Fatal("catalog headers or upstream redaction are incorrect")
|
||||
}
|
||||
id, item := strconv.FormatInt(readyID, 10), catalog.Items[0]
|
||||
if item.ID != id || item.Country != "DE" || item.Latency != 42 || item.Password == "" || item.URL != "http://node-"+id+":"+item.Password+"@proxy.example:8081" {
|
||||
t.Fatal("catalog did not return the stored health and stable gateway endpoint")
|
||||
}
|
||||
|
||||
base := "/v1/proxies?country=DE&format="
|
||||
h, body = assertRuntimeHTTP(t, api, http.MethodGet, base+"csv", runtimeBearer(cfg), http.StatusOK)
|
||||
rows, err := csv.NewReader(bytes.NewReader(body)).ReadAll()
|
||||
if err != nil || h.Get("Content-Type") != "text/csv; charset=utf-8" || len(rows) != 2 || len(rows[1]) != 13 || rows[1][0] != id || rows[1][5] != item.URL {
|
||||
t.Fatal("CSV did not export the same filtered node and URL")
|
||||
}
|
||||
for _, row := range []struct{ format, want string }{
|
||||
{"txt", "proxy.example:8081:node-" + id + ":" + item.Password + "\n"},
|
||||
{"proxy-url-list-txt", item.URL + "\n"},
|
||||
} {
|
||||
h, body = assertRuntimeHTTP(t, api, http.MethodGet, base+row.format, runtimeBearer(cfg), http.StatusOK)
|
||||
if h.Get("Content-Type") != "text/plain; charset=utf-8" || string(body) != row.want {
|
||||
t.Fatalf("%s did not export the same filtered node", row.format)
|
||||
}
|
||||
}
|
||||
_, body = assertRuntimeHTTP(t, api, http.MethodGet, "/v1/proxies?country=NL&format=txt", runtimeBearer(cfg), http.StatusOK)
|
||||
if len(body) != 0 {
|
||||
t.Fatal("catalog-only returned the expired node")
|
||||
}
|
||||
})
|
||||
|
||||
store.Close()
|
||||
assertRuntimeHTTP(t, api, http.MethodGet, "/healthz", "", http.StatusOK)
|
||||
assertRuntimeHTTP(t, api, http.MethodGet, "/readyz", "", http.StatusServiceUnavailable)
|
||||
assertRuntimeHTTP(t, api, http.MethodGet, "/v1/status", runtimeBearer(cfg), http.StatusServiceUnavailable)
|
||||
assertRuntimeHTTP(t, api, http.MethodGet, "/v1/proxies", runtimeBearer(cfg), http.StatusServiceUnavailable)
|
||||
stop()
|
||||
waitRuntimeEvent(t, done)
|
||||
if runErr != nil {
|
||||
t.Fatalf("stop catalog-only: %v", runErr)
|
||||
}
|
||||
assertRuntimeListenerClosed(t, api)
|
||||
select {
|
||||
case b := <-bound:
|
||||
t.Fatalf("catalog-only unexpectedly bound another port: %s", b.requested)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func catalogOnlyStatus(t *testing.T, api string, cfg Config) db.GatewayStatus {
|
||||
t.Helper()
|
||||
h, body := assertRuntimeHTTP(t, api, http.MethodGet, "/v1/status", runtimeBearer(cfg), http.StatusOK)
|
||||
var status db.GatewayStatus
|
||||
if h.Get("Content-Type") != "application/json" || h.Get("Cache-Control") != "no-store" || strings.Contains(string(body), "store_uuid") || json.Unmarshal(body, &status) != nil {
|
||||
t.Fatal("unexpected catalog-only status response")
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func seedCatalogOnly(t *testing.T, ctx context.Context, store *db.DB) (int64, int64) {
|
||||
t.Helper()
|
||||
if _, err := store.Pool().Exec(ctx, `UPDATE gateway_runtime SET heartbeat_at = now() - interval '1 hour' WHERE id = 1`); err != nil {
|
||||
t.Fatal("seed historical gateway heartbeat")
|
||||
}
|
||||
var sessionID, readyID int64
|
||||
err := store.Pool().QueryRow(ctx, `WITH published AS (
|
||||
INSERT INTO check_sessions (status, is_current, finished_at) VALUES ('completed', true, now()) RETURNING id
|
||||
), nodes AS (
|
||||
INSERT INTO proxies (canonical_url, protocol, host, port) VALUES
|
||||
('vless://fixture-a@upstream.example:443', 'vless', 'upstream.example', 443),
|
||||
('vless://fixture-b@upstream.example:443', 'vless', 'upstream.example', 443)
|
||||
RETURNING id, canonical_url, protocol, host, port
|
||||
), members AS (
|
||||
INSERT INTO session_proxies (session_id, proxy_id, canonical_url, protocol, host, port, country, speed_mbps)
|
||||
SELECT published.id, nodes.id, canonical_url, protocol, host, port,
|
||||
CASE WHEN canonical_url LIKE 'vless://fixture-a@%' THEN 'DE' ELSE 'NL' END, 25
|
||||
FROM published CROSS JOIN nodes RETURNING id, proxy_id, country
|
||||
), measured AS (
|
||||
INSERT INTO gateway_node_health (proxy_id, tested_membership_id, ok, checked_at, latency_ms)
|
||||
SELECT proxy_id, id, true, now() - CASE country WHEN 'DE' THEN interval '1 minute' ELSE interval '2 hours' END, 42
|
||||
FROM members RETURNING proxy_id
|
||||
)
|
||||
SELECT published.id, measured.proxy_id FROM published CROSS JOIN measured JOIN members USING (proxy_id) WHERE country = 'DE'`).Scan(&sessionID, &readyID)
|
||||
if err != nil {
|
||||
t.Fatalf("seed published catalog snapshot: %v", err)
|
||||
}
|
||||
return sessionID, readyID
|
||||
}
|
||||
+28
-11
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
// Config is the validated, operator-supplied process configuration.
|
||||
type Config struct {
|
||||
CatalogOnly bool
|
||||
DBDSN string
|
||||
PublicProxyHost string
|
||||
PublicProxyPort uint16
|
||||
@@ -34,6 +35,14 @@ func LoadConfig() (Config, error) {
|
||||
|
||||
func parseGatewayConfig(getenv func(string) string) (Config, error) {
|
||||
var cfg Config
|
||||
switch getenv("GATEWAY_MODE") {
|
||||
case "": // Full gateway is the default.
|
||||
case "catalog-only":
|
||||
cfg.CatalogOnly = true
|
||||
default:
|
||||
return Config{}, errors.New("GATEWAY_MODE must be empty (full gateway) or catalog-only")
|
||||
}
|
||||
|
||||
cfg.DBDSN = getenv("GATEWAY_DB_DSN")
|
||||
if strings.TrimSpace(cfg.DBDSN) == "" {
|
||||
return Config{}, errors.New("GATEWAY_DB_DSN is required")
|
||||
@@ -69,21 +78,29 @@ func parseGatewayConfig(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("GATEWAY_API_TOKEN and GATEWAY_NODE_SECRET must differ")
|
||||
}
|
||||
|
||||
cfg.AllowedDestinations, ok = parseGatewayDestinations(getenv("GATEWAY_ALLOWED_DESTINATIONS"))
|
||||
if !ok {
|
||||
return Config{}, errors.New("GATEWAY_ALLOWED_DESTINATIONS must be a list of exact DNS names with ports")
|
||||
if destinations := getenv("GATEWAY_ALLOWED_DESTINATIONS"); destinations != "" || !cfg.CatalogOnly {
|
||||
cfg.AllowedDestinations, ok = parseGatewayDestinations(destinations)
|
||||
if !ok {
|
||||
return Config{}, errors.New("GATEWAY_ALLOWED_DESTINATIONS must be a list of exact DNS names with ports")
|
||||
}
|
||||
}
|
||||
cfg.ProbeURL, ok = parseGatewayProbeURL(getenv("GATEWAY_PROBE_URL"))
|
||||
if !ok {
|
||||
return Config{}, errors.New("GATEWAY_PROBE_URL must be an absolute HTTPS URL without credentials, query, or fragment")
|
||||
if probe := getenv("GATEWAY_PROBE_URL"); probe != "" || !cfg.CatalogOnly {
|
||||
cfg.ProbeURL, ok = parseGatewayProbeURL(probe)
|
||||
if !ok {
|
||||
return Config{}, errors.New("GATEWAY_PROBE_URL must be an absolute HTTPS URL without credentials, query, or fragment")
|
||||
}
|
||||
}
|
||||
if _, ok := cfg.AllowedDestinations[cfg.ProbeURL.Host]; !ok {
|
||||
return Config{}, errors.New("GATEWAY_PROBE_URL authority must be in GATEWAY_ALLOWED_DESTINATIONS")
|
||||
if cfg.ProbeURL != nil && cfg.AllowedDestinations != nil {
|
||||
if _, ok := cfg.AllowedDestinations[cfg.ProbeURL.Host]; !ok {
|
||||
return Config{}, errors.New("GATEWAY_PROBE_URL authority must be in GATEWAY_ALLOWED_DESTINATIONS")
|
||||
}
|
||||
}
|
||||
|
||||
cfg.UpstreamNetworks, ok = parseGatewayUpstreamNetworks(getenv("GATEWAY_UPSTREAM_NETWORKS"))
|
||||
if !ok {
|
||||
return Config{}, errors.New("GATEWAY_UPSTREAM_NETWORKS must list 1 to 32 unique operator-managed public IPs or canonical CIDRs (IPv4 /24 or narrower, IPv6 /64 or narrower)")
|
||||
if networks := getenv("GATEWAY_UPSTREAM_NETWORKS"); networks != "" || !cfg.CatalogOnly {
|
||||
cfg.UpstreamNetworks, ok = parseGatewayUpstreamNetworks(networks)
|
||||
if !ok {
|
||||
return Config{}, errors.New("GATEWAY_UPSTREAM_NETWORKS must list 1 to 32 unique operator-managed public IPs or canonical CIDRs (IPv4 /24 or narrower, IPv6 /64 or narrower)")
|
||||
}
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
@@ -36,6 +36,9 @@ func TestGatewayLaunchConfig(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.CatalogOnly {
|
||||
t.Fatal("an unset mode must start the full gateway")
|
||||
}
|
||||
if cfg.PublicProxyHost != "fd12:3456::9" || cfg.PublicProxyPort != 8081 || cfg.DBDSN != env["GATEWAY_DB_DSN"] {
|
||||
t.Fatal("validated process endpoints did not match configuration")
|
||||
}
|
||||
@@ -73,6 +76,7 @@ func TestGatewayLaunchConfigRejectsInvalidPolicyAndRedactsValues(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, key, value string
|
||||
}{
|
||||
{"unknown launch mode", "GATEWAY_MODE", "sensitive-mode-marker"},
|
||||
{"invalid DSN", "GATEWAY_DB_DSN", "postgres://user:sensitive-dsn-marker@localhost:bad/gateway"},
|
||||
{"invalid API token", "GATEWAY_API_TOKEN", "sensitive-api-marker"},
|
||||
{"invalid node secret", "GATEWAY_NODE_SECRET", "sensitive-node-marker"},
|
||||
@@ -97,6 +101,63 @@ func TestGatewayLaunchConfigRejectsInvalidPolicyAndRedactsValues(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayLaunchConfigCatalogOnly(t *testing.T) {
|
||||
forwardingKeys := []string{"GATEWAY_PROBE_URL", "GATEWAY_ALLOWED_DESTINATIONS", "GATEWAY_UPSTREAM_NETWORKS"}
|
||||
for _, omitted := range [][]string{forwardingKeys, forwardingKeys[:1], forwardingKeys[1:2], forwardingKeys[2:]} {
|
||||
t.Run("without "+strings.Join(omitted, ","), func(t *testing.T) {
|
||||
env := identityTestEnv()
|
||||
env["GATEWAY_MODE"] = "catalog-only"
|
||||
env["GATEWAY_SOCKS_PORT"] = "1081"
|
||||
for _, key := range omitted {
|
||||
delete(env, key)
|
||||
}
|
||||
cfg, err := parseGatewayConfig(func(k string) string { return env[k] })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !cfg.CatalogOnly || cfg.DBDSN != env["GATEWAY_DB_DSN"] || cfg.PublicProxyHost != "fd12:3456::9" ||
|
||||
cfg.PublicProxyPort != 8081 || cfg.PublicSOCKSPort != 1081 || cfg.APIToken != identityTestToken(1) || cfg.NodeSecret != identityTestKey(2) {
|
||||
t.Fatal("catalog-only launch lost required PostgreSQL, authentication, or export configuration")
|
||||
}
|
||||
if (cfg.ProbeURL == nil) != (env["GATEWAY_PROBE_URL"] == "") ||
|
||||
(cfg.AllowedDestinations == nil) != (env["GATEWAY_ALLOWED_DESTINATIONS"] == "") ||
|
||||
(cfg.UpstreamNetworks == nil) != (env["GATEWAY_UPSTREAM_NETWORKS"] == "") {
|
||||
t.Fatal("catalog-only did not distinguish supplied and omitted forwarding configuration")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayLaunchConfigCatalogOnlyRejectsInvalidInputs(t *testing.T) {
|
||||
for _, tc := range []struct{ name, key, value string }{
|
||||
{"missing DSN", "GATEWAY_DB_DSN", ""},
|
||||
{"invalid DSN", "GATEWAY_DB_DSN", "postgres://user:sensitive-dsn-marker@localhost:bad/gateway"},
|
||||
{"missing HTTP export address", "GATEWAY_PUBLIC_PROXY_ADDR", ""},
|
||||
{"invalid SOCKS export port", "GATEWAY_SOCKS_PORT", "not-a-port"},
|
||||
{"missing API token", "GATEWAY_API_TOKEN", ""},
|
||||
{"missing node secret", "GATEWAY_NODE_SECRET", ""},
|
||||
{"shared secrets", "GATEWAY_NODE_SECRET", identityTestToken(1)},
|
||||
{"invalid optional probe URL", "GATEWAY_PROBE_URL", "http://probe.example/check"},
|
||||
{"invalid optional destination list", "GATEWAY_ALLOWED_DESTINATIONS", "*.example:443"},
|
||||
{"invalid optional upstream network", "GATEWAY_UPSTREAM_NETWORKS", "1.1.0.0/16"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
env := identityTestEnv()
|
||||
env["GATEWAY_MODE"] = "catalog-only"
|
||||
delete(env, "GATEWAY_PROBE_URL")
|
||||
delete(env, "GATEWAY_ALLOWED_DESTINATIONS")
|
||||
delete(env, "GATEWAY_UPSTREAM_NETWORKS")
|
||||
env[tc.key] = tc.value
|
||||
got, err := parseGatewayConfig(func(k string) string { return env[k] })
|
||||
if err == nil || !strings.Contains(err.Error(), tc.key) || !reflect.DeepEqual(got, Config{}) {
|
||||
t.Errorf("expected a %s validation error and zero config", tc.key)
|
||||
} else if tc.value != "" && strings.Contains(err.Error(), tc.value) {
|
||||
t.Error("configuration error included rejected input")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayLaunchConfigAcceptsListedCustomProbePort(t *testing.T) {
|
||||
env := identityTestEnv()
|
||||
env["GATEWAY_PROBE_URL"] = "https://probe.example:8443/check"
|
||||
|
||||
@@ -6,11 +6,23 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
|
||||
)
|
||||
|
||||
func (rt *gatewayRuntime) apiHandler(token string) http.Handler {
|
||||
status := RequireBearerAuth(token, http.HandlerFunc(rt.serveStatus))
|
||||
catalog := RequireBearerAuth(token, http.HandlerFunc(rt.serveCatalog))
|
||||
return gatewayAPIHandler(token, rt.serveReady, rt.serveStatus, rt.serveCatalog)
|
||||
}
|
||||
|
||||
func gatewayAPIHandler(token string, serveReady, serveStatus, serveCatalog http.HandlerFunc) http.Handler {
|
||||
authenticatedGET := func(next http.HandlerFunc) http.Handler {
|
||||
return RequireBearerAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if gatewayGET(w, r) {
|
||||
next(w, r)
|
||||
}
|
||||
}))
|
||||
}
|
||||
status, catalog := authenticatedGET(serveStatus), authenticatedGET(serveCatalog)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if r.Method == http.MethodConnect || !strings.HasPrefix(r.RequestURI, "/") || r.URL.Host != "" || r.URL.Scheme != "" {
|
||||
@@ -24,7 +36,7 @@ func (rt *gatewayRuntime) apiHandler(token string) http.Handler {
|
||||
}
|
||||
case "/readyz":
|
||||
if gatewayGET(w, r) {
|
||||
rt.serveReady(w, r)
|
||||
serveReady(w, r)
|
||||
}
|
||||
case "/v1/status":
|
||||
status.ServeHTTP(w, r)
|
||||
@@ -65,9 +77,6 @@ func (rt *gatewayRuntime) serveReady(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (rt *gatewayRuntime) serveStatus(w http.ResponseWriter, r *http.Request) {
|
||||
if !gatewayGET(w, r) {
|
||||
return
|
||||
}
|
||||
if rt.serving() == nil {
|
||||
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
@@ -79,14 +88,15 @@ func (rt *gatewayRuntime) serveStatus(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
writeGatewayStatus(w, status)
|
||||
}
|
||||
|
||||
func writeGatewayStatus(w http.ResponseWriter, status db.GatewayStatus) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(status)
|
||||
}
|
||||
|
||||
func (rt *gatewayRuntime) serveCatalog(w http.ResponseWriter, r *http.Request) {
|
||||
if !gatewayGET(w, r) {
|
||||
return
|
||||
}
|
||||
active := rt.serving()
|
||||
if active == nil {
|
||||
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
|
||||
|
||||
Reference in new issue
Block a user