Add private HTTP gateway with verified catalog and isolated release tests
CI / validate (push) Successful in 43s
CI / gateway-contract (push) Successful in 3m50s
CI / images (deploy/Dockerfile.web, web) (push) Successful in 50s
CI / images (deploy/Dockerfile.api, api) (push) Successful in 1m16s
CI / images (deploy/Dockerfile.http-gateway, http-gateway) (push) Successful in 1m16s
CI / images (deploy/Dockerfile.checker, checker) (push) Successful in 1m20s

Bind node credentials to the current inventory, independently verify HTTP and CONNECT availability, and serve four filtered export formats.
Add operator controls, least-privilege database access, native WSL/Gitea contracts and release image smoke coverage.
This commit is contained in:
omar committed 2026-11-26 21:41:07 +03:00
1 parent 32aad6b1c8
commit db12ef9fcf
92 files changed
+15479 -515

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
.git
GOAL.md
**/.env
**/.env.*
**/*.key
**/*.pem
**/*.p12
**/*.pfx
# Local builds and test outputs; keep tracked sources and lockfiles.
**/node_modules
frontend/dist
frontend/*.tsbuildinfo
**/test-results
**/playwright-report
**/blob-report
**/.playwright-mcp
bin
api
checker
http-gateway
*.exe
+22 -1
View File
@@ -1,4 +1,4 @@
# Copy to .env and adjust. `docker compose up -d --build` reads this file.
# Copy to .env and adjust. Compose reads this file by default.
# --- PostgreSQL ---
POSTGRES_USER=perchik
@@ -19,3 +19,24 @@ WEB_PORT=8088
# --- Image tagging (used by CI / registry pushes) ---
# REGISTRY=git.eeee.moe/omar
# TAG=latest
# --- Optional private HTTP gateway (docker compose --profile gateway) ---
# Publish on loopback or on an explicit VPN interface; never on all interfaces.
GATEWAY_BIND_IP=127.0.0.1
GATEWAY_PROXY_PORT=8081
GATEWAY_API_PORT=8082
# Address clients can reach, e.g. 127.0.0.1:8081 or a private VPN name:port.
GATEWAY_PUBLIC_PROXY_ADDR=
# Dedicated restricted PostgreSQL login provisioned with deploy/gateway-grants.sql.
GATEWAY_DB_DSN=
# Generate each independently: openssl rand -base64 32 | tr '/+' '_-' | tr -d '=\n'
GATEWAY_API_TOKEN=
GATEWAY_NODE_SECRET=
# Operator-owned HTTPS endpoint with valid TLS and a stable 204 response.
GATEWAY_PROBE_URL=
# Exact origin DNS names and TCP ports, including the probe authority.
# Example syntax: origin.example:80,origin.example:443,probe.example:443
GATEWAY_ALLOWED_DESTINATIONS=
# 1-32 operator-managed public peer IPs or canonical CIDRs, not exit IP pools.
# Restrict to /32 (IPv4) or /128 (IPv6) where possible; min prefix lengths /24 and /64.
GATEWAY_UPSTREAM_NETWORKS=
+52 -6
View File
@@ -2,7 +2,7 @@ name: CI
on:
push:
branches: [main]
branches: [main, feature/http-gateway]
tags: ["v*"]
pull_request:
workflow_dispatch:
@@ -21,7 +21,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.26"
go-version-file: go.mod
cache: true
- run: go vet ./...
- run: go test ./...
@@ -35,12 +35,57 @@ jobs:
npm ci
npm run build
# Build and push the three images to the Gitea container registry. Runs only
# on pushes to main / tags. Uses a PAT with write:package scope (the automatic
gateway-contract:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
cache-dependency-path: frontend/package-lock.json
- name: Cache pinned Xray and Chromium
uses: actions/cache@v4
with:
path: |
~/.cache/gateway-contract/xray
~/.cache/ms-playwright
key: gateway-contract-${{ runner.os }}-${{ runner.arch }}-xray-2cba2c4d59e48a04aa5d09b8e4c2b2d26f8608a4-${{ hashFiles('frontend/package-lock.json') }}
- name: Install PostgreSQL 16 and the race compiler
shell: bash
run: |
set -euo pipefail
root=()
if (( EUID != 0 )); then root=(sudo); fi
"${root[@]}" apt-get update
if ! apt-cache show postgresql-16 >/dev/null 2>&1; then
"${root[@]}" apt-get install -y --no-install-recommends ca-certificates curl
. /etc/os-release
"${root[@]}" install -d /usr/share/postgresql-common/pgdg
"${root[@]}" curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
-o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc
printf '%s\n' "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt ${VERSION_CODENAME}-pgdg main" \
| "${root[@]}" tee /etc/apt/sources.list.d/gateway-pgdg.list >/dev/null
"${root[@]}" apt-get update
fi
"${root[@]}" apt-get install -y --no-install-recommends build-essential postgresql-16
- name: Verify gateway end to end on native Linux
env:
TEST_DATABASE_URL: ""
XRAY_BIN: ""
GATEWAY_INSTALL_BROWSER_DEPS: "1"
run: bash tests/gateway/verify.sh
# Build and push the four images to the Gitea container registry. Runs only
# for main / version tags. Uses a PAT with write:package scope (the automatic
# GITEA_TOKEN cannot push packages), stored as the REGISTRY_TOKEN secret.
images:
needs: validate
if: github.event_name != 'pull_request'
needs: [validate, gateway-contract]
if: github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v'))
runs-on: ubuntu-latest
strategy:
matrix:
@@ -48,6 +93,7 @@ jobs:
- { name: checker, dockerfile: deploy/Dockerfile.checker }
- { name: api, dockerfile: deploy/Dockerfile.api }
- { name: web, dockerfile: deploy/Dockerfile.web }
- { name: http-gateway, dockerfile: deploy/Dockerfile.http-gateway }
steps:
- uses: actions/checkout@v4
+17 -2
View File
@@ -14,8 +14,9 @@ subscriptions.
| `api` | Go (`cmd/api`) | REST API for panel + public subscription endpoints |
| `frontend` | React + Vite + TS + Tailwind + shadcn/ui + recharts | SPA panel, built to static |
| `edge` | nginx | Serves frontend static, routes `/api` and `/sub` to `api` |
| `http-gateway` | Go (`cmd/http-gateway`), optional `gateway` profile | Private HTTP/CONNECT forward proxy on 8081; authenticated catalog and status API on 8082 |
Single Go module (`git.eeee.moe/omar/zhguchiy_perchik`) with two binaries
Single Go module (`git.eeee.moe/omar/zhguchiy_perchik`) with three binaries
sharing `internal/` packages (dialers, upstream parser + canonicalization,
geoip, fetcher, db, subs). Dialers, geoip, fetcher and the upstream parser are
reused from `tessero-checker`; the session model, DB layer, canonicalization,
@@ -42,6 +43,16 @@ subscription conversion and API are new.
every failed candidate).
- No auto-delete after N failures, no dead pool in output.
The gateway reads every membership of the current completed session via
`gateway_candidates`. The monitor uses the real proxy listener to check an
operator-owned HTTPS endpoint, then publishes results to `gateway_node_health`.
A node is available only while still in that snapshot with a successful probe
newer than twice the configured interval. `gateway_runtime` holds monitor
status and the persistent credential namespace; a PostgreSQL advisory lock
limits the gateway to one active instance per database. Country and speed
stay in the checker's snapshot. The admin API reads status from the same DB
but does not receive catalog or node secrets.
## Validity criterion (all gates)
1. Successful protocol handshake + exit IP obtained within timeout.
@@ -105,6 +116,7 @@ Auth: single admin (login+password from env), issues a signed session token.
- `GET/POST/PATCH/DELETE /subscriptions` — CRUD
- `GET/POST/PATCH/DELETE /sources` — CRUD (+ enable/disable)
- `GET/PATCH /settings`
- `GET /gateway/status` — credential-free gateway status (admin session required)
- `POST /checker/run` (manual full cycle), `POST /checker/stop`, `GET /checker/status`
- Public: `GET /sub/{token}` — dynamic subscription, honors format & filters,
404 when disabled/expired; increments request stats.
@@ -114,10 +126,13 @@ Auth: single admin (login+password from env), issues a signed session token.
check_interval_hours(12), workers(10), timeout_sec(5), max_latency_ms(1000),
min_speed_mbps(3), speedtest_enabled(true), speedtest_url, geoip_db_url
(default geolite2-geo-whois-asn-country mmdb), auto_enabled, telegram_bot_token,
telegram_chat_id, telegram_notify_start, telegram_notify_finish.
telegram_chat_id, telegram_notify_start, telegram_notify_finish,
gateway_check_interval_minutes(20, integer 15 through 30).
Exit-IP echo URL is hardcoded with fallbacks (not a setting).
## Deploy
`docker-compose up`. Schema is embedded and applied idempotently by the checker
on boot. `.env` supplies DB creds, admin login/password, session secret.
The optional [private HTTP gateway](./README.md#private-http-gateway) uses a
restricted DB login and is not routed through the public nginx instance.
+198 -3
View File
@@ -16,6 +16,7 @@ for the full feature wishlist.
| `checker` | Go (`cmd/checker`) | Worker: fetch → canonicalize/dedup → check → geo → write sessions |
| `api` | Go (`cmd/api`) | REST panel API + public subscription endpoints |
| `web` | React + Vite + TS + Tailwind + nginx | SPA panel (Dashboard / Proxies / Subscriptions / Settings), also routes `/api` + `/sub` |
| `http-gateway` | Go (`cmd/http-gateway`), optional `gateway` profile | Private HTTP/CONNECT proxy and filtered catalog API |
The vless/vmess/trojan/ss dialers, upstream parser, geoip and fetcher are reused
from `tessero-checker`; the canonicalization, session model, DB layer,
@@ -57,6 +58,200 @@ transaction flips the `is_current` pointer. Per-canonical history (uptime,
consecutive failures) is kept even while a proxy is currently invalid, but only
working proxies from the current session are ever shown or served.
## Private HTTP gateway
The optional `gateway` Compose profile publishes two **separate** HTTP ports:
8081 for forward proxy traffic (plain HTTP and HTTPS through CONNECT), and
8082 for the catalog and status API. Both bind to host loopback by default.
For remote clients, bind both 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 either port on the WAN: both client authentication headers
are cleartext on the hop to the gateway. Public nginx does not route either port.
The normal stack does not require any `GATEWAY_*` variables.
### Provisioning
1. **Enroll only authorized peers.** 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
snapshot. In `GATEWAY_UPSTREAM_NETWORKS`, list 1-32 unique public peer IPs or
canonical CIDRs you manage or are authorized to use, IPv4 `/24` or narrower,
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. **Allow only intended destinations.** Set `GATEWAY_ALLOWED_DESTINATIONS`
to exact DNS names with ports, separated by commas, for example
`origin.example:80,origin.example:443,probe.example:443`. The names must
resolve exclusively to public addresses. Set `GATEWAY_PROBE_URL` to a fixed
operator-owned HTTPS URL, for example `https://probe.example/gateway-check`,
with no credentials, query, or fragment. Its authority must be in the list;
it must return exactly `204` without a redirect and have a trusted TLS
certificate. The control endpoint must be reachable directly from the
gateway and through each enrolled peer. CONNECT restricts the TCP destination,
not URL paths inside TLS; the gateway does not decrypt the tunnel.
3. **Provision a restricted database login.** Start the updated checker to apply
its schema during an approved maintenance window; the gateway does not run
migrations. As a PostgreSQL role administrator on the same database, create
a dedicated non-owner login with no role memberships. Use `\password` in an
interactive `psql` session so the password does not appear in SQL history.
With the default Compose DB name and owner, open it with
`docker compose exec postgres psql -U perchik -d perchik`:
```sql
CREATE ROLE perchik_gateway LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS;
GRANT CONNECT ON DATABASE perchik TO perchik_gateway;
\password perchik_gateway
```
Adjust `perchik` to the configured database name. Then run the checked-in
grants as the schema/object owner (for a non-default schema, pass
`-v gateway_schema=<schema>` and configure the login's `search_path`):
```sh
docker compose exec -T postgres psql -U perchik -d perchik \
-v gateway_role=perchik_gateway < deploy/gateway-grants.sql
```
Keep schema creation and access to checker tables, subscriptions and other
settings off this role, including access inherited through `PUBLIC` or
existing ACLs. The grant script does not revoke preexisting privileges. Set
`GATEWAY_DB_DSN` to this login's connection string, not the checker or admin
API DSN. For Compose the database host is `postgres:5432`; for a database
outside the isolated Compose network use TLS with `sslmode=verify-full`.
4. **Set the address and secrets.** Set `GATEWAY_PUBLIC_PROXY_ADDR` to the
client-reachable `host:port`, for example `127.0.0.1:8081` for local clients
or `[fd12:3456::9]:8081` on a private VPN. This is the address written into
the export, not a container hostname. `GATEWAY_BIND_IP`, `GATEWAY_PROXY_PORT`
and `GATEWAY_API_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`:
```sh
openssl rand -base64 32 | tr '/+' '_-' | tr -d '=\n'
```
Run the generator twice in a private session. Keep values in a restricted
env file or secret manager, not in Git, shell arguments or shared logs.
Use `docker compose config --quiet` for Compose syntax checks; rendered
config and container inspection can expose the environment. Keep the node
secret and DB's `store_uuid` across restarts to preserve existing passwords.
Rotating the API token revokes catalog access only; rotating the node secret
revokes all issued proxy passwords. Recreate **only** the gateway container
after updating its secrets and re-export credentials for affected clients.
### Start and observe
Once the schema, grants, and gateway environment are provisioned:
```sh
docker compose --profile gateway pull http-gateway
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
8081 and 8082 on all interfaces; the Compose host bind settings do not change
these sockets. Keep the host private and restrict the two 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 proxy
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
successful and next scheduled checks. The panel does not receive client secrets.
Set the interval to 15-30 whole minutes (default 20), independent of the main
checker. Only gateway availability and latency are probed on that schedule;
country and speed remain in the last completed checker snapshot. Removed nodes
are unavailable immediately for new connections/requests; successful gateway
checks expire after twice the effective interval.
### Catalog and proxy clients
Send `Authorization: Bearer …` to `GET /v1/proxies` on port 8082. The API always
returns `Cache-Control: no-store`. The same query selects the same rows for any
format:
| Query parameter | Meaning |
| --- | --- |
| `country` | Country codes such as `DE,NL`; `XX` means unknown. |
| `protocol` | `vless`, `vmess`, `trojan` or `ss`. |
| `min_speed_mbps`, `max_latency_ms` | Inclusive thresholds; missing speed does not match a specified minimum. Latency is the latest gateway probe; maximum latency is an integer. |
| `sort` | `id` (default), `speed` (descending, unmeasured last), `latency` or `country`. Ties use ascending proxy ID. |
| `limit`, `offset` | Positive limit and nonnegative offset; default is all matching ready rows. |
| `format` | `json` (default), `csv`, `txt`, or `proxy-url-list-txt`. |
Both `country` and `protocol` support comma-separated or repeated values (OR
within a field, AND across fields). JSON includes `total` before pagination,
`session_finished_at` for the main snapshot, and `checked_at` for each gateway
check. No matching nodes yields an empty successful response; an unavailable
gateway or DB yields `503`, not a successful empty list. JSON and CSV include
the stable `node-<proxy_id>` username and derived password. `txt` uses
`host:port:username:password` (brackets around IPv6), and
`proxy-url-list-txt` emits HTTP proxy URLs, not upstream provider links.
For example, prepare `$gateway_headers` in a private directory with one
`Authorization: Bearer <catalog token>` line and mode `0600`. Keep every export
private, including TXT and CSV. Use a separate curl config at `$proxy_client`
with a line `proxy = "<exported HTTP proxy URL>"` for a selected node; its
username/password authenticate to port 8081 on every request:
```sh
umask 077
curl --disable --fail --silent --show-error --noproxy '*' \
--header "@$gateway_headers" --output "$gateway_export" \
'http://127.0.0.1:8082/v1/proxies?country=DE,NL&min_speed_mbps=5&sort=latency&format=proxy-url-list-txt'
curl --disable --fail --silent --show-error --noproxy '' \
--config "$proxy_client" 'http://origin.example/check'
curl --disable --fail --silent --show-error --noproxy '' \
--config "$proxy_client" 'https://origin.example/check'
```
Replace the illustrative `.example` names with your configured operator-owned
origins. Never use verbose wire traces or print export contents in shared logs.
### Isolated canary and rollback
Run the local contract gate (`bash tests/gateway/verify.sh`) before a live
canary. For the canary, use the **same pinned gateway image** you intend to
deploy, a unique Compose project and database/volume, and a separate protected
`CANARY_ENV_FILE` outside the checkout. Set unused loopback ports (for example
18081/18082), adjust the advertised port, and use one-off DB credentials and
gateway secrets. In a clean shell (no inherited production env overrides),
start only the canary database, apply the current schema and grants there, and
publish a snapshot containing only your canary peers. The usual checker may
publish it on the canary database using a controlled source and probe setup;
do not copy a production snapshot or trigger a production checker run.
```sh
docker compose --env-file "$CANARY_ENV_FILE" -p gateway-canary up -d postgres
# After the canary DB is healthy, initialize its schema, role and snapshot.
docker compose --env-file "$CANARY_ENV_FILE" -p gateway-canary --profile gateway \
up -d --no-deps http-gateway
```
Verify both listeners and each of SS, Trojan, VMess and VLESS with a dedicated
authorized peer. On each route, compare all four filtered exports, use an
exported credential for HTTP and HTTPS, and match a one-off request nonce to
the expected route at your own origin/peer. A 200 or an exit IP alone does not
prove routing. Recreate only the gateway and verify the same login still works
with the unchanged canary database and node secret. Keep only safe IDs, timings,
formats and outcomes in the report. Mark scenarios blocked if an authorized
peer or operator-owned origin is unavailable; do not substitute public proxies.
If the gate or canary fails, leave the production profile off. To roll back an
enabled gateway, stop just that service (`docker compose --profile gateway stop
http-gateway`, using the same project and env file as the instance) and remove
`gateway` from any startup profile selection. Omitting the profile alone does
not stop an existing container. Leave the additive schema and data intact; do
not run `down -v` or restart the checker, API or web to disable this profile.
## Operations
**Check failures.** A failed or cancelled check session does not replace the
@@ -110,6 +305,6 @@ npm run dev
## CI
`.gitea/workflows/ci.yml` runs `go vet` / `go test` / `go build` and the frontend
build on every push, then (on `main`) builds and pushes the three images to the
Gitea container registry.
`.gitea/workflows/ci.yml` runs Go validation, the frontend build and the
`gateway-contract` job. Both validation jobs must pass before release builds
publish the four service images to the Gitea container registry.
+72
View File
@@ -0,0 +1,72 @@
// Command http-gateway serves the private gateway catalog and forward proxy.
package main
import (
"context"
"errors"
"log/slog"
"os"
"os/signal"
"syscall"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
"git.eeee.moe/omar/zhguchiy_perchik/internal/gateway"
)
func main() {
log := slog.New(slog.NewTextHandler(os.Stdout, nil))
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
log.Info("starting HTTP gateway")
err := run(ctx)
stop()
if err != nil {
log.Error("HTTP gateway stopped", "error", err)
os.Exit(1)
}
log.Info("HTTP gateway stopped")
}
func run(ctx context.Context) error {
cfg, err := gateway.LoadConfig()
if err != nil {
return err
}
store, err := connectDatabase(ctx, cfg.DBDSN)
if err != nil {
if ctx.Err() != nil {
return nil
}
return err
}
defer store.Close()
// Run binds both 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) {
return gateway.NewRuntimeComponents(store, cfg, endpoints)
},
})
}
func connectDatabase(ctx context.Context, dsn string) (*db.DB, error) {
startup, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
retry := time.NewTimer(time.Second)
retry.Stop()
defer retry.Stop()
for startup.Err() == nil {
store, err := db.New(startup, dsn)
if err == nil {
return store, nil
}
// Driver errors can contain connection details. Never log them here.
retry.Reset(time.Second)
select {
case <-startup.Done():
case <-retry.C:
}
}
return nil, errors.New("gateway database connection deadline expired")
}
+14
View File
@@ -0,0 +1,14 @@
# Private HTTP gateway. Build context is the repo root.
FROM golang:1.26 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY cmd/http-gateway/ ./cmd/http-gateway/
COPY internal/ ./internal/
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/http-gateway ./cmd/http-gateway
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/http-gateway /http-gateway
USER nonroot:nonroot
EXPOSE 8081 8082
ENTRYPOINT ["/http-gateway"]
+27
View File
@@ -0,0 +1,27 @@
-- Run as the schema/object owner after the checker applies its schema:
-- psql -d perchik -v gateway_role=perchik_gateway -f deploy/gateway-grants.sql
-- gateway_role is an existing dedicated, non-owner login with database CONNECT
-- and no broader inherited privileges. This script does not change other ACLs.
-- For a non-default schema, pass -v gateway_schema=<schema> and set the role's
-- connection search_path accordingly.
\set ON_ERROR_STOP on
\if :{?gateway_schema}
\else
SELECT current_schema() AS gateway_schema \gset
\endif
BEGIN;
GRANT USAGE ON SCHEMA :"gateway_schema" TO :"gateway_role";
GRANT SELECT ON :"gateway_schema".gateway_candidates,
:"gateway_schema".gateway_current_session,
:"gateway_schema".gateway_check_interval
TO :"gateway_role";
GRANT SELECT, INSERT, UPDATE (tested_membership_id, ok, checked_at, latency_ms)
ON :"gateway_schema".gateway_node_health TO :"gateway_role";
GRANT SELECT, UPDATE (heartbeat_at, last_started_at, last_attempt_finished_at,
last_success_at, next_full_at, phase, last_error_code)
ON :"gateway_schema".gateway_runtime TO :"gateway_role";
GRANT EXECUTE ON FUNCTION :"gateway_schema".gateway_lock_current(bigint),
:"gateway_schema".gateway_lock_memberships(bigint, bigint[])
TO :"gateway_role";
COMMIT;
+4
View File
@@ -15,3 +15,7 @@ services:
build:
context: .
dockerfile: deploy/Dockerfile.web
http-gateway:
build:
context: .
dockerfile: deploy/Dockerfile.http-gateway
+24 -2
View File
@@ -41,8 +41,10 @@ services:
environment:
DB_DSN: postgres://${POSTGRES_USER:-perchik}:${POSTGRES_PASSWORD:-perchik}@postgres:5432/${POSTGRES_DB:-perchik}?sslmode=disable
ADMIN_USER: ${ADMIN_USER:-admin}
ADMIN_PASSWORD: ${ADMIN_PASSWORD:?ADMIN_PASSWORD is required}
SESSION_SECRET: ${SESSION_SECRET:?SESSION_SECRET is required}
# The API requires both at startup. Unrelated targets (e.g. a standalone
# gateway canary) can load this file without panel credentials.
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
SESSION_SECRET: ${SESSION_SECRET:-}
LOG_LEVEL: ${LOG_LEVEL:-info}
depends_on:
postgres:
@@ -56,5 +58,25 @@ services:
depends_on:
- api
http-gateway:
image: ${REGISTRY:-git.eeee.moe/omar/zhguchiy_perchik}/http-gateway:${TAG:-latest}
profiles: [gateway]
restart: unless-stopped
stop_grace_period: 15s
environment:
GATEWAY_DB_DSN: ${GATEWAY_DB_DSN:-}
GATEWAY_PUBLIC_PROXY_ADDR: ${GATEWAY_PUBLIC_PROXY_ADDR:-}
GATEWAY_API_TOKEN: ${GATEWAY_API_TOKEN:-}
GATEWAY_NODE_SECRET: ${GATEWAY_NODE_SECRET:-}
GATEWAY_PROBE_URL: ${GATEWAY_PROBE_URL:-}
GATEWAY_ALLOWED_DESTINATIONS: ${GATEWAY_ALLOWED_DESTINATIONS:-}
GATEWAY_UPSTREAM_NETWORKS: ${GATEWAY_UPSTREAM_NETWORKS:-}
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"
depends_on:
postgres:
condition: service_healthy
volumes:
pgdata:
+46
View File
@@ -18,6 +18,7 @@
"tailwind-merge": "^2.5.5"
},
"devDependencies": {
"@playwright/test": "1.65.1",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
@@ -812,6 +813,22 @@
"node": ">= 8"
}
},
"node_modules/@playwright/test": {
"version": "1.65.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.1.tgz",
"integrity": "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.65.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@remix-run/router": {
"version": "1.23.3",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz",
@@ -2319,6 +2336,35 @@
"node": ">= 6"
}
},
"node_modules/playwright": {
"version": "1.65.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz",
"integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.65.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.65.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz",
"integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/postcss": {
"version": "8.5.16",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz",
+2
View File
@@ -7,6 +7,7 @@
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"test:gateway-ui": "playwright test -c playwright.gateway.config.ts",
"typecheck": "tsc -b --noEmit"
},
"dependencies": {
@@ -20,6 +21,7 @@
"tailwind-merge": "^2.5.5"
},
"devDependencies": {
"@playwright/test": "1.65.1",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
+34
View File
@@ -0,0 +1,34 @@
import { defineConfig, devices } from "@playwright/test";
import { tmpdir } from "node:os";
import { isAbsolute, join } from "node:path";
const rawURL = process.env.GATEWAY_UI_BASE_URL;
if (!rawURL) throw new Error("Set GATEWAY_UI_BASE_URL to the disposable Vite server");
const baseURL = new URL(rawURL);
if (
baseURL.protocol !== "http:" ||
!["127.0.0.1", "[::1]", "localhost"].includes(baseURL.hostname) ||
!baseURL.port || baseURL.username || baseURL.password ||
baseURL.pathname !== "/" || baseURL.search || baseURL.hash
) {
throw new Error("GATEWAY_UI_BASE_URL must be a loopback HTTP origin with an explicit port");
}
const artifactRoot = process.env.GATEWAY_UI_ARTIFACTS_DIR ?? tmpdir();
if (!isAbsolute(artifactRoot)) throw new Error("GATEWAY_UI_ARTIFACTS_DIR must be absolute");
export default defineConfig({
testDir: "./tests",
testMatch: "gateway-settings.spec.ts",
outputDir: join(artifactRoot, `gateway-ui-${baseURL.port}`),
workers: 1, // The real settings tests share one disposable database.
retries: 0,
use: {
...devices["Desktop Chrome"],
baseURL: baseURL.origin,
screenshot: "off",
trace: "off",
video: "off",
},
});
+6 -1
View File
@@ -2,6 +2,7 @@ import type {
CheckerStatus,
Dashboard,
Facets,
GatewayStatus,
Proxy,
Session,
SessionDetail,
@@ -19,10 +20,11 @@ export class ApiError extends Error {
}
}
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
async function request<T>(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<T> {
const res = await fetch(path, {
method,
credentials: "include",
signal,
headers: body !== undefined ? { "Content-Type": "application/json" } : undefined,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
@@ -84,6 +86,9 @@ export const api = {
settings: () => request<Settings>("GET", "/api/v1/settings"),
updateSettings: (body: Settings) => request<{ status: string }>("PATCH", "/api/v1/settings", body),
// gateway
gatewayStatus: (signal?: AbortSignal) => request<GatewayStatus>("GET", "/api/v1/gateway/status", undefined, signal),
// checker
checkerStatus: () => request<CheckerStatus>("GET", "/api/v1/checker/status"),
checkerRun: () => request<{ status: string }>("POST", "/api/v1/checker/run"),
+13
View File
@@ -151,6 +151,19 @@ export interface CheckerStatus {
current: Session | null;
}
export interface GatewayStatus {
state: "not_started" | "offline" | "idle" | "checking" | "degraded";
session_id: number | null;
candidate_count: number;
ready_count: number;
interval_minutes: number | null;
last_started_at: string | null;
last_attempt_finished_at: string | null;
last_success_at: string | null;
next_full_at: string | null;
last_error_code: string | null;
}
export interface SessionDetail {
session: Session;
protocols?: ProtocolStat[];
+139
View File
@@ -0,0 +1,139 @@
import { useId, useRef, useState, type FormEvent } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Save } from "lucide-react";
import { Badge, Button, Input, Label } from "@/components/ui";
import { api } from "@/lib/api";
import { fmtDateTime, fmtInt } from "@/lib/format";
import type { GatewayStatus, Settings } from "@/lib/types";
const intervalKey = "gateway_check_interval_minutes";
const settingsQueryKey = ["settings"];
const statusQueryKey = ["gateway-status"];
const intervalError = "Enter a whole number from 15 to 30.";
const gatewayStates = {
not_started: { label: "Not started", color: "muted" },
offline: { label: "Offline", color: "rose" },
idle: { label: "Idle", color: "signal" },
checking: { label: "Checking", color: "peri" },
degraded: { label: "Degraded", color: "amber" },
} as const satisfies Record<GatewayStatus["state"], { label: string; color: string }>;
function selectInterval(settings: Settings): string | null {
return settings[intervalKey] ?? null;
}
export default function GatewaySettings() {
const id = useId();
const input = useRef<HTMLInputElement>(null);
const qc = useQueryClient();
const settings = useQuery({ queryKey: settingsQueryKey, queryFn: api.settings, select: selectInterval });
const status = useQuery({
queryKey: statusQueryKey,
queryFn: ({ signal }) => api.gatewayStatus(signal),
refetchInterval: 10_000,
});
const current = status.isError ? undefined : status.data;
const lastSuccessAt = current?.last_success_at;
const scheduled = current && current.state !== "offline" && current.state !== "not_started";
const nextFullAt = scheduled ? current.next_full_at : null;
const state = current
? gatewayStates[current.state]
: status.isError || status.isPaused
? { label: "Unavailable", color: "muted" } as const
: { label: "Loading status", color: "muted" } as const;
const [draft, setDraft] = useState<string | null>(null);
const [invalid, setInvalid] = useState(false);
const interval = draft ?? settings.data ?? current?.interval_minutes?.toString() ?? "";
const waitingForInterval = settings.isLoading && !interval;
const save = useMutation({
mutationFn: (value: string) => api.updateSettings({ [intervalKey]: value }),
onSuccess: async (_, value) => {
await qc.cancelQueries({ queryKey: settingsQueryKey });
qc.setQueryData<Settings>(settingsQueryKey, (previous) => ({ ...previous, [intervalKey]: value }));
setDraft(null);
void qc.invalidateQueries({ queryKey: settingsQueryKey });
void qc.invalidateQueries({ queryKey: statusQueryKey });
},
});
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (save.isPending || waitingForInterval) return;
if (!/^(?:1[5-9]|2[0-9]|30)$/.test(interval)) {
save.reset();
setInvalid(true);
input.current?.focus();
return;
}
save.mutate(interval);
}
return (
<section aria-labelledby={`${id}-heading`} className="panel min-w-0 p-5">
<div className="mb-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
<h2 id={`${id}-heading`} className="font-display text-base font-semibold text-fog">HTTP gateway</h2>
<span role="status"><Badge color={state.color}>{state.label}</Badge></span>
</div>
<dl className="grid gap-3 sm:grid-cols-3">
<div className="min-w-0">
<dt className="text-sm text-fog-muted">Ready / candidates</dt>
<dd className="mt-1 break-words text-sm">
{current ? (current.session_id === null ? "No published snapshot" : (
<span className="num">{fmtInt(current.ready_count)} / {fmtInt(current.candidate_count)}</span>
)) : "\u2014"}
</dd>
</div>
<div className="min-w-0">
<dt className="text-sm text-fog-muted">Last successful check</dt>
<dd className="mt-1 break-words text-sm">
{lastSuccessAt ? <time dateTime={lastSuccessAt}>{fmtDateTime(lastSuccessAt)}</time> : current ? "Never" : "\u2014"}
</dd>
</div>
<div className="min-w-0">
<dt className="text-sm text-fog-muted">Next full check</dt>
<dd className="mt-1 break-words text-sm">
{nextFullAt ? <time dateTime={nextFullAt}>{fmtDateTime(nextFullAt)}</time> : scheduled ? "Not scheduled" : "\u2014"}
</dd>
</div>
</dl>
<form noValidate onSubmit={submit} className="mt-4 border-t border-ink-700 pt-4">
<Label htmlFor={`${id}-interval`} className="text-fog-muted">Check interval (minutes)</Label>
<div className="flex flex-wrap items-center gap-3">
<Input
ref={input}
id={`${id}-interval`}
name={intervalKey}
type="number"
min={15}
max={30}
step={1}
required
value={interval}
readOnly={save.isPending || waitingForInterval}
aria-invalid={invalid || undefined}
aria-describedby={invalid ? `${id}-interval-error` : undefined}
className="h-11 w-28 max-w-full text-base aria-[invalid=true]:border-rose sm:h-9 sm:text-sm"
onChange={(event) => {
setDraft(event.target.value);
setInvalid(false);
if (save.isError || save.isSuccess) save.reset();
}}
/>
<Button type="submit" variant="primary" className="h-11 sm:h-9" disabled={save.isPending || waitingForInterval}>
<Save aria-hidden="true" size={15} />
Save
</Button>
</div>
<div id={`${id}-interval-error`} role="alert" className="text-sm text-rose [&:not(:empty)]:mt-2">
{invalid ? intervalError : save.isError ? "Could not save the gateway interval. Try again." : null}
</div>
<div role="status" className="text-sm text-fog-muted [&:not(:empty)]:mt-2">
{save.isSuccess ? "Interval saved." : save.isPending ? "Saving interval..." : waitingForInterval ? "Loading saved interval..." : null}
</div>
</form>
</section>
);
}
+13 -1
View File
@@ -6,6 +6,7 @@ import { Badge, Button, Card, CardTitle, Input, Label, Select, Spinner, Toggle }
import { useToast } from "@/components/Toast";
import { fmtAgo, fmtInt } from "@/lib/format";
import type { Settings as SettingsMap, Source } from "@/lib/types";
import GatewaySettings from "./GatewaySettings";
export default function Settings() {
return (
@@ -16,6 +17,7 @@ export default function Settings() {
</div>
<SourcesPanel />
<CheckParamsPanel />
<GatewaySettings />
</div>
);
}
@@ -185,10 +187,20 @@ const KEYS = {
tgFinish: "telegram_notify_finish",
};
function selectCheckSettings(settings: SettingsMap): SettingsMap {
const checkSettings: SettingsMap = {};
for (const key of Object.values(KEYS)) {
const value = settings[key];
if (value !== undefined) checkSettings[key] = value;
}
return checkSettings;
}
function CheckParamsPanel() {
const toast = useToast();
const qc = useQueryClient();
const q = useQuery({ queryKey: ["settings"], queryFn: api.settings });
// A gateway-only cache update must not reset unsaved checker or Telegram fields.
const q = useQuery({ queryKey: ["settings"], queryFn: api.settings, select: selectCheckSettings });
const [form, setForm] = React.useState<SettingsMap>({});
React.useEffect(() => {
+279
View File
@@ -0,0 +1,279 @@
import { devices, expect, test, type APIRequestContext, type Page, type Response } from "@playwright/test";
const settingsPath = "/api/v1/settings";
const statusPath = "/api/v1/gateway/status";
const intervalKey = "gateway_check_interval_minutes";
const speedURLKey = "speedtest_url";
const checkingStatus = {
state: "checking",
session_id: 41,
candidate_count: 7,
ready_count: 3,
interval_minutes: 20,
last_started_at: "2026-09-15T10:20:00Z",
last_attempt_finished_at: "2026-09-15T10:01:00Z",
last_success_at: "2026-09-15T10:01:00Z",
next_full_at: "2026-09-15T10:40:00Z",
last_error_code: null as string | null,
};
function requiredEnv(name: string) {
const value = process.env[name];
if (!value) throw new Error(`Set ${name} from the disposable gateway UI harness`);
return value;
}
function gateway(page: Page) {
return page.getByRole("region", { name: "HTTP gateway", exact: true });
}
function intervalInput(page: Page) {
return gateway(page).getByRole("spinbutton", { name: "Check interval (minutes)", exact: true });
}
function isResponse(response: Response, path: string, method = "GET") {
return new URL(response.url()).pathname === path && response.request().method() === method;
}
async function signIn(page: Page) {
await page.goto("/login");
await page.getByLabel("Operator").fill(requiredEnv("GATEWAY_UI_USERNAME"));
await page.getByLabel("Passphrase").fill(requiredEnv("GATEWAY_UI_PASSWORD"));
const [response] = await Promise.all([
page.waitForResponse((r) => isResponse(r, "/api/v1/auth/login", "POST")),
page.getByRole("button", { name: "Enter console" }).click(),
]);
expect(response.status()).toBe(200);
await page.waitForURL((url) => url.pathname === "/");
}
async function readSettings(request: APIRequestContext): Promise<Record<string, string>> {
const response = await request.get(settingsPath);
expect(response.status()).toBe(200);
return response.json();
}
async function patchSettings(request: APIRequestContext, data: Record<string, string>) {
const response = await request.patch(settingsPath, { data });
expect(response.status()).toBe(200);
}
async function patchFromUI(page: Page, action: () => Promise<void>) {
const [response] = await Promise.all([
page.waitForResponse((r) => isResponse(r, settingsPath, "PATCH")),
action(),
]);
expect(response.status()).toBe(200);
return response.request().postDataJSON();
}
async function nextPoll(page: Page) {
const [response] = await Promise.all([
page.waitForResponse((r) => isResponse(r, statusPath)),
page.clock.fastForward(10_000),
]);
expect(response.status()).toBe(200);
return response;
}
function assertNoGatewaySecrets(text: string) {
for (const name of ["GATEWAY_API_TOKEN", "GATEWAY_NODE_SECRET"]) {
// Assert a boolean so a regression cannot print the value in the reporter.
expect(text.includes(requiredEnv(name)), `${name} must not reach the browser`).toBe(false);
}
}
async function captureSettings(page: Page, path: string) {
await signIn(page);
const [response] = await Promise.all([
page.waitForResponse((r) => isResponse(r, statusPath)),
page.goto("/settings"),
]);
expect(response.status()).toBe(200);
assertNoGatewaySecrets(await response.text());
await expect(intervalInput(page)).not.toHaveValue("");
await expect(gateway(page).getByText("Not started", { exact: true })).toBeVisible();
assertNoGatewaySecrets(await page.content());
await page.screenshot({ path, fullPage: true, animations: "disabled" });
}
test("requires operator auth and saves 15 and 30 across actual reloads", async ({ page }) => {
expect((await page.request.get(statusPath)).status()).toBe(401);
await page.goto("/settings");
await expect(page).toHaveURL(/\/login$/);
await signIn(page);
const original = (await readSettings(page.request))[intervalKey];
expect(original).toBe("20");
try {
await page.goto("/settings");
const interval = intervalInput(page);
await expect(interval).toHaveValue("20");
await expect(interval).toHaveAttribute("min", "15");
await expect(interval).toHaveAttribute("max", "30");
await expect(interval).toHaveAttribute("step", "1");
for (const value of ["15", "30"]) {
await interval.fill(value);
const payload = await patchFromUI(page, () => gateway(page).getByRole("button", { name: "Save", exact: true }).click());
expect(payload).toEqual({ [intervalKey]: value });
await page.reload();
await expect(interval).toHaveValue(value);
expect((await readSettings(page.request))[intervalKey]).toBe(value);
}
} finally {
await patchSettings(page.request, { [intervalKey]: original });
}
});
test("keyboard validation blocks bad drafts and the server rejects the whole invalid PATCH", async ({ page }) => {
await signIn(page);
const baseline = await readSettings(page.request);
let patchCount = 0;
page.on("request", (request) => {
if (new URL(request.url()).pathname === settingsPath && request.method() === "PATCH") patchCount++;
});
await page.goto("/settings");
const interval = intervalInput(page);
await expect(interval).toHaveValue(baseline[intervalKey]);
const error = gateway(page).getByRole("alert");
for (const value of ["14", "31", "15.5"]) {
await interval.fill(value);
await interval.press("Enter");
await expect(error).toHaveText("Enter a whole number from 15 to 30.");
await expect(interval).toHaveAttribute("aria-invalid", "true");
}
expect(patchCount).toBe(0);
expect((await readSettings(page.request))[intervalKey]).toBe(baseline[intervalKey]);
await interval.fill("20");
await expect(error).toBeHidden();
for (const value of ["14", "31", "15.5", "1e1", " 20"]) {
const response = await page.request.patch(settingsPath, {
data: { [intervalKey]: value, [speedURLKey]: "https://speed.example.test/rejected" },
});
expect(response.status()).toBe(400);
const persisted = await readSettings(page.request);
expect(persisted[intervalKey]).toBe(baseline[intervalKey]);
expect(persisted[speedURLKey]).toBe(baseline[speedURLKey]);
}
});
test("a real status poll and another settings save preserve the interval draft", async ({ page }) => {
await signIn(page);
const baseline = await readSettings(page.request);
try {
await patchSettings(page.request, { [intervalKey]: "20" });
await page.clock.install();
const [response] = await Promise.all([
page.waitForResponse((r) => isResponse(r, statusPath)),
page.goto("/settings"),
]);
expect(response.status()).toBe(200);
await expect(gateway(page).getByText("Not started", { exact: true })).toBeVisible();
const interval = intervalInput(page);
await expect(interval).toHaveValue("20");
await interval.fill("30");
await patchSettings(page.request, { [intervalKey]: "15" });
const refreshed = await nextPoll(page);
expect((await refreshed.json()).interval_minutes).toBe(15);
await expect(interval).toHaveValue("30");
const speedURL = "https://speed.example.test/saved";
await page.getByPlaceholder(/__down\?bytes=10000000/).fill(speedURL);
const other = await patchFromUI(page, () => page.getByRole("button", { name: "Save settings", exact: true }).click());
expect(Object.hasOwn(other, intervalKey), "Other settings save must omit the gateway interval").toBe(false);
expect(other[speedURLKey]).toBe(speedURL);
await expect(page.getByText("Settings saved", { exact: true })).toBeVisible();
await expect(interval).toHaveValue("30");
let persisted = await readSettings(page.request);
expect(persisted[intervalKey]).toBe("15");
expect(persisted[speedURLKey]).toBe(speedURL);
expect(await patchFromUI(page, () => interval.press("Enter"))).toEqual({ [intervalKey]: "30" });
await page.reload();
await expect(interval).toHaveValue("30");
persisted = await readSettings(page.request);
expect(persisted[speedURLKey]).toBe(speedURL);
} finally {
await patchSettings(page.request, {
[intervalKey]: baseline[intervalKey],
[speedURLKey]: baseline[speedURLKey],
});
}
});
test("real status is sanitized and distinguishes no published snapshot from zero ready", async ({ page }) => {
await signIn(page);
const [response] = await Promise.all([
page.waitForResponse((r) => isResponse(r, statusPath)),
page.goto("/settings"),
]);
expect(response.status()).toBe(200);
assertNoGatewaySecrets(await response.text());
const status = await response.json();
expect(Object.keys(status).sort()).toEqual(Object.keys(checkingStatus).sort());
expect(status).toMatchObject({ state: "not_started", session_id: null, candidate_count: 0, ready_count: 0 });
await expect(gateway(page).getByText("Not started", { exact: true })).toBeVisible();
await expect(gateway(page).getByText("No published snapshot", { exact: true })).toBeVisible();
await expect(gateway(page).getByText("0 / 0", { exact: true })).toHaveCount(0);
assertNoGatewaySecrets(await page.content());
await page.route(statusPath, (route) => route.fulfill({
json: { ...status, session_id: 41 },
}));
await page.reload();
await expect(gateway(page).getByText("0 / 0", { exact: true })).toBeVisible();
await expect(gateway(page).getByText("No published snapshot", { exact: true })).toHaveCount(0);
});
test("status polls show checking metrics, degraded and offline", async ({ page }) => {
await signIn(page);
let status = checkingStatus;
await page.route(statusPath, (route) => route.fulfill({ json: status }));
await page.clock.install();
await page.goto("/settings");
const panel = gateway(page);
await expect(panel.getByText("Checking", { exact: true })).toBeVisible();
await expect(panel.getByText("Ready / candidates", { exact: true })).toBeVisible();
await expect(panel.getByText("3 / 7", { exact: true })).toBeVisible();
await expect(panel.getByText("Last successful check", { exact: true })).toBeVisible();
await expect(panel.getByText("Next full check", { exact: true })).toBeVisible();
await expect(panel.locator(`time[datetime="${checkingStatus.last_success_at}"]`)).toBeVisible();
await expect(panel.locator(`time[datetime="${checkingStatus.next_full_at}"]`)).toBeVisible();
status = { ...status, state: "degraded", last_error_code: "control" };
await nextPoll(page);
await expect(panel.getByText("Degraded", { exact: true })).toBeVisible();
status = { ...status, state: "offline" };
await nextPoll(page);
await expect(panel.getByText("Offline", { exact: true })).toBeVisible();
});
test("a failed status request is unavailable, not offline or zero ready", async ({ page }) => {
await signIn(page);
await page.route(statusPath, (route) => route.fulfill({ status: 503, json: { error: "unavailable" } }));
await page.goto("/settings");
const panel = gateway(page);
await expect(panel.getByText("Unavailable", { exact: true })).toBeVisible();
await expect(panel.getByText("Offline", { exact: true })).toHaveCount(0);
await expect(panel.getByText("0 / 0", { exact: true })).toHaveCount(0);
await expect(intervalInput(page)).toBeEditable();
});
test("captures desktop Settings in temporary artifacts", async ({ page }, testInfo) => {
await captureSettings(page, testInfo.outputPath("gateway-settings-desktop.png"));
});
test.describe("mobile", () => {
const { viewport, isMobile, hasTouch, deviceScaleFactor, userAgent } = devices["Pixel 7"];
test.use({ viewport, isMobile, hasTouch, deviceScaleFactor, userAgent });
test("captures mobile Settings in temporary artifacts", async ({ page }, testInfo) => {
await captureSettings(page, testInfo.outputPath("gateway-settings-mobile.png"));
});
});
+157
View File
@@ -0,0 +1,157 @@
package api
import (
"context"
"crypto/rand"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
"git.eeee.moe/omar/zhguchiy_perchik/internal/config"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
)
func TestGatewaySettingsREST(t *testing.T) {
database := gatewaySettingsTestDB(t)
s := NewServer(Config{DB: database, Log: slog.New(slog.DiscardHandler), SessionSecret: rand.Text()})
handler := s.Handler()
cookie := &http.Cookie{Name: sessionCookie, Value: s.signToken(time.Now().Add(time.Hour))}
const path = "/api/v1/settings"
const key = config.KeyGatewayCheckIntervalMinutes
request := func(t *testing.T, method, body string, authenticated bool, want int) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequestWithContext(t.Context(), method, path, strings.NewReader(body))
if authenticated {
r.AddCookie(cookie)
}
if method == http.MethodPatch {
r.Header.Set("Content-Type", "application/json")
}
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
if w.Code != want {
t.Fatalf("%s settings: status %d, want %d", method, w.Code, want)
}
return w
}
read := func(t *testing.T) map[string]string {
t.Helper()
res := request(t, http.MethodGet, "", true, http.StatusOK)
var settings map[string]string
if err := json.Unmarshal(res.Body.Bytes(), &settings); err != nil {
t.Fatal("could not decode settings response")
}
return settings
}
request(t, http.MethodGet, "", false, http.StatusUnauthorized)
request(t, http.MethodPatch, `{"gateway_check_interval_minutes":"15"}`, false, http.StatusUnauthorized)
initial := read(t)
if initial[key] != "20" || initial[config.KeyWorkers] == "" {
t.Fatal("the settings response did not include the default interval and existing settings")
}
for _, value := range []string{`"14"`, `"31"`, `"15.5"`, `"+20"`, `"020"`, `" 20"`, `""`, `15`, `null`, `"invalid-interval-marker"`} {
t.Run("invalid="+value, func(t *testing.T) {
body := `{"gateway_check_interval_minutes":` + value + `,"workers":"17"}`
res := request(t, http.MethodPatch, body, true, http.StatusBadRequest)
if strings.Contains(res.Body.String(), "invalid-interval-marker") {
t.Fatal("validation response echoed an invalid setting value")
}
got := read(t)
if got[key] != initial[key] || got[config.KeyWorkers] != initial[config.KeyWorkers] {
t.Fatal("rejected PATCH modified settings")
}
})
}
for _, value := range []string{"15", "30"} {
body := `{"gateway_check_interval_minutes":"` + value + `"}`
request(t, http.MethodPatch, body, true, http.StatusOK)
got := read(t)
if got[key] != value || got[config.KeyWorkers] != initial[config.KeyWorkers] {
t.Fatalf("could not save interval %s independently of other settings", value)
}
}
const invalidStored = "invalid-stored-interval-marker"
if err := database.SetSettings(t.Context(), map[string]string{
key: invalidStored, "gateway_node_secret": "unused-secret-placeholder",
}); err != nil {
t.Fatal("could not seed malformed gateway settings")
}
request(t, http.MethodPatch, `{"workers":"17"}`, true, http.StatusOK)
got := read(t)
if _, present := got[key]; present {
t.Fatal("settings response exposed the malformed interval")
}
if _, present := got["gateway_node_secret"]; present {
t.Fatal("settings response exposed a noneditable gateway credential")
}
if got[config.KeyWorkers] != "17" {
t.Fatal("a corrupt interval blocked an unrelated settings update")
}
if stored, present, err := database.GetSetting(t.Context(), key); err != nil || !present || stored != invalidStored {
t.Fatal("updating an unrelated setting changed the malformed value needed for gateway status")
}
request(t, http.MethodPatch, `{"gateway_check_interval_minutes":"20"}`, true, http.StatusOK)
if read(t)[key] != "20" {
t.Fatal("could not repair the malformed interval using PATCH")
}
}
func gatewaySettingsTestDB(t *testing.T) *db.DB {
t.Helper()
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("set TEST_DATABASE_URL to a PostgreSQL test database")
}
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
admin, err := db.New(ctx, dsn)
if err != nil {
t.Fatal("could not connect to the test database")
}
t.Cleanup(admin.Close)
schema := "gateway_settings_" + strings.ToLower(rand.Text())
identifier := pgx.Identifier{schema}.Sanitize()
if _, err := admin.Pool().Exec(ctx, "CREATE SCHEMA "+identifier); err != nil {
t.Fatal("could not create the isolated settings schema")
}
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := admin.Pool().Exec(ctx, "DROP SCHEMA "+identifier+" CASCADE"); err != nil {
t.Error("could not drop the isolated settings schema")
}
})
scopedDSN := dsn + " search_path=" + schema
if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {
uri, err := url.Parse(dsn)
if err != nil {
t.Fatal("could not parse the test database URI")
}
params := uri.Query()
params.Set("search_path", schema)
uri.RawQuery = params.Encode()
scopedDSN = uri.String()
}
database, err := db.New(ctx, scopedDSN)
if err != nil {
t.Fatal("could not connect to the isolated settings schema")
}
t.Cleanup(database.Close)
if err := database.ApplySchema(ctx); err != nil {
t.Fatal("could not apply the embedded test schema:", err)
}
return database
}
+21
View File
@@ -0,0 +1,21 @@
package api
import (
"net/http"
"time"
)
func (s *Server) gatewayStatusHandler() http.Handler {
authenticated := s.auth(func(w http.ResponseWriter, r *http.Request) {
status, err := s.db.GatewayStatus(r.Context(), time.Time{})
if err != nil {
writeErr(w, http.StatusServiceUnavailable, "gateway status unavailable")
return
}
writeJSON(w, http.StatusOK, status)
})
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "private, no-store")
authenticated.ServeHTTP(w, r)
})
}
+175
View File
@@ -0,0 +1,175 @@
package api
import (
"bytes"
"crypto/rand"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
)
const gatewayStatusTestPath = "/api/v1/gateway/status"
func TestGatewayStatusAuth(t *testing.T) {
s := NewServer(Config{Log: slog.New(slog.DiscardHandler), SessionSecret: rand.Text()})
handler := s.Handler()
for _, tt := range []struct {
name string
cookie string
bearer string
}{
{name: "missing session"},
{name: "expired session", cookie: s.signToken(time.Now().Add(-time.Hour))},
{name: "catalog bearer is not an admin session", bearer: rand.Text()},
} {
t.Run(tt.name, func(t *testing.T) {
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, gatewayStatusTestPath, nil)
if tt.cookie != "" {
r.AddCookie(&http.Cookie{Name: sessionCookie, Value: tt.cookie})
}
if tt.bearer != "" {
r.Header.Set("Authorization", "Bearer "+tt.bearer)
}
res := httptest.NewRecorder()
handler.ServeHTTP(res, r)
assertGatewayStatusResponse(t, res, http.StatusUnauthorized)
})
}
}
func TestGatewayStatusPostgres(t *testing.T) {
database := gatewaySettingsTestDB(t)
var logs bytes.Buffer
s := NewServer(Config{
DB: database,
Log: slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})),
SessionSecret: rand.Text(),
})
handler := s.Handler()
cookie := &http.Cookie{Name: sessionCookie, Value: s.signToken(time.Now().Add(time.Hour))}
request := func(want int) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, gatewayStatusTestPath, nil)
r.AddCookie(cookie)
res := httptest.NewRecorder()
handler.ServeHTTP(res, r)
assertGatewayStatusResponse(t, res, want)
return res
}
read := func() db.GatewayStatus {
t.Helper()
res := request(http.StatusOK)
var fields map[string]json.RawMessage
if err := json.Unmarshal(res.Body.Bytes(), &fields); err != nil {
t.Fatal("invalid gateway status JSON")
}
keys := []string{
"state", "session_id", "candidate_count", "ready_count", "interval_minutes", "last_started_at",
"last_attempt_finished_at", "last_success_at", "next_full_at", "last_error_code",
}
if len(fields) != len(keys) {
t.Fatalf("gateway status has %d fields, want %d", len(fields), len(keys))
}
for _, key := range keys {
if _, ok := fields[key]; !ok {
t.Fatalf("gateway status lacks %q", key)
}
}
var status db.GatewayStatus
if err := json.Unmarshal(res.Body.Bytes(), &status); err != nil {
t.Fatal("invalid gateway status values")
}
if status.IntervalMinutes == nil || *status.IntervalMinutes != 20 {
t.Fatal("gateway status did not report the default interval")
}
return status
}
initial := read()
if initial.State != "not_started" || initial.SessionID != nil || initial.CandidateCount != 0 || initial.ReadyCount != 0 {
t.Fatalf("unexpected status for a fresh schema: %+v", initial)
}
const providerCredential = "gateway-status-fixture-provider-secret"
pool := database.Pool()
var sessionID int64
if err := pool.QueryRow(t.Context(), `INSERT INTO check_sessions (status, is_current, finished_at, valid)
VALUES ('completed', true, now(), 999) RETURNING id`).Scan(&sessionID); err != nil {
t.Fatal("could not seed current session")
}
exec := func(query string, args ...any) {
t.Helper()
if _, err := pool.Exec(t.Context(), query, args...); err != nil {
t.Fatal("could not update gateway status fixture")
}
}
exec(`WITH nodes AS (
INSERT INTO proxies (canonical_url, protocol, host, port)
SELECT 'trojan://' || $2::text || '@' || host, 'trojan', host, 443
FROM (VALUES ('ready.invalid'), ('stale.invalid'), ('pending.invalid')) AS hosts(host)
RETURNING id, canonical_url, protocol, host, port
), memberships AS (
INSERT INTO session_proxies (session_id, proxy_id, canonical_url, protocol, host, port)
SELECT $1, id, canonical_url, protocol, host, port FROM nodes
RETURNING id, proxy_id, host
)
INSERT INTO gateway_node_health (proxy_id, tested_membership_id, ok, checked_at, latency_ms)
SELECT proxy_id, id, true, CASE WHEN host = 'ready.invalid' THEN now() ELSE now() - interval '1 hour' END, 42
FROM memberships WHERE host <> 'pending.invalid'`, sessionID, providerCredential)
exec(`UPDATE gateway_runtime SET heartbeat_at = now(), phase = 'checking',
last_started_at = now(), last_attempt_finished_at = now() - interval '20 minutes',
last_success_at = now() - interval '20 minutes', next_full_at = now() + interval '20 minutes' WHERE id = 1`)
assertCounts := func(state string, candidates, ready int64) db.GatewayStatus {
t.Helper()
status := read()
if status.State != state || status.SessionID == nil || *status.SessionID != sessionID ||
status.CandidateCount != candidates || status.ReadyCount != ready {
t.Fatalf("gateway status state/session/counts = %+v, want %s session %d counts %d/%d", status, state, sessionID, ready, candidates)
}
return status
}
live := assertCounts("checking", 3, 1)
if live.LastStartedAt == nil || live.LastAttemptFinishedAt == nil || live.LastSuccessAt == nil || live.NextFullAt == nil || live.LastErrorCode != nil {
t.Fatal("live gateway status did not report pass timestamps")
}
exec(`UPDATE gateway_runtime SET heartbeat_at = now() - interval '46 seconds', phase = 'degraded', last_error_code = 'control' WHERE id = 1`)
offline := assertCounts("offline", 3, 1)
if offline.LastErrorCode == nil || *offline.LastErrorCode != "control" {
t.Fatal("offline status lost the last sanitized error code")
}
exec(`DELETE FROM session_proxies WHERE session_id = $1 AND host = 'ready.invalid'`, sessionID)
exec(`UPDATE gateway_runtime SET heartbeat_at = now(), phase = 'idle', last_error_code = NULL WHERE id = 1`)
assertCounts("idle", 2, 0)
exec(`ALTER TABLE gateway_runtime RENAME TO gateway_status_fixture_unavailable`)
failure := request(http.StatusServiceUnavailable)
var body map[string]string
if err := json.Unmarshal(failure.Body.Bytes(), &body); err != nil || len(body) != 1 || body["error"] != "gateway status unavailable" {
t.Fatal("database failure did not return only a generic error")
}
for _, secret := range []string{providerCredential, cookie.Value, "gateway_runtime", "SQLSTATE"} {
if strings.Contains(logs.String(), secret) {
t.Fatal("gateway status logged request credentials or database details")
}
}
}
func assertGatewayStatusResponse(t *testing.T, res *httptest.ResponseRecorder, want int) {
t.Helper()
if res.Code != want {
t.Fatalf("gateway status HTTP code = %d, want %d", res.Code, want)
}
if got := res.Header().Get("Cache-Control"); got != "private, no-store" {
t.Fatalf("gateway status Cache-Control = %q, want private, no-store", got)
}
if got := res.Header().Get("Content-Type"); got != "application/json; charset=utf-8" {
t.Fatalf("gateway status Content-Type = %q, want JSON", got)
}
}
+14
View File
@@ -22,6 +22,8 @@ var editableKeys = map[string]struct{}{
config.KeyTelegramChatID: {},
config.KeyTelegramNotifyStart: {},
config.KeyTelegramNotifyFinish: {},
config.KeyGatewayCheckIntervalMinutes: {},
}
func (s *Server) handleGetSettings(w http.ResponseWriter, r *http.Request) {
@@ -33,6 +35,12 @@ func (s *Server) handleGetSettings(w http.ResponseWriter, r *http.Request) {
out := make(map[string]string, len(editableKeys))
for k := range editableKeys {
if v, ok := m[k]; ok {
if k == config.KeyGatewayCheckIntervalMinutes {
if _, err := config.ParseGatewayCheckIntervalMinutes(v); err != nil {
// Do not expose a malformed stored value. Gateway status reports the config error.
continue
}
}
out[k] = v
}
}
@@ -45,6 +53,12 @@ func (s *Server) handleUpdateSettings(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "bad request")
return
}
if interval, ok := req[config.KeyGatewayCheckIntervalMinutes]; ok {
if _, err := config.ParseGatewayCheckIntervalMinutes(interval); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
}
upd := make(map[string]string, len(req))
for k, v := range req {
if _, ok := editableKeys[k]; ok {
+1
View File
@@ -69,6 +69,7 @@ func (s *Server) Handler() http.Handler {
mux.Handle("GET /api/v1/settings", s.auth(s.handleGetSettings))
mux.Handle("PATCH /api/v1/settings", s.auth(s.handleUpdateSettings))
mux.Handle("GET /api/v1/gateway/status", s.gatewayStatusHandler())
mux.Handle("GET /api/v1/checker/status", s.auth(s.handleCheckerStatus))
mux.Handle("POST /api/v1/checker/run", s.auth(s.handleCheckerRun))
+3 -38
View File
@@ -20,6 +20,7 @@ import (
"git.eeee.moe/omar/zhguchiy_perchik/internal/config"
"git.eeee.moe/omar/zhguchiy_perchik/internal/dialer"
"git.eeee.moe/omar/zhguchiy_perchik/internal/geoip"
"git.eeee.moe/omar/zhguchiy_perchik/internal/netpolicy"
"git.eeee.moe/omar/zhguchiy_perchik/internal/upstream"
)
@@ -64,7 +65,7 @@ type Checker struct {
// New builds a Checker. The dispatcher and resolver are safe for concurrent use.
func New(geo *geoip.Resolver, log *slog.Logger) *Checker {
return &Checker{
dispatch: dialer.NewDispatcher(log),
dispatch: dialer.NewDispatcher(log, (&net.Dialer{}).DialContext),
geo: geo,
log: log,
}
@@ -280,48 +281,12 @@ func probeExitIP(ctx context.Context, transport http.RoundTripper, rawURL string
return "", 0, errors.New("exit-IP response too large")
}
ip, err := netip.ParseAddr(strings.Trim(string(body), " \t\r\n"))
if err != nil || ip.Zone() != "" || !isPublicExitIP(ip.Unmap()) {
if err != nil || ip.Zone() != "" || !netpolicy.IsPublicIP(ip.Unmap()) {
return "", 0, errors.New("invalid public exit-IP response")
}
return ip.Unmap().String(), latency, nil
}
// These IANA special-purpose blocks are not filtered by IsGlobalUnicast and
// IsPrivate. For IPv6, restrict to the current global unicast allocation first.
var ipv6GlobalUnicast = netip.MustParsePrefix("2000::/3")
var specialExitIPPrefixes = [...]netip.Prefix{
netip.MustParsePrefix("0.0.0.0/8"),
netip.MustParsePrefix("100.64.0.0/10"),
netip.MustParsePrefix("192.0.0.0/24"),
netip.MustParsePrefix("192.0.2.0/24"),
netip.MustParsePrefix("192.31.196.0/24"),
netip.MustParsePrefix("192.52.193.0/24"),
netip.MustParsePrefix("192.88.99.0/24"),
netip.MustParsePrefix("192.175.48.0/24"),
netip.MustParsePrefix("198.18.0.0/15"),
netip.MustParsePrefix("198.51.100.0/24"),
netip.MustParsePrefix("203.0.113.0/24"),
netip.MustParsePrefix("240.0.0.0/4"),
netip.MustParsePrefix("2001::/23"),
netip.MustParsePrefix("2001:db8::/32"),
netip.MustParsePrefix("2002::/16"),
netip.MustParsePrefix("2620:4f:8000::/48"),
netip.MustParsePrefix("3fff::/20"),
}
func isPublicExitIP(ip netip.Addr) bool {
if !ip.IsGlobalUnicast() || ip.IsPrivate() || (ip.Is6() && !ipv6GlobalUnicast.Contains(ip)) {
return false
}
for _, prefix := range specialExitIPPrefixes {
if prefix.Contains(ip) {
return false
}
}
return true
}
func probeSpeed(ctx context.Context, transport http.RoundTripper, rawURL string) (float64, error) {
resp, startedAt, err := getProbe(ctx, transport, rawURL)
if err != nil {
+19
View File
@@ -4,6 +4,7 @@
package config
import (
"errors"
"strconv"
"time"
)
@@ -25,6 +26,24 @@ const (
KeyTelegramNotifyFinish = "telegram_notify_finish"
)
// KeyGatewayCheckIntervalMinutes controls the gateway monitor, not the checker.
const KeyGatewayCheckIntervalMinutes = "gateway_check_interval_minutes"
// DefaultGatewayCheckIntervalMinutes is used when no interval is stored.
const DefaultGatewayCheckIntervalMinutes = 20
var errGatewayCheckInterval = errors.New("gateway_check_interval_minutes must be a decimal integer from 15 to 30")
// ParseGatewayCheckIntervalMinutes accepts only the canonical decimal values 15 through 30.
func ParseGatewayCheckIntervalMinutes(v string) (int, error) {
if len(v) == 2 {
if n, err := strconv.Atoi(v); err == nil && n >= 15 && n <= 30 {
return n, nil
}
}
return 0, errGatewayCheckInterval
}
// DefaultSpeedTestURL is the bounded HTTPS sample used for new installations.
const DefaultSpeedTestURL = "https://speedtest.selectel.ru/10MB"
+31
View File
@@ -0,0 +1,31 @@
package config
import (
"strconv"
"strings"
"testing"
)
func TestParseGatewayCheckIntervalMinutes(t *testing.T) {
if DefaultGatewayCheckIntervalMinutes != 20 {
t.Fatalf("default = %d, want 20", DefaultGatewayCheckIntervalMinutes)
}
for want := 15; want <= 30; want++ {
got, err := ParseGatewayCheckIntervalMinutes(strconv.Itoa(want))
if err != nil || got != want {
t.Errorf("parse %d = %d, %v", want, got, err)
}
}
for _, invalid := range []string{
"", "0", "14", "31", "-20", "+20", "020", " 20", "20 ", "20\n", "20.0", "2e1",
"0x14", "\uff12\uff10", "999999999999999999999", "invalid-interval-marker",
} {
got, err := ParseGatewayCheckIntervalMinutes(invalid)
if err == nil || got != 0 {
t.Errorf("invalid input %q returned (%d, %v), want zero and an error", invalid, got, err)
}
if err != nil && invalid == "invalid-interval-marker" && strings.Contains(err.Error(), invalid) {
t.Error("parse error exposed the stored value")
}
}
}
+399
View File
@@ -0,0 +1,399 @@
package db
import (
"context"
"errors"
"math"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/config"
"github.com/jackc/pgx/v5"
)
var (
ErrGatewayConfig = errors.New("invalid gateway configuration")
ErrGatewayCatalogFilter = errors.New("invalid gateway catalog filter")
)
// GatewayCandidateSnapshot is the currently published work list for the monitor.
type GatewayCandidateSnapshot struct {
SessionID *int64
SessionFinishedAt *time.Time
IntervalMinutes int
Candidates []GatewayCandidate
}
type GatewayCandidate struct {
ProxyID int64
MembershipID int64
TestedMembershipID *int64
}
// GatewayNode identifies one upstream for dialing. It is not a catalog item.
type GatewayNode struct {
ProxyID int64
MembershipID int64
CanonicalURL string `json:"-"`
}
type GatewayCatalogSort string
const (
GatewaySortID GatewayCatalogSort = "id"
GatewaySortSpeed GatewayCatalogSort = "speed"
GatewaySortLatency GatewayCatalogSort = "latency"
GatewaySortCountry GatewayCatalogSort = "country"
)
// GatewayCatalogFilter contains validated HTTP parameters, without a wire format.
// Its zero value selects all ready nodes in ascending proxy ID order.
type GatewayCatalogFilter struct {
Countries []string
Protocols []string
MinSpeedMbps *float64
MaxLatencyMs *int64
Sort GatewayCatalogSort
Limit *int64
Offset int64
}
type GatewayCatalogResult struct {
SessionID *int64 `json:"session_id"`
SessionFinishedAt *time.Time `json:"session_finished_at"`
AsOf time.Time `json:"as_of"`
Total int64 `json:"total"`
Items []GatewayCatalogItem `json:"items"`
}
// GatewayCatalogItem contains only the snapshot and probe fields safe to export.
// The gateway combines these with client connection details separately.
type GatewayCatalogItem struct {
ProxyID int64 `json:"proxy_id,string"`
Country string `json:"country"`
Protocol string `json:"protocol"`
ExitIP string `json:"exit_ip"`
SpeedMbps *float64 `json:"speed_mbps"`
LatencyMs int32 `json:"latency_ms"`
CheckedAt time.Time `json:"checked_at"`
}
type GatewayStatus struct {
State string `json:"state"`
SessionID *int64 `json:"session_id"`
CandidateCount int64 `json:"candidate_count"`
ReadyCount int64 `json:"ready_count"`
IntervalMinutes *int `json:"interval_minutes"`
LastStartedAt *time.Time `json:"last_started_at"`
LastAttemptFinishedAt *time.Time `json:"last_attempt_finished_at"`
LastSuccessAt *time.Time `json:"last_success_at"`
NextFullAt *time.Time `json:"next_full_at"`
LastErrorCode *string `json:"last_error_code"`
}
const (
gatewayReadSettings = `(SELECT value FROM gateway_check_interval)`
gatewayReadClock = `COALESCE($1::timestamptz, statement_timestamp())`
gatewayReadMetadata = `SELECT s.session_id, s.session_finished_at, ` + gatewayReadClock + `, ` + gatewayReadSettings + `
FROM (SELECT 1) anchor LEFT JOIN gateway_current_session s ON true`
gatewayHealthJoin = ` FROM gateway_candidates c LEFT JOIN gateway_node_health h ON h.proxy_id = c.proxy_id`
// $1 is the exclusive checked_at cutoff. A new membership needs a new
// measurement but does not invalidate still-fresh health of the same ID.
gatewayReadReady = `(h.ok IS TRUE AND h.checked_at > $1::timestamptz)`
gatewayCatalogCountry = `COALESCE(NULLIF(c.country, ''), 'XX')`
gatewayCatalogSpeed = `CASE WHEN c.speed_mbps > 0 AND c.speed_mbps < 'Infinity'::double precision THEN c.speed_mbps END`
gatewayCatalogWhere = ` WHERE ` + gatewayReadReady + `
AND (COALESCE(cardinality($2::text[]), 0) = 0 OR ` + gatewayCatalogCountry + ` = ANY($2))
AND (COALESCE(cardinality($3::text[]), 0) = 0 OR c.protocol = ANY($3))
AND ($4::bigint IS NULL OR h.latency_ms <= $4)
AND ($5::double precision IS NULL OR (` + gatewayCatalogSpeed + `) >= $5)`
)
func gatewayReadTx(ctx context.Context, d *DB) (pgx.Tx, error) {
return d.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
}
func gatewayReadTime(asOf time.Time) *time.Time {
if asOf.IsZero() {
return nil
}
return &asOf
}
func gatewayReadUTC(t *time.Time) *time.Time {
if t != nil {
*t = t.UTC()
}
return t
}
func gatewayReadInterval(value *string) (int, error) {
if value == nil {
return config.DefaultGatewayCheckIntervalMinutes, nil
}
minutes, err := config.ParseGatewayCheckIntervalMinutes(*value)
if err != nil {
return 0, ErrGatewayConfig
}
return minutes, nil
}
func gatewayReadCutoff(asOf time.Time, minutes int) time.Time {
return asOf.Add(-2 * time.Duration(minutes) * time.Minute)
}
func (d *DB) GatewayIntervalMinutes(ctx context.Context) (int, error) {
var value *string
if err := d.pool.QueryRow(ctx, `SELECT `+gatewayReadSettings).Scan(&value); err != nil {
return 0, err
}
return gatewayReadInterval(value)
}
func (d *DB) GatewayStoreUUID(ctx context.Context) (string, error) {
var uuid string
err := d.pool.QueryRow(ctx, `SELECT store_uuid::text FROM gateway_runtime WHERE id = 1`).Scan(&uuid)
return uuid, err
}
func (d *DB) GatewayCandidates(ctx context.Context) (GatewayCandidateSnapshot, error) {
tx, err := gatewayReadTx(ctx, d)
if err != nil {
return GatewayCandidateSnapshot{}, err
}
defer tx.Rollback(ctx) //nolint:errcheck // no-op after successful commit
var out GatewayCandidateSnapshot
var value *string
if err := tx.QueryRow(ctx, `SELECT s.session_id, s.session_finished_at, `+gatewayReadSettings+`
FROM (SELECT 1) anchor LEFT JOIN gateway_current_session s ON true`,
).Scan(&out.SessionID, &out.SessionFinishedAt, &value); err != nil {
return GatewayCandidateSnapshot{}, err
}
out.IntervalMinutes, err = gatewayReadInterval(value)
if err != nil {
return GatewayCandidateSnapshot{}, err
}
out.SessionFinishedAt = gatewayReadUTC(out.SessionFinishedAt)
out.Candidates = make([]GatewayCandidate, 0)
rows, err := tx.Query(ctx, `SELECT c.proxy_id, c.membership_id, h.tested_membership_id`+gatewayHealthJoin+` ORDER BY c.proxy_id`)
if err != nil {
return GatewayCandidateSnapshot{}, err
}
defer rows.Close()
for rows.Next() {
var candidate GatewayCandidate
if err := rows.Scan(&candidate.ProxyID, &candidate.MembershipID, &candidate.TestedMembershipID); err != nil {
return GatewayCandidateSnapshot{}, err
}
out.Candidates = append(out.Candidates, candidate)
}
if err := rows.Err(); err != nil {
return GatewayCandidateSnapshot{}, err
}
if err := tx.Commit(ctx); err != nil {
return GatewayCandidateSnapshot{}, err
}
return out, nil
}
// LookupGatewayNode evaluates current membership and readiness of a single ID.
// An asOf of zero uses PostgreSQL statement time.
func (d *DB) LookupGatewayNode(ctx context.Context, proxyID int64, asOf time.Time) (*GatewayNode, error) {
return d.lookupGatewayNode(ctx, proxyID, 0, asOf)
}
// LookupGatewayProbeNode additionally requires the exact membership of a ticket
// already authenticated by the caller, but does not require prior good health.
func (d *DB) LookupGatewayProbeNode(ctx context.Context, proxyID, membershipID int64) (*GatewayNode, error) {
if membershipID <= 0 {
return nil, nil
}
return d.lookupGatewayNode(ctx, proxyID, membershipID, time.Time{})
}
func (d *DB) lookupGatewayNode(ctx context.Context, proxyID, probeMembershipID int64, asOf time.Time) (*GatewayNode, error) {
if proxyID <= 0 {
return nil, nil
}
tx, err := gatewayReadTx(ctx, d)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx) //nolint:errcheck // no-op after successful commit
var value *string
if err := tx.QueryRow(ctx, `SELECT `+gatewayReadClock+`, `+gatewayReadSettings, gatewayReadTime(asOf)).Scan(&asOf, &value); err != nil {
return nil, err
}
interval, err := gatewayReadInterval(value)
if err != nil {
return nil, err
}
var row pgx.Row
const fields = `SELECT c.proxy_id, c.membership_id, c.canonical_url`
if probeMembershipID > 0 {
row = tx.QueryRow(ctx, fields+` FROM gateway_candidates c WHERE c.proxy_id = $1 AND c.membership_id = $2`, proxyID, probeMembershipID)
} else {
row = tx.QueryRow(ctx, fields+gatewayHealthJoin+` WHERE `+gatewayReadReady+` AND c.proxy_id = $2`, gatewayReadCutoff(asOf, interval), proxyID)
}
var node GatewayNode
err = row.Scan(&node.ProxyID, &node.MembershipID, &node.CanonicalURL)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return &node, nil
}
func (f GatewayCatalogFilter) orderBy() (string, error) {
if f.Offset < 0 || (f.Limit != nil && *f.Limit <= 0) || (f.MaxLatencyMs != nil && *f.MaxLatencyMs < 0) {
return "", ErrGatewayCatalogFilter
}
if f.MinSpeedMbps != nil {
speed := *f.MinSpeedMbps
if speed < 0 || math.IsNaN(speed) || math.IsInf(speed, 0) {
return "", ErrGatewayCatalogFilter
}
}
for _, country := range f.Countries {
if len(country) != 2 || country[0] < 'A' || country[0] > 'Z' || country[1] < 'A' || country[1] > 'Z' {
return "", ErrGatewayCatalogFilter
}
}
for _, protocol := range f.Protocols {
switch protocol {
case "vless", "vmess", "trojan", "ss":
default:
return "", ErrGatewayCatalogFilter
}
}
switch f.Sort {
case "", GatewaySortID:
return `c.proxy_id ASC`, nil
case GatewaySortSpeed:
return `speed_mbps DESC NULLS LAST, c.proxy_id ASC`, nil
case GatewaySortLatency:
return `h.latency_ms ASC, c.proxy_id ASC`, nil
case GatewaySortCountry:
return gatewayCatalogCountry + ` COLLATE "C" ASC, c.proxy_id ASC`, nil
default:
return "", ErrGatewayCatalogFilter
}
}
// GatewayCatalog reads metadata, filtered total, and the page from one snapshot.
// An asOf of zero uses PostgreSQL statement time.
func (d *DB) GatewayCatalog(ctx context.Context, filter GatewayCatalogFilter, asOf time.Time) (GatewayCatalogResult, error) {
order, err := filter.orderBy()
if err != nil {
return GatewayCatalogResult{}, err
}
tx, err := gatewayReadTx(ctx, d)
if err != nil {
return GatewayCatalogResult{}, err
}
defer tx.Rollback(ctx) //nolint:errcheck // no-op after successful commit
var out GatewayCatalogResult
var value *string
if err := tx.QueryRow(ctx, gatewayReadMetadata, gatewayReadTime(asOf)).Scan(&out.SessionID, &out.SessionFinishedAt, &out.AsOf, &value); err != nil {
return GatewayCatalogResult{}, err
}
interval, err := gatewayReadInterval(value)
if err != nil {
return GatewayCatalogResult{}, err
}
out.AsOf = out.AsOf.UTC()
out.SessionFinishedAt = gatewayReadUTC(out.SessionFinishedAt)
out.Items = make([]GatewayCatalogItem, 0)
args := []any{gatewayReadCutoff(out.AsOf, interval), filter.Countries, filter.Protocols, filter.MaxLatencyMs, filter.MinSpeedMbps, filter.Limit, filter.Offset}
paged := filter.Limit != nil || filter.Offset != 0
if paged {
if err := tx.QueryRow(ctx, `SELECT count(*)`+gatewayHealthJoin+gatewayCatalogWhere, args[:5]...).Scan(&out.Total); err != nil {
return GatewayCatalogResult{}, err
}
}
if !paged || filter.Offset < out.Total {
rows, err := tx.Query(ctx, `SELECT c.proxy_id, `+gatewayCatalogCountry+`, c.protocol, c.exit_ip, (`+gatewayCatalogSpeed+`) AS speed_mbps,
h.latency_ms, h.checked_at`+gatewayHealthJoin+gatewayCatalogWhere+` ORDER BY `+order+` LIMIT $6::bigint OFFSET $7::bigint`, args...)
if err != nil {
return GatewayCatalogResult{}, err
}
defer rows.Close()
for rows.Next() {
var item GatewayCatalogItem
if err := rows.Scan(&item.ProxyID, &item.Country, &item.Protocol, &item.ExitIP, &item.SpeedMbps, &item.LatencyMs, &item.CheckedAt); err != nil {
return GatewayCatalogResult{}, err
}
item.CheckedAt = item.CheckedAt.UTC()
out.Items = append(out.Items, item)
}
if err := rows.Err(); err != nil {
return GatewayCatalogResult{}, err
}
}
if !paged {
out.Total = int64(len(out.Items))
}
if err := tx.Commit(ctx); err != nil {
return GatewayCatalogResult{}, err
}
return out, nil
}
// GatewayStatus is the shared, credential-free status for the gateway and panel.
// An asOf of zero uses PostgreSQL statement time.
func (d *DB) GatewayStatus(ctx context.Context, asOf time.Time) (GatewayStatus, error) {
tx, err := gatewayReadTx(ctx, d)
if err != nil {
return GatewayStatus{}, err
}
defer tx.Rollback(ctx) //nolint:errcheck // no-op after successful commit
var out GatewayStatus
var heartbeat *time.Time
var value *string
if err := tx.QueryRow(ctx, `SELECT s.session_id, `+gatewayReadClock+`, `+gatewayReadSettings+`,
r.heartbeat_at, r.phase, r.last_started_at, r.last_attempt_finished_at, r.last_success_at, r.next_full_at, r.last_error_code
FROM gateway_runtime r LEFT JOIN gateway_current_session s ON true
WHERE r.id = 1`, gatewayReadTime(asOf)).Scan(
&out.SessionID, &asOf, &value, &heartbeat, &out.State, &out.LastStartedAt,
&out.LastAttemptFinishedAt, &out.LastSuccessAt, &out.NextFullAt, &out.LastErrorCode,
); err != nil {
return GatewayStatus{}, err
}
interval, configErr := gatewayReadInterval(value)
if configErr == nil {
out.IntervalMinutes = &interval
} else {
code := "config"
out.State = "degraded"
out.LastErrorCode = &code
}
if heartbeat == nil {
out.State = "not_started"
} else if asOf.Sub(*heartbeat) > 45*time.Second {
out.State = "offline"
}
out.LastStartedAt = gatewayReadUTC(out.LastStartedAt)
out.LastAttemptFinishedAt = gatewayReadUTC(out.LastAttemptFinishedAt)
out.LastSuccessAt = gatewayReadUTC(out.LastSuccessAt)
out.NextFullAt = gatewayReadUTC(out.NextFullAt)
if err := tx.QueryRow(ctx, `SELECT count(*), count(*) FILTER (WHERE $2::boolean AND `+gatewayReadReady+`)`+gatewayHealthJoin,
gatewayReadCutoff(asOf, interval), configErr == nil,
).Scan(&out.CandidateCount, &out.ReadyCount); err != nil {
return GatewayStatus{}, err
}
if err := tx.Commit(ctx); err != nil {
return GatewayStatus{}, err
}
return out, nil
}
+370
View File
@@ -0,0 +1,370 @@
package db
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
)
const gatewayLeaseLockKey int64 = 72640821
var (
ErrGatewayLeaseHeld = errors.New("gateway monitor lease is held")
ErrGatewayLeaseLost = errors.New("gateway monitor lease was lost")
errGatewayPassActive = errors.New("gateway monitor pass already active")
errGatewayPassInactive = errors.New("gateway monitor pass is not active")
)
// GatewayLease owns a dedicated PostgreSQL session and serializes its operations.
// The same backend holds the lock and makes monitor writes, so a disconnected
// monitor cannot write through another pool connection after a replacement starts.
type GatewayLease struct {
conn *pgx.Conn
pid int32
gate chan struct{}
lost chan struct{}
pass *GatewayPass
}
// AcquireGatewayLease fails without waiting if another monitor holds the lock.
func (d *DB) AcquireGatewayLease(ctx context.Context) (*GatewayLease, error) {
pooled, err := d.pool.Acquire(ctx)
if err != nil {
return nil, err
}
// Never put a session with a possibly acquired advisory lock back in the pool.
conn := pooled.Hijack()
var pid int32
var acquired bool
err = conn.QueryRow(ctx, `SELECT pg_backend_pid(), pg_try_advisory_lock($1)`, gatewayLeaseLockKey).Scan(&pid, &acquired)
if err != nil || !acquired {
closeCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = conn.Close(closeCtx)
if err != nil {
return nil, err
}
return nil, ErrGatewayLeaseHeld
}
return &GatewayLease{conn: conn, pid: pid, gate: make(chan struct{}, 1), lost: make(chan struct{})}, nil
}
// Lost closes when an operation detects lease loss or Close shuts it down.
func (l *GatewayLease) Lost() <-chan struct{} { return l.lost }
// Close shuts down the dedicated session, releasing the advisory lock.
func (l *GatewayLease) Close(ctx context.Context) error {
if err := l.take(ctx); err != nil {
return err
}
defer l.release()
var unlockErr error
select {
case <-l.lost:
default:
l.markLost()
_, unlockErr = l.conn.Exec(ctx, `SELECT pg_advisory_unlock($1) WHERE pg_backend_pid() = $2`, gatewayLeaseLockKey, l.pid)
}
return errors.Join(unlockErr, l.conn.Close(ctx))
}
// Check verifies that the original backend still owns the lease. Call regularly
// (e.g. via Heartbeat) even when the monitor has no candidates or is degraded.
func (l *GatewayLease) Check(ctx context.Context) error {
return l.run(ctx, func() error { return l.check(ctx, l.conn) })
}
func (l *GatewayLease) take(ctx context.Context) error {
select {
case l.gate <- struct{}{}:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (l *GatewayLease) release() { <-l.gate }
func (l *GatewayLease) markLost() {
select {
case <-l.lost:
default:
close(l.lost)
}
}
func (l *GatewayLease) run(ctx context.Context, f func() error) error {
if err := l.take(ctx); err != nil {
return err
}
defer l.release()
select {
case <-l.lost:
return ErrGatewayLeaseLost
default:
}
err := f()
if errors.Is(err, ErrGatewayLeaseLost) {
l.markLost()
} else if l.conn.IsClosed() {
l.markLost()
err = errors.Join(ErrGatewayLeaseLost, err)
}
return err
}
type gatewayQueryRower interface {
QueryRow(context.Context, string, ...any) pgx.Row
}
func (l *GatewayLease) check(ctx context.Context, conn gatewayQueryRower) error {
var owned bool
// objsubid=1 distinguishes the bigint lock from two-integer advisory locks.
err := conn.QueryRow(ctx, `SELECT EXISTS (
SELECT 1 FROM pg_catalog.pg_locks WHERE locktype = 'advisory'
AND pid = pg_backend_pid() AND pid = $2 AND granted AND mode = 'ExclusiveLock'
AND classid = 0 AND objid = $1::bigint::oid AND objsubid = 1
)`, gatewayLeaseLockKey, l.pid).Scan(&owned)
if err != nil {
if ctx.Err() != nil {
return err
}
return fmt.Errorf("%w: %w", ErrGatewayLeaseLost, err)
}
if !owned {
return ErrGatewayLeaseLost
}
return nil
}
// withTx runs on the dedicated connection while the caller holds the gate.
func (l *GatewayLease) withTx(ctx context.Context, f func(pgx.Tx) error) error {
tx, err := l.conn.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
if err != nil {
return err
}
defer tx.Rollback(ctx) //nolint:errcheck // no-op after commit
if err := l.check(ctx, tx); err != nil {
return err
}
if err := f(tx); err != nil {
return err
}
return tx.Commit(ctx)
}
func (l *GatewayLease) updateRuntime(ctx context.Context, query string, args ...any) error {
return l.withTx(ctx, func(tx pgx.Tx) error {
return requireOneRow(tx.Exec(ctx, query, args...))
})
}
// Heartbeat advances the heartbeat without changing pass state.
func (l *GatewayLease) Heartbeat(ctx context.Context, at time.Time) error {
return l.run(ctx, func() error {
return l.updateRuntime(ctx, `UPDATE gateway_runtime SET heartbeat_at = greatest(heartbeat_at, $1) WHERE id = 1`, at)
})
}
// GatewayPassMode selects whether a pass advances the full-pass schedule.
type GatewayPassMode string
const (
GatewayPassFull GatewayPassMode = "full"
GatewayPassEarly GatewayPassMode = "early"
)
// GatewayErrorCode is the sanitized failure category persisted in runtime state.
type GatewayErrorCode string
const (
GatewayErrorConfig GatewayErrorCode = "config"
GatewayErrorControl GatewayErrorCode = "control"
GatewayErrorDatabase GatewayErrorCode = "database"
GatewayErrorProbe GatewayErrorCode = "probe"
GatewayErrorInterrupted GatewayErrorCode = "interrupted"
)
func (c GatewayErrorCode) valid() bool {
switch c {
case GatewayErrorConfig, GatewayErrorControl, GatewayErrorDatabase, GatewayErrorProbe, GatewayErrorInterrupted:
return true
default:
return false
}
}
// GatewayPass identifies one active pass. A zero session ID means no snapshot.
type GatewayPass struct{ sessionID int64 }
// GatewayProbeResult is one completed measurement for an exact membership.
type GatewayProbeResult struct {
ProxyID, MembershipID int64
CheckedAt time.Time
OK bool
LatencyMS int32 // ignored when OK is false
}
// GatewayPassOutcome describes the committed subset of a successful batch.
type GatewayPassOutcome struct {
SessionCurrent bool // false for a stale source snapshot or a degraded pass
Applied int64
}
func gatewayNextFull(startedAt time.Time, intervalMinutes int) (time.Time, error) {
if intervalMinutes < 15 || intervalMinutes > 30 {
return time.Time{}, errors.New("invalid gateway pass interval")
}
return startedAt.Add(time.Duration(intervalMinutes) * time.Minute), nil
}
// BeginPass marks the attempt as checking. Only full passes set next_full_at.
func (l *GatewayLease) BeginPass(ctx context.Context, sessionID *int64, mode GatewayPassMode, startedAt time.Time, intervalMinutes int) (*GatewayPass, error) {
if mode != GatewayPassFull && mode != GatewayPassEarly {
return nil, errors.New("invalid gateway pass mode")
}
nextFullAt, err := gatewayNextFull(startedAt, intervalMinutes)
if err != nil {
return nil, err
}
pass := new(GatewayPass)
if sessionID != nil {
if *sessionID <= 0 {
return nil, errors.New("invalid gateway pass session ID")
}
pass.sessionID = *sessionID
}
err = l.run(ctx, func() error {
if l.pass != nil {
return errGatewayPassActive
}
if err := l.updateRuntime(ctx, `UPDATE gateway_runtime
SET last_started_at = $1, phase = 'checking', last_error_code = NULL,
next_full_at = CASE WHEN $2 THEN $3 ELSE next_full_at END
WHERE id = 1`, startedAt, mode == GatewayPassFull, nextFullAt); err != nil {
return err
}
l.pass = pass
return nil
})
if err != nil {
return nil, err
}
return pass, nil
}
// RescheduleFull recomputes the deadline from the last full pass's start, never
// from the moment the setting changed or an early pass started.
func (l *GatewayLease) RescheduleFull(ctx context.Context, lastFullStartedAt time.Time, intervalMinutes int) error {
nextFullAt, err := gatewayNextFull(lastFullStartedAt, intervalMinutes)
if err != nil {
return err
}
return l.run(ctx, func() error {
return l.updateRuntime(ctx, `UPDATE gateway_runtime SET next_full_at = $1 WHERE id = 1`, nextFullAt)
})
}
// Degrade records a system failure outside a pass, without changing attempt times.
func (l *GatewayLease) Degrade(ctx context.Context, failure GatewayErrorCode) error {
if !failure.valid() {
return errors.New("invalid gateway failure code")
}
return l.run(ctx, func() error {
if l.pass != nil {
return errGatewayPassActive
}
return l.updateRuntime(ctx, `UPDATE gateway_runtime SET phase = 'degraded', last_error_code = $1 WHERE id = 1`, string(failure))
})
}
// FinishPass atomically publishes current measurements and their runtime status.
// A system failure publishes no node results. A failed transaction leaves the
// pass active so the caller can finish it as degraded if the lease still exists.
func (l *GatewayLease) FinishPass(ctx context.Context, pass *GatewayPass, finishedAt time.Time, results []GatewayProbeResult, failure GatewayErrorCode) (GatewayPassOutcome, error) {
if failure != "" && !failure.valid() {
return GatewayPassOutcome{}, errors.New("invalid gateway failure code")
}
var batch gatewayProbeBatch
if failure == "" && len(results) != 0 {
batch = newGatewayProbeBatch(results)
}
var out GatewayPassOutcome
err := l.run(ctx, func() error {
if pass == nil || l.pass != pass {
return errGatewayPassInactive
}
if err := l.withTx(ctx, func(tx pgx.Tx) error {
if failure != "" {
return requireOneRow(tx.Exec(ctx, `UPDATE gateway_runtime
SET phase = 'degraded', last_attempt_finished_at = $1, last_error_code = $2
WHERE id = 1`, finishedAt, string(failure)))
}
var sessionID *int64
if pass.sessionID != 0 {
sessionID = &pass.sessionID
}
// Hold the current-pointer lock until commit. The next statement
// takes a fresh snapshot and locks matching membership rows.
if err := tx.QueryRow(ctx, `SELECT gateway_lock_current($1)`, sessionID).Scan(&out.SessionCurrent); err != nil {
return err
}
if out.SessionCurrent && sessionID != nil && len(results) != 0 {
tag, err := tx.Exec(ctx, gatewayUpsertHealth, *sessionID, batch.proxyIDs, batch.membershipIDs, batch.checkedAt, batch.ok, batch.latencyMS)
if err != nil {
return err
}
out.Applied = tag.RowsAffected()
}
return requireOneRow(tx.Exec(ctx, `UPDATE gateway_runtime
SET phase = 'idle', last_attempt_finished_at = $1, last_error_code = NULL,
last_success_at = CASE WHEN $2 THEN $1 ELSE last_success_at END
WHERE id = 1`, finishedAt, out.SessionCurrent))
}); err != nil {
return err
}
l.pass = nil
return nil
})
if err != nil {
return GatewayPassOutcome{}, err
}
return out, nil
}
type gatewayProbeBatch struct {
proxyIDs []int64
membershipIDs []int64
checkedAt []time.Time
ok []bool
latencyMS []int32
}
func newGatewayProbeBatch(results []GatewayProbeResult) gatewayProbeBatch {
n := len(results)
b := gatewayProbeBatch{
proxyIDs: make([]int64, n),
membershipIDs: make([]int64, n),
checkedAt: make([]time.Time, n),
ok: make([]bool, n),
latencyMS: make([]int32, n),
}
for i, r := range results {
b.proxyIDs[i], b.membershipIDs[i], b.checkedAt[i], b.ok[i], b.latencyMS[i] = r.ProxyID, r.MembershipID, r.CheckedAt, r.OK, r.LatencyMS
}
return b
}
const gatewayUpsertHealth = `INSERT INTO gateway_node_health (proxy_id, tested_membership_id, checked_at, ok, latency_ms)
SELECT r.proxy_id, r.membership_id, r.checked_at, r.ok, CASE WHEN r.ok THEN r.latency_ms END
FROM unnest($2::bigint[], $3::bigint[], $4::timestamptz[], $5::boolean[], $6::integer[])
AS r(proxy_id, membership_id, checked_at, ok, latency_ms)
JOIN gateway_lock_memberships($1, $3) AS c USING (proxy_id, membership_id)
ORDER BY r.proxy_id
ON CONFLICT (proxy_id) DO UPDATE SET
tested_membership_id = EXCLUDED.tested_membership_id, checked_at = EXCLUDED.checked_at,
ok = EXCLUDED.ok, latency_ms = EXCLUDED.latency_ms`
+505
View File
@@ -0,0 +1,505 @@
package db
import (
"context"
"crypto/rand"
"errors"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
func TestGatewayMonitorPassRuntime(t *testing.T) {
ctx, owner, gateway := newGatewayMonitorFixture(t)
lease := acquireTestGatewayLease(t, ctx, gateway)
start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
if err := lease.Heartbeat(ctx, start); err != nil {
t.Fatal(err)
}
if err := lease.Degrade(ctx, GatewayErrorConfig); err != nil {
t.Fatal(err)
}
if state := readGatewayMonitorRuntime(t, ctx, owner); state.phase != "degraded" || !isGatewayCode(state.errorCode, GatewayErrorConfig) || state.lastStarted != nil {
t.Fatalf("config failure started a pass: %+v", state)
}
if _, err := lease.BeginPass(ctx, nil, GatewayPassFull, start, 14); err == nil {
t.Fatal("accepted invalid full-pass interval")
}
// No first session is different from a published empty one, but either can
// be reconciled successfully without fabricating a health result.
pass := beginTestGatewayPass(t, ctx, lease, nil, GatewayPassFull, start, 20)
if _, err := lease.BeginPass(ctx, nil, GatewayPassEarly, start, 20); !errors.Is(err, errGatewayPassActive) {
t.Fatalf("overlapping pass: %v", err)
}
if err := lease.Heartbeat(ctx, start.Add(time.Second)); err != nil {
t.Fatal(err)
}
state := readGatewayMonitorRuntime(t, ctx, owner)
if state.phase != "checking" || state.errorCode != nil || !isGatewayTime(state.lastStarted, start) ||
!isGatewayTime(state.heartbeat, start.Add(time.Second)) || !isGatewayTime(state.nextFull, start.Add(20*time.Minute)) {
t.Fatalf("full pass start or heartbeat: %+v", state)
}
if err := lease.RescheduleFull(ctx, start, 30); err != nil {
t.Fatal(err)
}
finished := start.Add(2 * time.Second)
if out, err := lease.FinishPass(ctx, pass, finished, nil, ""); err != nil || !out.SessionCurrent || out.Applied != 0 {
t.Fatalf("empty first pass: %+v, %v", out, err)
}
session := insertGatewayMonitorSession(t, ctx, owner, true)
earlyStart := start.Add(time.Minute)
early := beginTestGatewayPass(t, ctx, lease, &session, GatewayPassEarly, earlyStart, 30)
if _, err := lease.FinishPass(ctx, pass, earlyStart, nil, ""); !errors.Is(err, errGatewayPassInactive) {
t.Fatalf("finished using old pass token: %v", err)
}
earlyEnd := earlyStart.Add(time.Second)
if out, err := lease.FinishPass(ctx, early, earlyEnd, nil, ""); err != nil || !out.SessionCurrent || out.Applied != 0 {
t.Fatalf("published empty current: %+v, %v", out, err)
}
state = readGatewayMonitorRuntime(t, ctx, owner)
if state.phase != "idle" || state.errorCode != nil || !isGatewayTime(state.lastSuccess, earlyEnd) ||
!isGatewayTime(state.lastFinished, earlyEnd) || !isGatewayTime(state.nextFull, start.Add(30*time.Minute)) {
t.Fatalf("early pass replaced full-pass schedule: %+v", state)
}
}
func TestGatewayMonitorBatchRollbackAndOutcomes(t *testing.T) {
ctx, owner, gateway := newGatewayMonitorFixture(t)
lease := acquireTestGatewayLease(t, ctx, gateway)
session := insertGatewayMonitorSession(t, ctx, owner, true)
a := insertGatewayMonitorCandidate(t, ctx, owner, session, "a")
b := insertGatewayMonitorCandidate(t, ctx, owner, session, "b")
start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
a.CheckedAt, a.OK, a.LatencyMS = start.Add(time.Second), true, 0
b.CheckedAt, b.OK, b.LatencyMS = start.Add(2*time.Second), true, 9
seedEnd := start.Add(3 * time.Second)
pass := beginTestGatewayPass(t, ctx, lease, &session, GatewayPassFull, start, 20)
if out, err := lease.FinishPass(ctx, pass, seedEnd, []GatewayProbeResult{a, b}, ""); err != nil || !out.SessionCurrent || out.Applied != 2 {
t.Fatalf("publish initial health: %+v, %v", out, err)
}
assertGatewayMonitorHealth(t, ctx, owner, a)
assertGatewayMonitorHealth(t, ctx, owner, b)
down := a
down.OK = false
down.CheckedAt = start.Add(4 * time.Second)
down.LatencyMS = 123 // negative results do not store a latency
pass = beginTestGatewayPass(t, ctx, lease, &session, GatewayPassEarly, seedEnd, 20)
if out, err := lease.FinishPass(ctx, pass, down.CheckedAt, []GatewayProbeResult{down}, ""); err != nil || !out.SessionCurrent || out.Applied != 1 {
t.Fatalf("publish confirmed node failure: %+v, %v", out, err)
}
assertGatewayMonitorHealth(t, ctx, owner, down)
// Fail the runtime write after the entire health statement has executed.
// A transaction that only batches node inserts cannot pass this assertion.
if _, err := owner.pool.Exec(ctx, `
CREATE FUNCTION fail_gateway_idle() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
IF NEW.phase = 'idle' THEN RAISE check_violation USING MESSAGE = 'injected gateway runtime write failure'; END IF;
RETURN NEW;
END; $$;
CREATE TRIGGER fail_gateway_idle BEFORE UPDATE ON gateway_runtime FOR EACH ROW EXECUTE FUNCTION fail_gateway_idle()`); err != nil {
t.Fatal(err)
}
pass = beginTestGatewayPass(t, ctx, lease, &session, GatewayPassEarly, down.CheckedAt, 20)
recovery, failure := a, b
recovery.CheckedAt = start.Add(5 * time.Second)
failure.CheckedAt, failure.OK = recovery.CheckedAt, false
results := []GatewayProbeResult{recovery, failure}
var pgErr *pgconn.PgError
if out, err := lease.FinishPass(ctx, pass, recovery.CheckedAt, results, ""); out != (GatewayPassOutcome{}) || !errors.As(err, &pgErr) || pgErr.Code != "23514" {
t.Fatalf("atomic failure: %+v, %v", out, err)
}
assertGatewayMonitorHealth(t, ctx, owner, down)
assertGatewayMonitorHealth(t, ctx, owner, b)
if state := readGatewayMonitorRuntime(t, ctx, owner); state.phase != "checking" || !isGatewayTime(state.lastSuccess, down.CheckedAt) || !isGatewayTime(state.lastFinished, down.CheckedAt) {
t.Fatalf("failed finish changed committed runtime state: %+v", state)
}
if out, err := lease.FinishPass(ctx, pass, recovery.CheckedAt, results, GatewayErrorDatabase); err != nil || out != (GatewayPassOutcome{}) {
t.Fatalf("finish degraded: %+v, %v", out, err)
}
assertGatewayMonitorHealth(t, ctx, owner, down)
assertGatewayMonitorHealth(t, ctx, owner, b)
if state := readGatewayMonitorRuntime(t, ctx, owner); state.phase != "degraded" || !isGatewayCode(state.errorCode, GatewayErrorDatabase) ||
!isGatewayTime(state.lastSuccess, down.CheckedAt) || !isGatewayTime(state.lastFinished, recovery.CheckedAt) {
t.Fatalf("degraded finish changed prior success: %+v", state)
}
}
func TestGatewayMonitorConcurrentMembershipReplacement(t *testing.T) {
ctx, owner, gateway := newGatewayMonitorFixture(t)
lease := acquireTestGatewayLease(t, ctx, gateway)
session := insertGatewayMonitorSession(t, ctx, owner, true)
a := insertGatewayMonitorCandidate(t, ctx, owner, session, "a")
b := insertGatewayMonitorCandidate(t, ctx, owner, session, "b")
start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
a.CheckedAt, a.OK, a.LatencyMS = start.Add(time.Second), true, 10
pass := beginTestGatewayPass(t, ctx, lease, &session, GatewayPassFull, start, 20)
if out, err := lease.FinishPass(ctx, pass, a.CheckedAt, []GatewayProbeResult{a}, ""); err != nil || out.Applied != 1 {
t.Fatalf("seed health: %+v, %v", out, err)
}
pass = beginTestGatewayPass(t, ctx, lease, &session, GatewayPassEarly, a.CheckedAt, 20)
edit, err := owner.pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer edit.Rollback(ctx) //nolint:errcheck // no-op after commit
if _, err := edit.Exec(ctx, `DELETE FROM session_proxies WHERE id = $1`, a.MembershipID); err != nil {
t.Fatal(err)
}
fresh := a
fresh.MembershipID = insertGatewayMonitorMembership(t, ctx, edit, session, a.ProxyID)
if fresh.MembershipID == a.MembershipID {
t.Fatal("replacement reused membership ID")
}
late := a
late.CheckedAt, late.OK = start.Add(2*time.Second), false
b.CheckedAt, b.OK, b.LatencyMS = late.CheckedAt, true, 20
finished := finishTestGatewayPassAsync(ctx, lease, pass, late.CheckedAt, []GatewayProbeResult{late, b})
waitGatewayMonitorBlocked(t, ctx, owner, lease.pid)
if err := edit.Commit(ctx); err != nil {
t.Fatal(err)
}
out := awaitGatewayMonitorFinish(t, ctx, finished)
if !out.SessionCurrent || out.Applied != 1 {
t.Fatalf("expected to keep only unchanged membership: %+v", out)
}
assertGatewayMonitorHealth(t, ctx, owner, a)
assertGatewayMonitorHealth(t, ctx, owner, b)
fresh.CheckedAt, fresh.LatencyMS = start.Add(3*time.Second), 30
pass = beginTestGatewayPass(t, ctx, lease, &session, GatewayPassEarly, late.CheckedAt, 20)
if out, err := lease.FinishPass(ctx, pass, fresh.CheckedAt, []GatewayProbeResult{fresh}, ""); err != nil || out.Applied != 1 {
t.Fatalf("publish replacement: %+v, %v", out, err)
}
pass = beginTestGatewayPass(t, ctx, lease, &session, GatewayPassEarly, fresh.CheckedAt, 20)
late.CheckedAt = start.Add(4 * time.Second)
if out, err := lease.FinishPass(ctx, pass, late.CheckedAt, []GatewayProbeResult{late}, ""); err != nil || !out.SessionCurrent || out.Applied != 0 {
t.Fatalf("overwrote replacement using stale membership: %+v, %v", out, err)
}
assertGatewayMonitorHealth(t, ctx, owner, fresh)
}
func TestGatewayMonitorConcurrentSessionPublication(t *testing.T) {
ctx, owner, gateway := newGatewayMonitorFixture(t)
lease := acquireTestGatewayLease(t, ctx, gateway)
aID := insertGatewayMonitorSession(t, ctx, owner, true)
bID := insertGatewayMonitorSession(t, ctx, owner, false)
a := insertGatewayMonitorCandidate(t, ctx, owner, aID, "a")
bMembership := insertGatewayMonitorMembership(t, ctx, owner.pool, bID, a.ProxyID)
start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
pass := beginTestGatewayPass(t, ctx, lease, &aID, GatewayPassFull, start, 20)
publication, err := owner.pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer publication.Rollback(ctx) //nolint:errcheck // no-op after commit
if _, err := publication.Exec(ctx, `UPDATE check_sessions SET is_current = false WHERE id = $1`, aID); err != nil {
t.Fatal(err)
}
if _, err := publication.Exec(ctx, `UPDATE check_sessions SET is_current = true WHERE id = $1`, bID); err != nil {
t.Fatal(err)
}
a.CheckedAt, a.OK, a.LatencyMS = start.Add(time.Second), true, 1
finished := finishTestGatewayPassAsync(ctx, lease, pass, a.CheckedAt, []GatewayProbeResult{a})
waitGatewayMonitorBlocked(t, ctx, owner, lease.pid)
if err := publication.Commit(ctx); err != nil {
t.Fatal(err)
}
if out := awaitGatewayMonitorFinish(t, ctx, finished); out != (GatewayPassOutcome{}) {
t.Fatalf("stale session marked current or wrote health: %+v", out)
}
var count int
if err := owner.pool.QueryRow(ctx, `SELECT count(*) FROM gateway_node_health`).Scan(&count); err != nil || count != 0 {
t.Fatalf("stale session health count: %d, %v", count, err)
}
state := readGatewayMonitorRuntime(t, ctx, owner)
if state.phase != "idle" || !isGatewayTime(state.lastFinished, a.CheckedAt) || state.lastSuccess != nil {
t.Fatalf("stale attempt was recorded as a successful pass: %+v", state)
}
pass = beginTestGatewayPass(t, ctx, lease, &bID, GatewayPassEarly, a.CheckedAt, 20)
a.MembershipID, a.CheckedAt = bMembership, start.Add(2*time.Second)
if out, err := lease.FinishPass(ctx, pass, a.CheckedAt, []GatewayProbeResult{a}, ""); err != nil || !out.SessionCurrent || out.Applied != 1 {
t.Fatalf("could not immediately reconcile newly published snapshot: %+v, %v", out, err)
}
assertGatewayMonitorHealth(t, ctx, owner, a)
}
func TestGatewayMonitorLeaseContentionAndLoss(t *testing.T) {
ctx, owner, gateway := newGatewayMonitorFixture(t)
lease := acquireTestGatewayLease(t, ctx, gateway)
if err := lease.Check(ctx); err != nil {
t.Fatal(err)
}
if other, err := gateway.AcquireGatewayLease(ctx); !errors.Is(err, ErrGatewayLeaseHeld) {
if other != nil {
_ = other.Close(ctx)
}
t.Fatalf("second backend acquired lease or reported wrong error: %v", err)
}
var terminated bool
if err := owner.pool.QueryRow(ctx, `SELECT pg_terminate_backend($1, 1000)`, lease.pid).Scan(&terminated); err != nil || !terminated {
t.Fatalf("terminate the dedicated test backend: %v, %v", terminated, err)
}
if err := lease.Check(ctx); !errors.Is(err, ErrGatewayLeaseLost) {
t.Fatalf("lease loss not detected: %v", err)
}
select {
case <-lease.Lost():
default:
t.Fatal("loss not published")
}
other := acquireTestGatewayLease(t, ctx, gateway)
at := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
if err := other.Heartbeat(ctx, at); err != nil {
t.Fatal(err)
}
if err := lease.Heartbeat(ctx, at.Add(time.Second)); !errors.Is(err, ErrGatewayLeaseLost) {
t.Fatalf("lost lease wrote after its replacement acquired lock: %v", err)
}
if state := readGatewayMonitorRuntime(t, ctx, owner); !isGatewayTime(state.heartbeat, at) {
t.Fatalf("loss allowed a stale heartbeat: %+v", state)
}
if err := other.Close(ctx); err != nil {
t.Fatal(err)
}
acquireTestGatewayLease(t, ctx, gateway)
}
func newGatewayMonitorFixture(t *testing.T) (context.Context, *DB, *DB) {
t.Helper()
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("set TEST_DATABASE_URL to a PostgreSQL test database")
}
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
t.Cleanup(cancel)
admin, err := pgx.Connect(ctx, dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = admin.Close(context.Background()) })
suffix := strings.ToLower(rand.Text())
schema := "gateway_monitor_" + suffix
role := "gateway_role_" + suffix
quotedSchema, quotedRole := pgx.Identifier{schema}.Sanitize(), pgx.Identifier{role}.Sanitize()
if _, err := admin.Exec(ctx, "CREATE ROLE "+quotedRole+" NOLOGIN"); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
cleanupCtx, stop := context.WithTimeout(context.Background(), 5*time.Second)
defer stop()
if _, err := admin.Exec(cleanupCtx, "DROP ROLE "+quotedRole); err != nil {
t.Error(err)
}
})
if _, err := admin.Exec(ctx, "GRANT "+quotedRole+" TO SESSION_USER"); err != nil {
t.Fatal(err)
}
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+quotedSchema); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
cleanupCtx, stop := context.WithTimeout(context.Background(), 5*time.Second)
defer stop()
if _, err := admin.Exec(cleanupCtx, "DROP SCHEMA "+quotedSchema+" CASCADE"); err != nil {
t.Error(err)
}
})
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
t.Fatal(err)
}
cfg.ConnConfig.RuntimeParams["search_path"] = schema
cfg.MaxConns = 3
owner := openGatewayMonitorFixturePool(t, ctx, cfg)
if err := owner.ApplySchema(ctx); err != nil {
t.Fatal(err)
}
// Use the provisioned privilege shape; a table owner would hide errors in
// row locking, conflict updates or the definer functions' grant contract.
if _, err := owner.pool.Exec(ctx, `GRANT USAGE ON SCHEMA `+quotedSchema+` TO `+quotedRole+`;
GRANT SELECT ON gateway_current_session, gateway_candidates, gateway_check_interval, gateway_runtime, gateway_node_health TO `+quotedRole+`;
GRANT INSERT, UPDATE (tested_membership_id, ok, checked_at, latency_ms) ON gateway_node_health TO `+quotedRole+`;
GRANT UPDATE (heartbeat_at, last_started_at, last_attempt_finished_at, last_success_at, next_full_at, phase, last_error_code) ON gateway_runtime TO `+quotedRole+`;
GRANT EXECUTE ON FUNCTION gateway_lock_current(bigint), gateway_lock_memberships(bigint, bigint[]) TO `+quotedRole); err != nil {
t.Fatal(err)
}
cfg = cfg.Copy()
cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
_, err := conn.Exec(ctx, "SET ROLE "+quotedRole)
return err
}
gateway := openGatewayMonitorFixturePool(t, ctx, cfg)
var allowed bool
if err := gateway.pool.QueryRow(ctx, `SELECT
has_any_column_privilege('check_sessions', 'SELECT, UPDATE') OR
has_any_column_privilege('session_proxies', 'SELECT, UPDATE') OR
has_any_column_privilege('settings', 'SELECT, UPDATE') OR
has_any_column_privilege('subscriptions', 'SELECT, UPDATE')`).Scan(&allowed); err != nil || allowed {
t.Fatalf("test gateway role has direct core privileges: %v, %v", allowed, err)
}
return ctx, owner, gateway
}
func openGatewayMonitorFixturePool(t *testing.T, ctx context.Context, cfg *pgxpool.Config) *DB {
t.Helper()
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
d := &DB{pool: pool}
t.Cleanup(d.Close)
return d
}
func acquireTestGatewayLease(t *testing.T, ctx context.Context, d *DB) *GatewayLease {
t.Helper()
lease, err := d.AcquireGatewayLease(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
cleanupCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := lease.Close(cleanupCtx); err != nil {
t.Error(err)
}
})
return lease
}
func beginTestGatewayPass(t *testing.T, ctx context.Context, lease *GatewayLease, session *int64, mode GatewayPassMode, at time.Time, interval int) *GatewayPass {
t.Helper()
pass, err := lease.BeginPass(ctx, session, mode, at, interval)
if err != nil {
t.Fatal(err)
}
return pass
}
func insertGatewayMonitorSession(t *testing.T, ctx context.Context, owner *DB, current bool) int64 {
t.Helper()
var id int64
if err := owner.pool.QueryRow(ctx, `INSERT INTO check_sessions (status, is_current, finished_at)
VALUES ('completed', $1, now()) RETURNING id`, current).Scan(&id); err != nil {
t.Fatal(err)
}
return id
}
func insertGatewayMonitorCandidate(t *testing.T, ctx context.Context, owner *DB, session int64, name string) GatewayProbeResult {
t.Helper()
var proxy int64
if err := owner.pool.QueryRow(ctx, `INSERT INTO proxies (canonical_url, protocol, host, port)
VALUES ($1, 'ss', 'fixture.invalid', 443) RETURNING id`, "ss://fixture-"+name).Scan(&proxy); err != nil {
t.Fatal(err)
}
return GatewayProbeResult{ProxyID: proxy, MembershipID: insertGatewayMonitorMembership(t, ctx, owner.pool, session, proxy)}
}
func insertGatewayMonitorMembership(t *testing.T, ctx context.Context, writer gatewayQueryRower, session, proxy int64) int64 {
t.Helper()
var id int64
if err := writer.QueryRow(ctx, `INSERT INTO session_proxies (session_id, proxy_id, canonical_url, protocol, host, port)
SELECT $1, id, canonical_url, protocol, host, port FROM proxies WHERE id = $2 RETURNING id`, session, proxy).Scan(&id); err != nil {
t.Fatal(err)
}
return id
}
func assertGatewayMonitorHealth(t *testing.T, ctx context.Context, d *DB, want GatewayProbeResult) {
t.Helper()
var got GatewayProbeResult
var latency *int32
if err := d.pool.QueryRow(ctx, `SELECT tested_membership_id, ok, checked_at, latency_ms
FROM gateway_node_health WHERE proxy_id = $1`, want.ProxyID).Scan(&got.MembershipID, &got.OK, &got.CheckedAt, &latency); err != nil {
t.Fatal(err)
}
if got.MembershipID != want.MembershipID || got.OK != want.OK || !got.CheckedAt.Equal(want.CheckedAt) ||
(want.OK && (latency == nil || *latency != want.LatencyMS)) || (!want.OK && latency != nil) {
t.Fatalf("unwanted health for node %d: membership=%d ok=%t checked_at=%v latency=%v (wanted %+v)", want.ProxyID, got.MembershipID, got.OK, got.CheckedAt, latency, want)
}
}
type gatewayMonitorRuntimeState struct {
phase string
errorCode *string
heartbeat *time.Time
lastStarted *time.Time
lastFinished *time.Time
lastSuccess *time.Time
nextFull *time.Time
}
func readGatewayMonitorRuntime(t *testing.T, ctx context.Context, d *DB) gatewayMonitorRuntimeState {
t.Helper()
var state gatewayMonitorRuntimeState
if err := d.pool.QueryRow(ctx, `SELECT phase, last_error_code, heartbeat_at, last_started_at, last_attempt_finished_at, last_success_at, next_full_at
FROM gateway_runtime WHERE id = 1`).Scan(&state.phase, &state.errorCode, &state.heartbeat, &state.lastStarted, &state.lastFinished, &state.lastSuccess, &state.nextFull); err != nil {
t.Fatal(err)
}
return state
}
func isGatewayTime(got *time.Time, want time.Time) bool { return got != nil && got.Equal(want) }
func isGatewayCode(got *string, want GatewayErrorCode) bool {
return got != nil && *got == string(want)
}
type gatewayMonitorFinishResult struct {
out GatewayPassOutcome
err error
}
func finishTestGatewayPassAsync(ctx context.Context, lease *GatewayLease, pass *GatewayPass, at time.Time, results []GatewayProbeResult) <-chan gatewayMonitorFinishResult {
finished := make(chan gatewayMonitorFinishResult, 1)
go func() {
out, err := lease.FinishPass(ctx, pass, at, results, "")
finished <- gatewayMonitorFinishResult{out, err}
}()
return finished
}
func waitGatewayMonitorBlocked(t *testing.T, ctx context.Context, owner *DB, pid int32) {
t.Helper()
waitCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
tick := time.NewTicker(5 * time.Millisecond)
defer tick.Stop()
for {
var blocked bool
if err := owner.pool.QueryRow(waitCtx, `SELECT cardinality(pg_blocking_pids($1)) > 0`, pid).Scan(&blocked); err != nil {
t.Fatalf("observe monitor waiting on concurrent writer: %v", err)
}
if blocked {
return
}
select {
case <-tick.C:
case <-waitCtx.Done():
t.Fatal("monitor did not serialize with the concurrent writer")
}
}
}
func awaitGatewayMonitorFinish(t *testing.T, ctx context.Context, finished <-chan gatewayMonitorFinishResult) GatewayPassOutcome {
t.Helper()
select {
case result := <-finished:
if result.err != nil {
t.Fatal(result.err)
}
return result.out
case <-ctx.Done():
t.Fatal(ctx.Err())
return GatewayPassOutcome{}
}
}
+483
View File
@@ -0,0 +1,483 @@
package db
import (
"context"
"crypto/rand"
"encoding/json"
"errors"
"math"
"os"
"slices"
"strings"
"testing"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/config"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
func newGatewayReadTestDB(t *testing.T) (*DB, context.Context) {
t.Helper()
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("set TEST_DATABASE_URL to a PostgreSQL test database")
}
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
t.Cleanup(cancel)
admin, err := pgx.Connect(ctx, dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = admin.Close(context.Background()) })
schema := "gateway_read_" + strings.ToLower(rand.Text())
quotedSchema := pgx.Identifier{schema}.Sanitize()
if _, err := admin.Exec(ctx, `CREATE SCHEMA `+quotedSchema); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := admin.Exec(cleanupCtx, `DROP SCHEMA `+quotedSchema+` CASCADE`); err != nil {
t.Errorf("drop test schema: %v", err)
}
})
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
t.Fatal(err)
}
cfg.ConnConfig.RuntimeParams["search_path"] = schema
cfg.MaxConns = 4
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
d := &DB{pool: pool}
t.Cleanup(d.Close)
if err := d.ApplySchema(ctx); err != nil {
t.Fatal(err)
}
return d, ctx
}
func execGatewayReadFixture(t *testing.T, ctx context.Context, d *DB, sql string, args ...any) {
t.Helper()
if _, err := d.pool.Exec(ctx, sql, args...); err != nil {
t.Fatal(err)
}
}
func gatewayReadFixtureID(t *testing.T, ctx context.Context, d *DB, sql string, args ...any) int64 {
t.Helper()
var id int64
if err := d.pool.QueryRow(ctx, sql, args...).Scan(&id); err != nil {
t.Fatal(err)
}
return id
}
func gatewayReadSession(t *testing.T, ctx context.Context, d *DB, status string, current bool, at time.Time) int64 {
t.Helper()
var finished *time.Time
if status != "running" {
finished = &at
}
return gatewayReadFixtureID(t, ctx, d, `INSERT INTO check_sessions (status, is_current, finished_at, valid)
VALUES ($1, $2, $3, 999) RETURNING id`, status, current, finished)
}
func gatewayReadProxy(t *testing.T, ctx context.Context, d *DB, source *int64, name, protocol string) int64 {
t.Helper()
return gatewayReadFixtureID(t, ctx, d, `INSERT INTO proxies (canonical_url, protocol, host, port, source_id)
VALUES ($1, $2, 'upstream.invalid', 443, $3) RETURNING id`, protocol+"://provider-credential@"+name+".invalid:443", protocol, source)
}
func gatewayReadMembership(t *testing.T, ctx context.Context, d *DB, session, proxy int64, country, source string, speed float64) int64 {
t.Helper()
return gatewayReadFixtureID(t, ctx, d, `INSERT INTO session_proxies
(session_id, proxy_id, canonical_url, protocol, host, port, country, source_name, exit_ip, speed_mbps)
SELECT $1, id, canonical_url, protocol, host, port, $3, $4, '8.8.8.8', $5 FROM proxies WHERE id = $2
RETURNING session_proxies.id`, session, proxy, country, source, speed)
}
func gatewayReadHealth(t *testing.T, ctx context.Context, d *DB, proxy, membership int64, checkedAt time.Time, latency *int64) {
t.Helper()
execGatewayReadFixture(t, ctx, d, `INSERT INTO gateway_node_health (proxy_id, tested_membership_id, ok, checked_at, latency_ms)
VALUES ($1, $2, $3, $4, $5) ON CONFLICT (proxy_id) DO UPDATE SET
tested_membership_id = excluded.tested_membership_id, ok = excluded.ok, checked_at = excluded.checked_at, latency_ms = excluded.latency_ms`,
proxy, membership, latency != nil, checkedAt, latency)
}
func gatewayReadPublish(t *testing.T, ctx context.Context, d *DB, session int64) {
t.Helper()
tx, err := d.pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback(ctx) //nolint:errcheck // no-op after successful commit
if _, err := tx.Exec(ctx, `UPDATE check_sessions SET is_current = false WHERE is_current`); err != nil {
t.Fatal(err)
}
if _, err := tx.Exec(ctx, `UPDATE check_sessions SET is_current = true WHERE id = $1`, session); err != nil {
t.Fatal(err)
}
if err := tx.Commit(ctx); err != nil {
t.Fatal(err)
}
}
func gatewayReadCatalogIDs(items []GatewayCatalogItem) []int64 {
ids := make([]int64, len(items))
for i, item := range items {
ids[i] = item.ProxyID
}
return ids
}
func TestGatewayReadCurrentMembershipAndTTL(t *testing.T) {
d, ctx := newGatewayReadTestDB(t)
at := time.Date(2026, time.January, 3, 0, 0, 0, 0, time.UTC)
assertCurrent := func(id int64, count int64) {
t.Helper()
snapshot, err := d.GatewayCandidates(ctx)
if err != nil || snapshot.Candidates == nil || int64(len(snapshot.Candidates)) != count || snapshot.IntervalMinutes != 20 {
t.Fatalf("candidate snapshot: %+v, %v", snapshot, err)
}
status, err := d.GatewayStatus(ctx, at)
if err != nil || status.CandidateCount != count || status.State != "not_started" {
t.Fatalf("status: %+v, %v", status, err)
}
catalog, err := d.GatewayCatalog(ctx, GatewayCatalogFilter{}, at)
if err != nil || catalog.Items == nil || catalog.Total != 0 || status.ReadyCount != 0 || !catalog.AsOf.Equal(at) {
t.Fatalf("unmeasured catalog: %+v, %v", catalog, err)
}
for _, got := range []*int64{snapshot.SessionID, status.SessionID, catalog.SessionID} {
if (id == 0 && got != nil) || (id != 0 && (got == nil || *got != id)) {
t.Fatalf("current session: got %v, want %d", got, id)
}
}
for _, finished := range []*time.Time{snapshot.SessionFinishedAt, catalog.SessionFinishedAt} {
if (id == 0 && finished != nil) || (id != 0 && (finished == nil || !finished.Equal(at))) {
t.Fatalf("publication timestamp: %v", finished)
}
}
}
assertCurrent(0, 0)
storeUUID, err := d.GatewayStoreUUID(ctx)
if err != nil || len(storeUUID) != 36 {
t.Fatalf("store UUID: %q, %v", storeUUID, err)
}
if err := d.ApplySchema(ctx); err != nil {
t.Fatal(err)
}
if got, err := d.GatewayStoreUUID(ctx); err != nil || got != storeUUID {
t.Fatalf("schema reapplied: store UUID = %q, %v", got, err)
}
current := gatewayReadSession(t, ctx, d, "completed", true, at)
assertCurrent(current, 0)
running := gatewayReadSession(t, ctx, d, "running", false, at)
failed := gatewayReadSession(t, ctx, d, "failed", false, at)
disabled := gatewayReadFixtureID(t, ctx, d, `INSERT INTO sources (name, url, enabled) VALUES ('disabled', 'https://disabled.invalid', false) RETURNING id`)
enabled := gatewayReadFixtureID(t, ctx, d, `INSERT INTO sources (name, url) VALUES ('enabled', 'https://enabled.invalid') RETURNING id`)
first := gatewayReadProxy(t, ctx, d, &disabled, "first", "vless")
second := gatewayReadProxy(t, ctx, d, &enabled, "second", "ss")
other := gatewayReadProxy(t, ctx, d, nil, "other", "trojan")
firstMembership := gatewayReadMembership(t, ctx, d, current, first, "DE", "disabled", 10)
secondMembership := gatewayReadMembership(t, ctx, d, current, second, "NL", "enabled", 9)
gatewayReadMembership(t, ctx, d, running, other, "DE", "running-only", 12)
gatewayReadMembership(t, ctx, d, failed, other, "DE", "failed-only", 12)
assertCurrent(current, 2)
assertLookup := func(id, membership int64, asOf time.Time, probe, found bool) {
t.Helper()
var node *GatewayNode
var err error
if probe {
node, err = d.LookupGatewayProbeNode(ctx, id, membership)
} else {
node, err = d.LookupGatewayNode(ctx, id, asOf)
}
if err != nil || (node != nil) != found || (found && (node.ProxyID != id || node.MembershipID != membership || node.CanonicalURL == "")) {
t.Fatalf("proxy=%d membership=%d probe=%t found=%t, err=%v; want found=%t", id, membership, probe, node != nil, err, found)
}
}
assertLookup(first, firstMembership, at, false, false)
assertLookup(first, firstMembership, at, true, true)
assertLookup(first, secondMembership, at, true, false)
assertLookup(other, 0, at, false, false)
latency := int64(50)
gatewayReadHealth(t, ctx, d, first, firstMembership, at, &latency)
gatewayReadHealth(t, ctx, d, second, secondMembership, at, &latency)
catalog, err := d.GatewayCatalog(ctx, GatewayCatalogFilter{}, at)
if err != nil || catalog.Total != 2 || !slices.Equal(gatewayReadCatalogIDs(catalog.Items), []int64{first, second}) || catalog.Items[0].ExitIP != catalog.Items[1].ExitIP {
t.Fatalf("expected both sources with same exit IP: %+v, %v", catalog, err)
}
next := gatewayReadSession(t, ctx, d, "completed", false, at.Add(time.Minute))
newMembership := gatewayReadMembership(t, ctx, d, next, first, "NL", "disabled", 11)
gatewayReadPublish(t, ctx, d, next)
assertLookup(first, newMembership, at.Add(time.Minute), false, true)
assertLookup(first, firstMembership, at, true, false)
assertLookup(second, secondMembership, at, false, false)
snapshot, err := d.GatewayCandidates(ctx)
if err != nil || len(snapshot.Candidates) != 1 || snapshot.Candidates[0].MembershipID != newMembership ||
snapshot.Candidates[0].TestedMembershipID == nil || *snapshot.Candidates[0].TestedMembershipID != firstMembership {
t.Fatalf("new membership needs probe without losing ready state: %+v, %v", snapshot, err)
}
execGatewayReadFixture(t, ctx, d, `UPDATE session_proxies SET speed_mbps = 15 WHERE id = $1`, newMembership)
catalog, err = d.GatewayCatalog(ctx, GatewayCatalogFilter{}, at.Add(time.Minute))
if err != nil || len(catalog.Items) != 1 || catalog.Items[0].SpeedMbps == nil || *catalog.Items[0].SpeedMbps != 15 {
t.Fatalf("snapshot metric refresh: %+v, %v", catalog, err)
}
execGatewayReadFixture(t, ctx, d, `DELETE FROM session_proxies WHERE id = $1`, newMembership)
assertLookup(first, newMembership, at, false, false)
assertLookup(first, newMembership, at, true, false)
reinserted := gatewayReadMembership(t, ctx, d, next, first, "NL", "disabled", 15)
assertLookup(first, newMembership, at, true, false)
assertLookup(first, reinserted, at, true, true)
assertLookup(first, reinserted, at.Add(40*time.Minute-time.Microsecond), false, true)
assertLookup(first, reinserted, at.Add(40*time.Minute), false, false)
status, err := d.GatewayStatus(ctx, at.Add(40*time.Minute))
if err != nil || status.ReadyCount != 0 || status.CandidateCount != 1 {
t.Fatalf("exact TTL boundary: %+v, %v", status, err)
}
catalog, err = d.GatewayCatalog(ctx, GatewayCatalogFilter{}, at.Add(40*time.Minute))
if err != nil || catalog.Total != 0 {
t.Fatalf("expired catalog: %+v, %v", catalog, err)
}
if err := d.SetSetting(ctx, config.KeyGatewayCheckIntervalMinutes, "30"); err != nil {
t.Fatal(err)
}
assertLookup(first, reinserted, at.Add(40*time.Minute), false, true)
if err := d.SetSetting(ctx, config.KeyGatewayCheckIntervalMinutes, "15"); err != nil {
t.Fatal(err)
}
assertLookup(first, reinserted, at.Add(30*time.Minute), false, false)
gatewayReadHealth(t, ctx, d, first, reinserted, at.Add(2*time.Minute), nil)
assertLookup(first, reinserted, at.Add(2*time.Minute), false, false)
assertLookup(first, reinserted, at, true, true)
snapshot, err = d.GatewayCandidates(ctx)
if err != nil || len(snapshot.Candidates) != 1 || snapshot.Candidates[0].TestedMembershipID == nil || *snapshot.Candidates[0].TestedMembershipID != reinserted {
t.Fatalf("failed probe must also mark a tested membership: %+v, %v", snapshot, err)
}
gatewayReadHealth(t, ctx, d, first, reinserted, at.Add(3*time.Minute), &latency)
assertLookup(first, reinserted, at.Add(3*time.Minute), false, true)
}
func TestGatewayReadCatalogFilters(t *testing.T) {
d, ctx := newGatewayReadTestDB(t)
at := time.Date(2026, time.January, 3, 0, 0, 0, 0, time.UTC)
session := gatewayReadSession(t, ctx, d, "completed", true, at)
add := func(name, protocol, country string, speed float64, latency *int64) int64 {
t.Helper()
id := gatewayReadProxy(t, ctx, d, nil, name, protocol)
membership := gatewayReadMembership(t, ctx, d, session, id, country, "test", speed)
gatewayReadHealth(t, ctx, d, id, membership, at, latency)
return id
}
zero, ten, twenty, one, huge := int64(0), int64(10), int64(20), int64(1), int64(math.MaxInt64)
zeroSpeed, minSpeed := 0.0, 5.0
de1 := add("de1", "vless", "DE", 5, &ten)
de2 := add("de2", "ss", "DE", 5, &ten)
add("down", "vless", "DE", 100, nil)
nl := add("nl", "ss", "NL", 9, &twenty)
unknown := add("unknown", "vmess", "", 0, &zero)
tests := []struct {
name string
filter GatewayCatalogFilter
ids []int64
total int64
}{
{"default", GatewayCatalogFilter{}, []int64{de1, de2, nl, unknown}, 4},
{"boundaries and tie", GatewayCatalogFilter{Countries: []string{"DE"}, MinSpeedMbps: &minSpeed, MaxLatencyMs: &ten, Sort: GatewaySortSpeed}, []int64{de1, de2}, 2},
{"OR and AND", GatewayCatalogFilter{Countries: []string{"DE", "NL"}, Protocols: []string{"ss", "trojan"}, Sort: GatewaySortCountry}, []int64{de2, nl}, 2},
{"unknown and zero latency", GatewayCatalogFilter{Countries: []string{"XX"}, MaxLatencyMs: &zero}, []int64{unknown}, 1},
{"zero threshold excludes unmeasured", GatewayCatalogFilter{MinSpeedMbps: &zeroSpeed, Sort: GatewaySortSpeed}, []int64{nl, de1, de2}, 3},
{"speed nulls last", GatewayCatalogFilter{Sort: GatewaySortSpeed}, []int64{nl, de1, de2, unknown}, 4},
{"latency tie", GatewayCatalogFilter{Sort: GatewaySortLatency, MaxLatencyMs: &huge}, []int64{unknown, de1, de2, nl}, 4},
{"page", GatewayCatalogFilter{Sort: GatewaySortSpeed, Offset: 1, Limit: &one}, []int64{de1}, 4},
{"offset beyond end", GatewayCatalogFilter{Offset: huge}, nil, 4},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
out, err := d.GatewayCatalog(ctx, tt.filter, at)
if err != nil || out.Total != tt.total || out.Items == nil || !slices.Equal(gatewayReadCatalogIDs(out.Items), tt.ids) {
t.Fatalf("catalog items = %v, total = %d, error = %v; want %v, %d", gatewayReadCatalogIDs(out.Items), out.Total, err, tt.ids, tt.total)
}
for _, item := range out.Items {
if item.ProxyID == unknown && (item.SpeedMbps != nil || item.Country != "XX" || item.LatencyMs != 0) {
t.Fatalf("unmeasured item: %+v", item)
}
}
body, err := json.Marshal(out)
if err != nil || strings.Contains(string(body), "provider-credential") || strings.Contains(string(body), "canonical_url") {
t.Fatalf("catalog serialization failed or exposed provider fields: %v", err)
}
if tt.name == "default" && (!strings.Contains(string(body), `"proxy_id":"1"`) || !strings.Contains(string(body), `"speed_mbps":null`)) {
t.Fatalf("catalog ID or missing measurement wire type is incorrect")
}
})
}
}
func TestGatewayReadRejectsInvalidCatalogFilter(t *testing.T) {
minusOne, zero := int64(-1), int64(0)
negativeSpeed, nanSpeed, infSpeed := -1.0, math.NaN(), math.Inf(1)
tests := []GatewayCatalogFilter{
{Countries: []string{"de"}}, {Countries: []string{"D"}}, {Countries: []string{"Я"}}, {Countries: []string{""}},
{Protocols: []string{"socks5"}}, {Sort: "id; SELECT 1"}, {Offset: -1}, {Limit: &zero}, {Limit: &minusOne}, {MaxLatencyMs: &minusOne},
{MinSpeedMbps: &negativeSpeed}, {MinSpeedMbps: &nanSpeed}, {MinSpeedMbps: &infSpeed},
}
for _, f := range tests {
// No pool: invalid typed filters must not access PostgreSQL.
if _, err := new(DB).GatewayCatalog(t.Context(), f, time.Time{}); !errors.Is(err, ErrGatewayCatalogFilter) {
t.Errorf("filter %+v: got %v, want ErrGatewayCatalogFilter", f, err)
}
}
}
func TestGatewayReadStatusAndDatabaseFailures(t *testing.T) {
d, ctx := newGatewayReadTestDB(t)
at := time.Date(2026, time.January, 3, 0, 0, 0, 0, time.FixedZone("fixture", 3600))
session := gatewayReadSession(t, ctx, d, "completed", true, at)
id := gatewayReadProxy(t, ctx, d, nil, "status", "vless")
membership := gatewayReadMembership(t, ctx, d, session, id, "DE", "test", 5)
latency := int64(10)
gatewayReadHealth(t, ctx, d, id, membership, at, &latency)
execGatewayReadFixture(t, ctx, d, `UPDATE gateway_runtime SET heartbeat_at = $1, last_started_at = $1,
last_attempt_finished_at = $1, last_success_at = $1, next_full_at = $1, phase = 'checking' WHERE id = 1`, at)
for _, tt := range []struct {
asOf time.Time
state string
}{
{at, "checking"},
{at.Add(45 * time.Second), "checking"},
{at.Add(45*time.Second + time.Microsecond), "offline"},
} {
status, err := d.GatewayStatus(ctx, tt.asOf)
if err != nil || status.State != tt.state || status.SessionID == nil || *status.SessionID != session ||
status.CandidateCount != 1 || status.ReadyCount != 1 || status.IntervalMinutes == nil || *status.IntervalMinutes != 20 {
t.Fatalf("status at %s: %+v, %v", tt.asOf, status, err)
}
for _, stamp := range []*time.Time{status.LastStartedAt, status.LastAttemptFinishedAt, status.LastSuccessAt, status.NextFullAt} {
if stamp == nil || !stamp.Equal(at) || stamp.Location() != time.UTC {
t.Fatalf("bad public timestamp: %v", stamp)
}
}
}
if err := d.SetSetting(ctx, config.KeyGatewayCheckIntervalMinutes, "not-a-valid-interval"); err != nil {
t.Fatal(err)
}
status, err := d.GatewayStatus(ctx, at)
if err != nil || status.State != "degraded" || status.LastErrorCode == nil || *status.LastErrorCode != "config" ||
status.CandidateCount != 1 || status.ReadyCount != 0 || status.IntervalMinutes != nil {
t.Fatalf("invalid config status: %+v, %v", status, err)
}
if _, err := d.GatewayCandidates(ctx); !errors.Is(err, ErrGatewayConfig) {
t.Fatalf("candidate snapshot invalid config: %v", err)
}
if _, err := d.GatewayCatalog(ctx, GatewayCatalogFilter{}, at); !errors.Is(err, ErrGatewayConfig) {
t.Fatalf("catalog invalid config: %v", err)
}
if _, err := d.LookupGatewayNode(ctx, id, at); !errors.Is(err, ErrGatewayConfig) {
t.Fatalf("ordinary lookup invalid config: %v", err)
}
if _, err := d.LookupGatewayProbeNode(ctx, id, membership); !errors.Is(err, ErrGatewayConfig) {
t.Fatalf("probe lookup invalid config: %v", err)
}
if _, err := d.GatewayIntervalMinutes(ctx); !errors.Is(err, ErrGatewayConfig) {
t.Fatalf("interval read malformed value: %v", err)
}
execGatewayReadFixture(t, ctx, d, `DELETE FROM settings WHERE key = $1`, config.KeyGatewayCheckIntervalMinutes)
if interval, err := d.GatewayIntervalMinutes(ctx); err != nil || interval != 20 {
t.Fatalf("missing setting default: %d, %v", interval, err)
}
if _, err := d.GatewayCatalog(ctx, GatewayCatalogFilter{}, at); err != nil {
t.Fatalf("catalog before database failure: %v", err)
}
execGatewayReadFixture(t, ctx, d, `DROP VIEW gateway_check_interval`)
if out, err := d.GatewayCatalog(ctx, GatewayCatalogFilter{}, at); err == nil || out.Items != nil {
t.Fatalf("database error is not an empty export: %+v, %v", out, err)
}
if node, err := d.LookupGatewayNode(ctx, id, at); err == nil || node != nil {
t.Fatalf("lookup did not fail closed: node present=%t, %v", node != nil, err)
}
if _, err := d.GatewayStatus(ctx, at); err == nil {
t.Fatal("broken schema was reported as a usable status")
}
}
func TestGatewayReadCatalogSnapshotDuringPublication(t *testing.T) {
d, ctx := newGatewayReadTestDB(t)
at := time.Date(2026, time.January, 3, 0, 0, 0, 0, time.UTC)
before := gatewayReadSession(t, ctx, d, "completed", true, at)
after := gatewayReadSession(t, ctx, d, "completed", false, at.Add(time.Minute))
latency := int64(1)
beforeProxy := gatewayReadProxy(t, ctx, d, nil, "before", "vless")
for _, fixture := range []struct{ session, proxy int64 }{
{before, beforeProxy},
{before, gatewayReadProxy(t, ctx, d, nil, "also-before", "ss")},
{after, gatewayReadProxy(t, ctx, d, nil, "after", "vmess")},
} {
m := gatewayReadMembership(t, ctx, d, fixture.session, fixture.proxy, "DE", "test", 5)
gatewayReadHealth(t, ctx, d, fixture.proxy, m, at, &latency)
}
lockTx, err := d.pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer lockTx.Rollback(ctx) //nolint:errcheck // no-op after successful commit
if _, err := lockTx.Exec(ctx, `LOCK TABLE gateway_node_health IN ACCESS EXCLUSIVE MODE`); err != nil {
t.Fatal(err)
}
type result struct {
catalog GatewayCatalogResult
err error
}
results := make(chan result, 1)
one := int64(1)
go func() {
out, err := d.GatewayCatalog(ctx, GatewayCatalogFilter{Limit: &one}, at.Add(time.Minute))
results <- result{out, err}
}()
// The health lock pauses the count after metadata establishes the reader's
// snapshot. Publish a different session before letting that count continue.
tick := time.NewTicker(5 * time.Millisecond)
defer tick.Stop()
for {
var waiting bool
if err := lockTx.QueryRow(ctx, `SELECT EXISTS (
SELECT 1 FROM pg_locks WHERE relation = 'gateway_node_health'::regclass
AND mode = 'AccessShareLock' AND NOT granted
)`).Scan(&waiting); err != nil {
t.Fatal(err)
}
if waiting {
break
}
select {
case r := <-results:
t.Fatalf("catalog did not wait at the snapshot boundary: %v", r.err)
case <-ctx.Done():
t.Fatal(ctx.Err())
case <-tick.C:
}
}
gatewayReadPublish(t, ctx, d, after)
if err := lockTx.Commit(ctx); err != nil {
t.Fatal(err)
}
r := <-results
if r.err != nil || r.catalog.SessionID == nil || *r.catalog.SessionID != before || r.catalog.Total != 2 ||
!slices.Equal(gatewayReadCatalogIDs(r.catalog.Items), []int64{beforeProxy}) ||
r.catalog.SessionFinishedAt == nil || !r.catalog.SessionFinishedAt.Equal(at) {
t.Fatalf("mixed catalog publication: %+v, %v", r.catalog, r.err)
}
out, err := d.GatewayCatalog(ctx, GatewayCatalogFilter{}, at.Add(time.Minute))
if err != nil || out.SessionID == nil || *out.SessionID != after || out.Total != 1 {
t.Fatalf("next read must see new publication: %+v, %v", out, err)
}
}
+92
View File
@@ -190,3 +190,95 @@ ON CONFLICT (key) DO NOTHING;
-- Replace the old built-in HTTP URL without changing custom settings.
UPDATE settings SET value = 'https://speedtest.selectel.ru/10MB', updated_at = now()
WHERE key = 'speedtest_url' AND value = 'http://cachefly.cachefly.net/10mb.test';
-- ---------------------------------------------------------------------------
-- HTTP gateway: the checker owns the published snapshot, the gateway owns
-- only its runtime and health. The views expose no historical rows or settings.
-- ---------------------------------------------------------------------------
INSERT INTO settings (key, value) VALUES ('gateway_check_interval_minutes', '20')
ON CONFLICT (key) DO NOTHING;
CREATE OR REPLACE VIEW gateway_current_session WITH (security_barrier = true) AS
SELECT id AS session_id, finished_at AS session_finished_at
FROM check_sessions
WHERE is_current AND status = 'completed';
CREATE OR REPLACE VIEW gateway_candidates WITH (security_barrier = true) AS
SELECT cs.id AS session_id, cs.finished_at AS session_finished_at,
sp.id AS membership_id, sp.proxy_id, sp.canonical_url, sp.protocol,
sp.country, sp.exit_ip, sp.speed_mbps
FROM check_sessions cs
JOIN session_proxies sp ON sp.session_id = cs.id
WHERE cs.is_current AND cs.status = 'completed';
CREATE OR REPLACE VIEW gateway_check_interval WITH (security_barrier = true) AS
SELECT value FROM settings WHERE key = 'gateway_check_interval_minutes';
CREATE TABLE IF NOT EXISTS gateway_node_health (
proxy_id bigint PRIMARY KEY REFERENCES proxies(id) ON DELETE CASCADE,
tested_membership_id bigint NOT NULL,
ok boolean NOT NULL,
checked_at timestamptz NOT NULL,
latency_ms integer,
CHECK ((ok AND latency_ms IS NOT NULL AND latency_ms >= 0)
OR (NOT ok AND latency_ms IS NULL))
);
CREATE TABLE IF NOT EXISTS gateway_runtime (
id integer PRIMARY KEY CHECK (id = 1),
store_uuid uuid NOT NULL DEFAULT gen_random_uuid(),
heartbeat_at timestamptz,
last_started_at timestamptz,
last_attempt_finished_at timestamptz,
last_success_at timestamptz,
next_full_at timestamptz,
phase text NOT NULL DEFAULT 'idle' CHECK (phase IN ('idle', 'checking', 'degraded')),
last_error_code text CHECK (last_error_code IN ('config', 'control', 'database', 'probe', 'interrupted'))
);
INSERT INTO gateway_runtime (id) VALUES (1) ON CONFLICT (id) DO NOTHING;
-- Publication takes short-lived locks without granting the gateway access to
-- the checker tables. Bind their schema here; never use the caller's search_path.
DO $gateway_ddl$
BEGIN
EXECUTE format($definition$
CREATE OR REPLACE FUNCTION %1$I.gateway_lock_current(expected_session_id bigint)
RETURNS boolean
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp
AS $body$
BEGIN
IF expected_session_id IS NULL THEN
-- Before the first publication there is no row to lock.
LOCK TABLE %1$I.check_sessions IN SHARE MODE;
RETURN NOT EXISTS (
SELECT 1 FROM %1$I.check_sessions
WHERE is_current AND status = 'completed'
);
END IF;
PERFORM 1 FROM %1$I.check_sessions
WHERE id = expected_session_id AND is_current AND status = 'completed'
FOR SHARE;
RETURN FOUND;
END;
$body$
$definition$, current_schema());
EXECUTE format($definition$
CREATE OR REPLACE FUNCTION %1$I.gateway_lock_memberships(expected_session_id bigint, memberships bigint[])
RETURNS TABLE(proxy_id bigint, membership_id bigint)
LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, pg_temp
AS $body$
SELECT sp.proxy_id, sp.id
FROM %1$I.check_sessions cs
JOIN %1$I.session_proxies sp ON sp.session_id = cs.id
WHERE cs.id = expected_session_id AND cs.is_current AND cs.status = 'completed'
AND sp.id = ANY(memberships)
FOR SHARE OF cs FOR KEY SHARE OF sp;
$body$
$definition$, current_schema());
END;
$gateway_ddl$;
REVOKE EXECUTE ON FUNCTION gateway_lock_current(bigint), gateway_lock_memberships(bigint, bigint[]) FROM PUBLIC;
+6 -7
View File
@@ -7,6 +7,7 @@ import (
"net"
"git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/shadowsocks"
"git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/transport"
"git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/trojan"
"git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/vless"
"git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/vmess"
@@ -24,16 +25,14 @@ type Dispatcher struct {
vless *vless.Dialer
trojan *trojan.Dialer
vmess *vmess.Dialer
log *slog.Logger
}
func NewDispatcher(log *slog.Logger) *Dispatcher {
func NewDispatcher(log *slog.Logger, open transport.DialContextFunc) *Dispatcher {
return &Dispatcher{
ss: &shadowsocks.Dialer{Log: log},
vless: &vless.Dialer{Log: log},
trojan: &trojan.Dialer{Log: log},
vmess: &vmess.Dialer{Log: log},
log: log,
ss: &shadowsocks.Dialer{Log: log, Open: open},
vless: &vless.Dialer{Log: log, Open: open},
trojan: &trojan.Dialer{Log: log, Open: open},
vmess: &vmess.Dialer{Log: log, Open: open},
}
}
+170
View File
@@ -0,0 +1,170 @@
package dialer_test
import (
"context"
"errors"
"io"
"net"
"testing"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/dialer"
"git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/shadowsocks"
"git.eeee.moe/omar/zhguchiy_perchik/internal/upstream"
)
const (
peerHost = "unresolved-peer.invalid"
peerPort = 8443
peerAddr = "unresolved-peer.invalid:8443"
peerUUID = "12345678-1234-4234-8234-123456789abc"
testBound = 3 * time.Second
)
func TestDispatcherSocketOpener(t *testing.T) {
blocked := errors.New("policy denied raw socket")
for _, tc := range []upstream.Upstream{
{Scheme: upstream.SchemeShadowsocks, Transport: "tcp", SS: &upstream.ShadowsocksConfig{}},
{Scheme: upstream.SchemeTrojan, Transport: "tcp", Trojan: &upstream.TrojanConfig{}},
{Scheme: upstream.SchemeTrojan, Transport: "ws", Trojan: &upstream.TrojanConfig{}},
{Scheme: upstream.SchemeTrojan, Transport: "grpc", Trojan: &upstream.TrojanConfig{}},
{Scheme: upstream.SchemeVLESS, Transport: "tcp", VLESS: &upstream.VLESSConfig{Security: "tls"}},
{Scheme: upstream.SchemeVLESS, Transport: "ws", VLESS: &upstream.VLESSConfig{Security: "tls"}},
{Scheme: upstream.SchemeVLESS, Transport: "grpc", VLESS: &upstream.VLESSConfig{Security: "tls"}},
{Scheme: upstream.SchemeVLESS, Transport: "grpc", VLESS: &upstream.VLESSConfig{Security: "reality"}},
{Scheme: upstream.SchemeVMess, Transport: "tcp", VMess: &upstream.VMessConfig{TLS: true}},
{Scheme: upstream.SchemeVMess, Transport: "ws", VMess: &upstream.VMessConfig{TLS: true}},
{Scheme: upstream.SchemeVMess, Transport: "grpc", VMess: &upstream.VMessConfig{TLS: true}},
} {
name := string(tc.Scheme) + "/" + tc.Transport
if tc.VLESS != nil {
name += "/" + tc.VLESS.Security
}
t.Run(name, func(t *testing.T) {
tc.Host, tc.Port = peerHost, peerPort
count := 0
dispatch := dialer.NewDispatcher(nil, func(_ context.Context, network, address string) (net.Conn, error) {
count++
if network != "tcp" || address != peerAddr {
t.Fatalf("opener got %s %s, want tcp %s", network, address, peerAddr)
}
return nil, blocked
})
conn, err := dispatch.Dial(t.Context(), &tc, "192.0.2.1:80")
if conn != nil {
_ = conn.Close()
t.Fatal("denied opener yielded a connection")
}
if !errors.Is(err, blocked) || count != 1 {
t.Fatalf("opener denial: error = %v, calls = %d; want denial and one call", err, count)
}
})
}
}
func TestDispatcherCancelsBlockedSetup(t *testing.T) {
for _, tc := range []struct {
name string
up upstream.Upstream
}{
{"Shadowsocks header", upstream.Upstream{Scheme: upstream.SchemeShadowsocks, SS: &upstream.ShadowsocksConfig{Method: "aes-128-gcm", Password: "fixture"}}},
{"Trojan header", upstream.Upstream{Scheme: upstream.SchemeTrojan, Trojan: &upstream.TrojanConfig{Security: "none", Password: "fixture"}}},
{"VMess header", upstream.Upstream{Scheme: upstream.SchemeVMess, VMess: &upstream.VMessConfig{UUID: peerUUID}}},
{"VLESS TLS", upstream.Upstream{Scheme: upstream.SchemeVLESS, VLESS: &upstream.VLESSConfig{Security: "tls", UUID: peerUUID}}},
{"WebSocket upgrade", upstream.Upstream{Scheme: upstream.SchemeVLESS, Transport: "ws", VLESS: &upstream.VLESSConfig{UUID: peerUUID}}},
{"gRPC preface", upstream.Upstream{Scheme: upstream.SchemeVLESS, Transport: "grpc", VLESS: &upstream.VLESSConfig{UUID: peerUUID}}},
} {
t.Run(tc.name, func(t *testing.T) {
tc.up.Host, tc.up.Port = peerHost, peerPort
client, peer := net.Pipe()
defer client.Close()
defer peer.Close()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
writing := make(chan struct{}, 1)
dispatch := dialer.NewDispatcher(nil, func(context.Context, string, string) (net.Conn, error) {
return setupWriteConn{Conn: client, writing: writing}, nil
})
result := make(chan error, 1)
go func() {
conn, err := dispatch.Dial(ctx, &tc.up, "192.0.2.1:80")
if conn != nil {
_ = conn.Close()
}
result <- err
}()
select {
case <-writing:
case err := <-result:
t.Fatalf("dial returned before setup write: %v", err)
case <-time.After(testBound):
t.Fatal("setup did not attempt a write")
}
cancel()
select {
case err := <-result:
if !errors.Is(err, context.Canceled) {
t.Fatalf("dial error = %v, want canceled", err)
}
case <-time.After(testBound):
t.Fatal("cancellation did not interrupt setup")
}
if err := peer.SetReadDeadline(time.Now().Add(testBound)); err != nil && !errors.Is(err, io.ErrClosedPipe) {
t.Fatal(err)
}
var data [1]byte
if n, err := peer.Read(data[:]); n != 0 || !errors.Is(err, io.EOF) {
t.Fatalf("peer read = %d, %v; want EOF from closed socket", n, err)
}
})
}
}
func TestShadowsocksSetupTimeoutClosesSocket(t *testing.T) {
client, peer := net.Pipe()
defer client.Close()
defer peer.Close()
d := &shadowsocks.Dialer{
DialTimeout: 50 * time.Millisecond,
Open: func(context.Context, string, string) (net.Conn, error) {
return client, nil
},
}
ctx, cancel := context.WithTimeout(t.Context(), testBound)
defer cancel()
conn, err := d.Dial(ctx, &upstream.Upstream{
Scheme: upstream.SchemeShadowsocks,
Host: peerHost,
Port: peerPort,
SS: &upstream.ShadowsocksConfig{Method: "aes-128-gcm", Password: "fixture"},
}, "192.0.2.1:80")
if conn != nil {
_ = conn.Close()
t.Fatal("stalled setup yielded a connection")
}
if !errors.Is(err, context.DeadlineExceeded) || ctx.Err() != nil {
t.Fatalf("dial error = %v, outer context error = %v; want only the setup timeout", err, ctx.Err())
}
if err := peer.SetReadDeadline(time.Now().Add(testBound)); err != nil && !errors.Is(err, io.ErrClosedPipe) {
t.Fatal(err)
}
var data [1]byte
if n, err := peer.Read(data[:]); n != 0 || !errors.Is(err, io.EOF) {
t.Fatalf("peer read = %d, %v; want EOF from closed socket", n, err)
}
}
type setupWriteConn struct {
net.Conn
writing chan<- struct{}
}
func (c setupWriteConn) Write(p []byte) (int, error) {
select {
case c.writing <- struct{}{}:
default:
}
return c.Conn.Write(p)
}
+9 -7
View File
@@ -7,15 +7,23 @@ import (
"net"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/transport"
"git.eeee.moe/omar/zhguchiy_perchik/internal/upstream"
)
type Dialer struct {
DialTimeout time.Duration
Log *slog.Logger
Open transport.DialContextFunc
}
func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (net.Conn, error) {
return transport.DialSetup(ctx, d.Open, d.DialTimeout, func(ctx context.Context, open transport.DialContextFunc) (net.Conn, error) {
return d.dial(ctx, open, up, dest)
})
}
func (d *Dialer) dial(ctx context.Context, open transport.DialContextFunc, up *upstream.Upstream, dest string) (net.Conn, error) {
if up.SS == nil {
return nil, fmt.Errorf("shadowsocks: missing config")
}
@@ -24,14 +32,8 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (
d.Log.Debug("shadowsocks dial", "upstream", up.Address(), "dest", dest, "method", up.SS.Method)
}
timeout := d.DialTimeout
if timeout <= 0 {
timeout = 10 * time.Second
}
// 1. Connect to upstream
dialer := net.Dialer{Timeout: timeout}
c, err := dialer.DialContext(ctx, "tcp", up.Address())
c, err := open(ctx, "tcp", up.Address())
if err != nil {
return nil, fmt.Errorf("shadowsocks: connect to upstream: %w", err)
}
+22 -11
View File
@@ -257,9 +257,16 @@ func (g *GRPCConn) SetDeadline(t time.Time) error {
func (g *GRPCConn) SetReadDeadline(t time.Time) error { return g.reader.SetReadDeadline(t) }
func (g *GRPCConn) SetWriteDeadline(t time.Time) error { return g.writer.SetWriteDeadline(t) }
// DialGRPC establishes a gRPC tunnel, creating a new TLS connection internally.
// Used for standard TLS (non-Reality) transports.
func DialGRPC(ctx context.Context, addr string, serviceName string, tlsConfig *tls.Config) (net.Conn, error) {
// DialGRPC opens the raw socket for a dedicated gRPC tunnel. When TLS is
// configured, HTTP/2 negotiation and certificate verification precede gRPC.
func DialGRPC(ctx context.Context, addr, serviceName string, tlsConfig *tls.Config, open DialContextFunc) (net.Conn, error) {
if tlsConfig == nil {
raw, err := open(ctx, "tcp", addr)
if err != nil {
return nil, err
}
return DialGRPCOverConn(ctx, raw, addr, serviceName)
}
host, port, err := net.SplitHostPort(addr)
if err != nil {
host = strings.TrimPrefix(strings.TrimSuffix(addr, "]"), "[")
@@ -270,20 +277,24 @@ func DialGRPC(ctx context.Context, addr string, serviceName string, tlsConfig *t
if ascii, err := idna.ToASCII(host); err == nil {
host = ascii
}
config := new(tls.Config)
if tlsConfig != nil {
config = tlsConfig.Clone()
config := tlsConfig.Clone()
if config.ServerName == "" {
config.ServerName = host
}
if !slices.Contains(config.NextProtos, http2.NextProtoTLS) {
config.NextProtos = append([]string{http2.NextProtoTLS}, config.NextProtos...)
}
dialer := tls.Dialer{Config: config}
conn, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort(host, port))
raw, err := open(ctx, "tcp", net.JoinHostPort(host, port))
if err != nil {
return nil, fmt.Errorf("grpc: TLS dial: %w", err)
return nil, fmt.Errorf("grpc: connect: %w", err)
}
if state := conn.(*tls.Conn).ConnectionState(); state.NegotiatedProtocol != http2.NextProtoTLS {
closeGRPCSetupConn(conn)
conn := tls.Client(raw, config)
if err := conn.HandshakeContext(ctx); err != nil {
_ = raw.Close()
return nil, fmt.Errorf("grpc: TLS handshake: %w", err)
}
if conn.ConnectionState().NegotiatedProtocol != http2.NextProtoTLS {
_ = raw.Close()
return nil, errors.New("grpc: TLS did not negotiate HTTP/2")
}
return DialGRPCOverConn(ctx, conn, addr, serviceName)
+16 -2
View File
@@ -19,6 +19,7 @@ import (
const grpcTestTimeout = 3 * time.Second
func TestGRPCTLSRoundTripAfterDialCancellation(t *testing.T) {
const logicalAddr, sni = "peer.example.invalid:8443", "example.com"
first := []byte("initial tunnel data")
second := bytes.Repeat([]byte("b"), 300)
wantRequest := append(grpcTestFrame(first), grpcTestFrame(second)...)
@@ -27,6 +28,10 @@ func TestGRPCTLSRoundTripAfterDialCancellation(t *testing.T) {
t.Errorf("unexpected gRPC request path or protocol: %s %s", r.URL.Path, r.Proto)
return
}
if r.Host != logicalAddr || r.TLS.ServerName != sni {
t.Errorf("authority = %q, SNI = %q; want %q and %q", r.Host, r.TLS.ServerName, logicalAddr, sni)
return
}
got := make([]byte, len(wantRequest))
if _, err := io.ReadFull(r.Body, got); err != nil || !bytes.Equal(got, wantRequest) {
t.Errorf("request frames did not match: %v", err)
@@ -50,8 +55,17 @@ func TestGRPCTLSRoundTripAfterDialCancellation(t *testing.T) {
t.Cleanup(server.Close)
ctx, cancel := context.WithTimeout(t.Context(), grpcTestTimeout)
tlsConfig := server.Client().Transport.(*http.Transport).TLSClientConfig
conn, err := DialGRPC(ctx, server.Listener.Addr().String(), "Tunnel", tlsConfig)
tlsConfig := server.Client().Transport.(*http.Transport).TLSClientConfig.Clone()
tlsConfig.ServerName = sni
open := func(ctx context.Context, network, address string) (net.Conn, error) {
if network != "tcp" || address != logicalAddr {
t.Fatalf("opener got %s %s, want tcp %s", network, address, logicalAddr)
}
return (&net.Dialer{}).DialContext(ctx, network, server.Listener.Addr().String())
}
conn, err := DialSetup(ctx, open, 0, func(ctx context.Context, open DialContextFunc) (net.Conn, error) {
return DialGRPC(ctx, logicalAddr, "Tunnel", tlsConfig, open)
})
cancel()
if err != nil {
t.Fatal(err)
+54
View File
@@ -0,0 +1,54 @@
package transport
import (
"context"
"net"
"time"
)
// DialContextFunc opens the raw socket for a logical upstream address.
type DialContextFunc func(context.Context, string, string) (net.Conn, error)
var defaultDialContext = (&net.Dialer{}).DialContext
// DialSetup bounds opening the socket and all subsequent setup I/O. The setup
// function opens at most one raw socket; only a successful result transfers
// ownership to the caller, independent of the setup context's lifetime.
func DialSetup(ctx context.Context, open DialContextFunc, timeout time.Duration, setup func(context.Context, DialContextFunc) (net.Conn, error)) (net.Conn, error) {
if timeout <= 0 {
timeout = 10 * time.Second
}
setupCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
if open == nil {
open = defaultDialContext
}
var raw net.Conn
var stop func() bool
conn, err := setup(setupCtx, func(dialCtx context.Context, network, address string) (net.Conn, error) {
c, err := open(dialCtx, network, address)
if err != nil {
return nil, err
}
raw = c
stop = context.AfterFunc(setupCtx, func() { _ = c.Close() })
return c, nil
})
if stop != nil {
stop()
}
if contextErr := setupCtx.Err(); contextErr != nil {
err = contextErr
}
if err != nil {
if raw != nil {
_ = raw.Close()
}
if conn != nil {
_ = conn.Close()
}
return nil, err
}
return conn, nil
}
+5 -3
View File
@@ -53,7 +53,9 @@ func (c *WSConn) SetDeadline(t time.Time) error {
return c.Conn.SetWriteDeadline(t)
}
func DialWS(ctx context.Context, addr, path, host string, tlsConfig *tls.Config) (net.Conn, error) {
// DialWS upgrades the socket opened by open. DialSetup supplies the shared
// setup deadline and closes the socket if the HTTP upgrade stalls on cancel.
func DialWS(ctx context.Context, addr, path, host string, tlsConfig *tls.Config, open DialContextFunc) (net.Conn, error) {
scheme := "ws"
if tlsConfig != nil {
scheme = "wss"
@@ -61,8 +63,8 @@ func DialWS(ctx context.Context, addr, path, host string, tlsConfig *tls.Config)
u := url.URL{Scheme: scheme, Host: addr, Path: path}
dialer := &websocket.Dialer{
HandshakeTimeout: 10 * time.Second,
TLSClientConfig: tlsConfig,
NetDialContext: open,
TLSClientConfig: tlsConfig,
}
header := http.Header{}
+52 -16
View File
@@ -7,6 +7,7 @@ import (
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
@@ -35,31 +36,48 @@ func TestDialWSVerifiesTLSAndSeparatesSNIFromHost(t *testing.T) {
}
defer ws.Close()
requests <- requestNames{r.Host, r.TLS.ServerName}
kind, payload, err := ws.ReadMessage()
if err != nil {
t.Errorf("reading WebSocket payload: %v", err)
return
}
if err := ws.WriteMessage(kind, payload); err != nil {
t.Errorf("writing WebSocket payload: %v", err)
}
}))
t.Cleanup(server.Close)
addr := strings.TrimPrefix(server.URL, "https://")
addr := server.Listener.Addr().String()
roots := x509.NewCertPool()
roots.AddCert(server.Certificate())
const host = "route.example.invalid"
for _, tc := range []struct {
name, sni string
roots *x509.CertPool
wantErr error
name, endpoint, sni string
roots *x509.CertPool
wantErr error
}{
{name: "explicit SNI", sni: "example.com", roots: roots},
{name: "endpoint SNI fallback", roots: roots},
{name: "wrong certificate name", sni: "wrong.invalid", roots: roots, wantErr: x509.HostnameError{}},
{name: "untrusted certificate", sni: "example.com", roots: x509.NewCertPool(), wantErr: x509.UnknownAuthorityError{}},
{name: "explicit SNI", endpoint: "peer.example.invalid", sni: "example.com", roots: roots},
{name: "endpoint SNI fallback", endpoint: "example.com", roots: roots},
{name: "wrong certificate name", endpoint: "peer.example.invalid", sni: "wrong.invalid", roots: roots, wantErr: x509.HostnameError{}},
{name: "untrusted certificate", endpoint: "peer.example.invalid", sni: "example.com", roots: x509.NewCertPool(), wantErr: x509.UnknownAuthorityError{}},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
conn, err := transport.DialWS(ctx, addr, "/tunnel", host, &tls.Config{
ServerName: tc.sni,
RootCAs: tc.roots,
MinVersion: tls.VersionTLS12,
logicalAddr := net.JoinHostPort(tc.endpoint, "8443")
open := func(ctx context.Context, network, address string) (net.Conn, error) {
if network != "tcp" || address != logicalAddr {
t.Fatalf("opener got %s %s, want tcp %s", network, address, logicalAddr)
}
return (&net.Dialer{}).DialContext(ctx, network, addr)
}
conn, err := transport.DialSetup(ctx, open, 0, func(ctx context.Context, open transport.DialContextFunc) (net.Conn, error) {
return transport.DialWS(ctx, logicalAddr, "/tunnel", host, &tls.Config{
ServerName: tc.sni,
RootCAs: tc.roots,
MinVersion: tls.VersionTLS12,
}, open)
})
if conn != nil {
defer conn.Close()
@@ -81,19 +99,37 @@ func TestDialWSVerifiesTLSAndSeparatesSNIFromHost(t *testing.T) {
}
select {
case got := <-requests:
if want := (requestNames{host, tc.sni}); got != want {
wantSNI := tc.sni
if wantSNI == "" {
wantSNI = tc.endpoint
}
if want := (requestNames{host, wantSNI}); got != want {
t.Errorf("request names = %+v, want %+v", got, want)
}
case <-ctx.Done():
t.Fatal("WebSocket request not observed")
}
cancel()
if err := conn.SetDeadline(time.Now().Add(3 * time.Second)); err != nil {
t.Fatal(err)
}
const payload = "after dial cancellation"
if _, err := io.WriteString(conn, payload); err != nil {
t.Fatal(err)
}
var got [len(payload)]byte
if _, err := io.ReadFull(conn, got[:]); err != nil || string(got[:]) != payload {
t.Fatalf("echo = %q, %v", got, err)
}
}
})
}
}
func TestProxyDialersRejectUntrustedCertificates(t *testing.T) {
server := httptest.NewTLSServer(http.NotFoundHandler())
server := httptest.NewUnstartedServer(http.NotFoundHandler())
server.EnableHTTP2 = true
server.StartTLS()
t.Cleanup(server.Close)
addr := strings.TrimPrefix(server.URL, "https://")
host, port, err := net.SplitHostPort(addr)
@@ -117,7 +153,7 @@ func TestProxyDialersRejectUntrustedCertificates(t *testing.T) {
return "vmess://" + base64.StdEncoding.EncodeToString([]byte(data))
}, (&vmess.Dialer{}).Dial},
} {
for _, network := range []string{"tcp", "ws"} {
for _, network := range []string{"tcp", "ws", "grpc"} {
t.Run(tc.name+"/"+network, func(t *testing.T) {
_, up, err := upstream.Canonicalize(tc.link(network))
if err != nil {
+12 -19
View File
@@ -17,18 +17,20 @@ import (
type Dialer struct {
DialTimeout time.Duration
Log *slog.Logger
Open transport.DialContextFunc
}
func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (net.Conn, error) {
return transport.DialSetup(ctx, d.Open, d.DialTimeout, func(ctx context.Context, open transport.DialContextFunc) (net.Conn, error) {
return d.dial(ctx, open, up, dest)
})
}
func (d *Dialer) dial(ctx context.Context, open transport.DialContextFunc, up *upstream.Upstream, dest string) (net.Conn, error) {
if up.Trojan == nil {
return nil, fmt.Errorf("trojan: missing config")
}
timeout := d.DialTimeout
if timeout <= 0 {
timeout = 10 * time.Second
}
var tlsConfig *tls.Config
if up.Trojan.Security != "none" {
sni := up.Trojan.SNI
@@ -48,12 +50,11 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (
if host == "" && tlsConfig != nil {
host = tlsConfig.ServerName
}
conn, err = transport.DialWS(ctx, up.Address(), up.Path, host, tlsConfig)
case up.Transport == "grpc" && tlsConfig != nil:
conn, err = transport.DialGRPC(ctx, up.Address(), up.ServiceName, tlsConfig)
case up.Transport == "" || up.Transport == "tcp" || up.Transport == "raw" || up.Transport == "grpc":
dialer := net.Dialer{Timeout: timeout}
conn, err = dialer.DialContext(ctx, "tcp", up.Address())
conn, err = transport.DialWS(ctx, up.Address(), up.Path, host, tlsConfig, open)
case up.Transport == "grpc":
conn, err = transport.DialGRPC(ctx, up.Address(), up.ServiceName, tlsConfig, open)
case up.Transport == "" || up.Transport == "tcp" || up.Transport == "raw":
conn, err = open(ctx, "tcp", up.Address())
if err == nil && tlsConfig != nil {
tlsConn := tls.Client(conn, tlsConfig)
if err = tlsConn.HandshakeContext(ctx); err != nil {
@@ -62,14 +63,6 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (
}
conn = tlsConn
}
if err == nil && up.Transport == "grpc" {
grpcConn, grpcErr := transport.DialGRPCOverConn(ctx, conn, up.Address(), up.ServiceName)
if grpcErr != nil {
conn.Close()
return nil, fmt.Errorf("trojan: connect: %w", grpcErr)
}
conn = grpcConn
}
default:
return nil, fmt.Errorf("trojan: unsupported transport")
}
+110 -164
View File
@@ -2,12 +2,11 @@ package vless
import (
"bytes"
"encoding/binary"
"errors"
"io"
"net"
"strconv"
"time"
"sync"
"github.com/gofrs/uuid"
)
@@ -26,30 +25,24 @@ const (
AtypIPv6 byte = 3
)
var (
TlsApplicationDataStart = []byte{0x17, 0x03, 0x03}
)
const (
visionReadTimeout = 2 * time.Second
maxReadTimeoutCount = 5
)
// The request starts with version, ID, addons and a single TCP destination.
const maxVLESSRequest = 1 + 16 + 1 + 255 + 1 + 2 + 1 + 1 + 255
type Conn struct {
net.Conn
uuid uuid.UUID
flow string
dest string
received bool
sent bool
visionReadActive bool
visionWriteActive bool
visionUUID []byte
readBuffer []byte
enableXtls bool
tlsAppDataCount int
tlsFinishedSent bool
readTimeoutCount int
request []byte
vision *visionState
readMu sync.Mutex
response [2]byte
responseN int
responseAddon int
received bool
readErr error
writeMu sync.Mutex
sent bool
writeErr error
}
func NewConn(conn net.Conn, uuidStr string, flow string, dest string) (*Conn, error) {
@@ -57,101 +50,105 @@ func NewConn(conn net.Conn, uuidStr string, flow string, dest string) (*Conn, er
if err != nil {
return nil, err
}
c := &Conn{
Conn: conn,
uuid: uid,
flow: flow,
dest: dest,
request, err := requestHeader(uid, flow, dest)
if err != nil {
return nil, err
}
c := &Conn{Conn: conn, request: request}
if flow == "xtls-rprx-vision" {
c.visionReadActive = true
c.visionWriteActive = true
c.visionUUID = uid.Bytes()
c.vision = &visionState{uuid: uid}
// NetConn exposes the record-bounded socket beneath either TLS implementation.
if outer, ok := conn.(interface{ NetConn() net.Conn }); ok {
c.vision.wire, _ = outer.NetConn().(*visionTLSWire)
}
}
return c, nil
}
func (c *Conn) Read(b []byte) (int, error) {
if len(b) == 0 {
return 0, nil
}
c.readMu.Lock()
defer c.readMu.Unlock()
if c.readErr != nil {
return 0, c.readErr
}
if !c.received {
if err := c.recvResponse(); err != nil {
return 0, err
if err := c.recvResponse(b); err != nil {
return 0, c.rememberReadError(err)
}
c.received = true
}
if len(c.readBuffer) > 0 {
n := copy(b, c.readBuffer)
c.readBuffer = c.readBuffer[n:]
return n, nil
if c.vision != nil {
n, err := c.vision.read(c.Conn, b)
return n, c.rememberReadError(err)
}
if c.visionReadActive {
return c.readVisionPadded(b)
}
return c.Conn.Read(b)
}
func (c *Conn) Write(b []byte) (int, error) {
if !c.sent {
if len(b) == 0 {
return 0, nil
if len(b) == 0 {
return 0, nil
}
c.writeMu.Lock()
defer c.writeMu.Unlock()
if c.writeErr != nil {
return 0, c.writeErr
}
if c.vision != nil {
n, err := c.vision.write(c.Conn, c.request, b)
c.request = nil
if err != nil {
// A partially transmitted frame cannot be retried as application bytes.
c.writeErr = err
_ = c.Close()
}
if err := c.sendRequest(b); err != nil {
return n, err
}
if !c.sent {
if err := writeVLESSWire(c.Conn, c.request); err != nil {
c.writeErr = err
_ = c.Close()
return 0, err
}
c.sent = true
return len(b), nil
c.request = nil
}
if c.visionWriteActive {
if len(b) >= 3 && bytes.Equal(b[:3], TlsApplicationDataStart) {
c.tlsAppDataCount++
if c.tlsAppDataCount == 1 {
c.tlsFinishedSent = true
return c.writeVisionPadded(b, CommandPaddingContinue)
}
c.visionWriteActive = false
c.enableXtls = true
return c.writeVisionPadded(b, CommandPaddingDirect)
}
return c.writeVisionPadded(b, CommandPaddingContinue)
}
return c.Conn.Write(b)
}
func (c *Conn) sendRequest(payload []byte) error {
buf := &bytes.Buffer{}
func (c *Conn) Close() error {
if c.vision != nil && c.vision.wire != nil {
// TLS.Close can send an outer close_notify after either direction has
// stopped using the outer TLS record layer.
return c.vision.wire.Close()
}
return c.Conn.Close()
}
func requestHeader(uid uuid.UUID, flow, dest string) ([]byte, error) {
host, portStr, err := net.SplitHostPort(dest)
if err != nil {
return nil, err
}
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil || port == 0 || host == "" || len(host) > 255 || len(flow) > 253 {
return nil, errors.New("invalid VLESS destination or flow")
}
var buf bytes.Buffer
buf.WriteByte(Version)
buf.Write(c.uuid.Bytes())
if c.flow != "" && c.flow != "none" {
addonBuf := &bytes.Buffer{}
flowBytes := []byte(c.flow)
addonBuf.WriteByte(0x0A)
addonBuf.WriteByte(byte(len(flowBytes)))
addonBuf.Write(flowBytes)
buf.WriteByte(byte(addonBuf.Len()))
buf.Write(addonBuf.Bytes())
buf.Write(uid[:])
if flow != "" && flow != "none" {
buf.WriteByte(byte(2 + len(flow)))
buf.WriteByte(0x0a)
buf.WriteByte(byte(len(flow)))
buf.WriteString(flow)
} else {
buf.WriteByte(0)
}
buf.WriteByte(CommandTCP)
host, portStr, err := net.SplitHostPort(c.dest)
if err != nil {
return err
}
port, _ := strconv.Atoi(portStr)
binary.Write(buf, binary.BigEndian, uint16(port))
buf.WriteByte(byte(port >> 8))
buf.WriteByte(byte(port))
if ip := net.ParseIP(host); ip != nil {
if v4 := ip.To4(); v4 != nil {
buf.WriteByte(AtypIPv4)
@@ -163,94 +160,43 @@ func (c *Conn) sendRequest(payload []byte) error {
} else {
buf.WriteByte(AtypDomainName)
buf.WriteByte(byte(len(host)))
buf.Write([]byte(host))
buf.WriteString(host)
}
if c.visionWriteActive && len(payload) > 0 {
paddedPayload := ApplyVisionPaddingWithCmd(payload, c.visionUUID, CommandPaddingContinue)
buf.Write(paddedPayload)
c.visionUUID = nil
} else {
buf.Write(payload)
}
_, err = c.Conn.Write(buf.Bytes())
return err
return buf.Bytes(), nil
}
func (c *Conn) recvResponse() error {
header := make([]byte, 2)
_, err := io.ReadFull(c.Conn, header)
if err != nil {
return err
}
if header[0] != Version {
return errors.New("invalid VLESS response version")
}
addonLen := int(header[1])
if addonLen > 0 {
addon := make([]byte, addonLen)
_, err = io.ReadFull(c.Conn, addon)
func (c *Conn) recvResponse(scratch []byte) error {
if c.responseN < len(c.response) {
n, err := io.ReadFull(c.Conn, c.response[c.responseN:])
c.responseN += n
if err != nil {
return err
}
if c.response[0] != Version {
return errors.New("invalid VLESS response version")
}
c.responseAddon = int(c.response[1])
}
if err := discardVisionBytes(c.Conn, scratch, &c.responseAddon); err != nil {
return err
}
c.received = true
return nil
}
func (c *Conn) writeVisionPadded(b []byte, cmd byte) (int, error) {
padded := ApplyVisionPaddingWithCmd(b, c.visionUUID, cmd)
if c.visionUUID != nil {
c.visionUUID = nil
}
_, err := c.Conn.Write(padded)
func (c *Conn) rememberReadError(err error) error {
if err != nil {
return 0, err
if timeout, ok := err.(net.Error); !ok || !timeout.Timeout() {
c.readErr = err
}
}
return len(b), nil
return err
}
func (c *Conn) readVisionPadded(b []byte) (int, error) {
content, cmd, err := ReadVisionPaddedWithTimeout(c.Conn, visionReadTimeout)
if err == ErrVisionTimeout {
c.readTimeoutCount++
if c.readTimeoutCount >= maxReadTimeoutCount || c.enableXtls {
c.visionReadActive = false
}
return 0, nil
func writeVLESSWire(w io.Writer, data []byte) error {
n, err := w.Write(data)
if n != len(data) && err == nil {
return io.ErrShortWrite
}
c.readTimeoutCount = 0
if err == ErrNotVisionFrame {
c.visionReadActive = false
if content != nil {
n := copy(b, content)
if n < len(content) {
c.readBuffer = content[n:]
}
return n, nil
}
return 0, nil
}
if err != nil {
return 0, err
}
if cmd == CommandPaddingEnd || cmd == CommandPaddingDirect {
c.visionReadActive = false
} else if c.enableXtls && len(content) >= 3 && bytes.Equal(content[:3], TlsApplicationDataStart) {
c.visionReadActive = false
}
n := copy(b, content)
if n < len(content) {
c.readBuffer = content[n:]
}
return n, nil
return err
}
+29 -46
View File
@@ -15,9 +15,16 @@ import (
type Dialer struct {
DialTimeout time.Duration
Log *slog.Logger
Open transport.DialContextFunc
}
func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (net.Conn, error) {
return transport.DialSetup(ctx, d.Open, d.DialTimeout, func(ctx context.Context, open transport.DialContextFunc) (net.Conn, error) {
return d.dial(ctx, open, up, dest)
})
}
func (d *Dialer) dial(ctx context.Context, open transport.DialContextFunc, up *upstream.Upstream, dest string) (net.Conn, error) {
if up.VLESS == nil {
return nil, fmt.Errorf("vless: missing config")
}
@@ -27,11 +34,6 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (
"security", up.VLESS.Security, "flow", up.VLESS.Flow, "transport", up.Transport)
}
timeout := d.DialTimeout
if timeout <= 0 {
timeout = 10 * time.Second
}
sni := up.VLESS.SNI
if sni == "" {
sni = up.Host
@@ -50,16 +52,17 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (
if host == "" && (tlsConfig != nil || up.VLESS.Security == "reality") {
host = sni
}
c, err = transport.DialWS(ctx, up.Address(), up.Path, host, tlsConfig)
c, err = transport.DialWS(ctx, up.Address(), up.Path, host, tlsConfig, open)
case "grpc":
// gRPC requires the security layer to be established BEFORE HTTP/2.
// Dial raw TCP, apply Reality/TLS, then put gRPC on top.
c, err = d.dialGRPC(ctx, up, timeout, sni, tlsConfig)
if up.VLESS.Security == "reality" {
c, err = d.dialRealityGRPC(ctx, open, up, sni)
} else {
c, err = transport.DialGRPC(ctx, up.Address(), up.ServiceName, tlsConfig, open)
}
case "", "tcp", "raw":
dialer := net.Dialer{Timeout: timeout}
c, err = dialer.DialContext(ctx, "tcp", up.Address())
c, err = open(ctx, "tcp", up.Address())
default:
return nil, fmt.Errorf("vless: unsupported transport")
}
@@ -72,7 +75,7 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (
d.Log.Debug("vless connected", "upstream", up.Address())
}
// Apply security for non-gRPC transports (gRPC handles it internally in dialGRPC).
// gRPC establishes its security layer before starting HTTP/2.
if up.Transport != "grpc" {
if up.VLESS.Security == "reality" {
if d.Log != nil {
@@ -89,6 +92,9 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (
d.Log.Debug("vless reality handshake success")
}
} else if tlsConfig != nil && up.Transport != "ws" {
if up.VLESS.Flow == "xtls-rprx-vision" {
c = newVisionTLSWire(c)
}
tlsConn := tls.Client(c, tlsConfig)
if err = tlsConn.HandshakeContext(ctx); err != nil {
c.Close()
@@ -107,44 +113,21 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (
return conn, nil
}
// dialGRPC handles the gRPC transport: TCP → security → HTTP/2.
func (d *Dialer) dialGRPC(ctx context.Context, up *upstream.Upstream, timeout time.Duration, sni string, tlsConfig *tls.Config) (net.Conn, error) {
rawDialer := net.Dialer{Timeout: timeout}
raw, err := rawDialer.DialContext(ctx, "tcp", up.Address())
// dialRealityGRPC establishes REALITY before passing the socket to HTTP/2.
func (d *Dialer) dialRealityGRPC(ctx context.Context, open transport.DialContextFunc, up *upstream.Upstream, sni string) (net.Conn, error) {
raw, err := open(ctx, "tcp", up.Address())
if err != nil {
return nil, err
}
var underlying net.Conn
switch up.VLESS.Security {
case "reality":
if d.Log != nil {
d.Log.Debug("vless grpc starting reality handshake", "sni", sni)
}
underlying, err = streamRealityConn(ctx, raw, up.VLESS, sni)
if err != nil {
raw.Close()
return nil, fmt.Errorf("reality handshake: %w", err)
}
if d.Log != nil {
d.Log.Debug("vless grpc reality handshake success")
}
case "tls":
tlsConfig.NextProtos = []string{"h2"}
tlsConn := tls.Client(raw, tlsConfig)
if err = tlsConn.HandshakeContext(ctx); err != nil {
raw.Close()
return nil, fmt.Errorf("tls handshake: %w", err)
}
underlying = tlsConn
default:
underlying = raw
if d.Log != nil {
d.Log.Debug("vless grpc starting reality handshake", "sni", sni)
}
conn, err := transport.DialGRPCOverConn(ctx, underlying, up.Address(), up.ServiceName)
underlying, err := streamRealityConn(ctx, raw, up.VLESS, sni)
if err != nil {
underlying.Close()
return nil, fmt.Errorf("grpc: %w", err)
return nil, fmt.Errorf("reality handshake: %w", err)
}
return conn, nil
if d.Log != nil {
d.Log.Debug("vless grpc reality handshake success")
}
return transport.DialGRPCOverConn(ctx, underlying, up.Address(), up.ServiceName)
}
+3
View File
@@ -80,6 +80,9 @@ func streamRealityConn(ctx context.Context, conn net.Conn, cfg *upstream.VLESSCo
},
}
if cfg.Flow == "xtls-rprx-vision" {
conn = newVisionTLSWire(conn)
}
uConn := utls.UClient(conn, utlsConfig, *fingerprint)
if err := uConn.BuildHandshakeState(); err != nil {
+332 -99
View File
@@ -1,128 +1,361 @@
package vless
import (
"bufio"
"bytes"
"crypto/rand"
"encoding/binary"
"errors"
"io"
"net"
"time"
"sync/atomic"
"golang.org/x/crypto/cryptobyte"
)
const (
VisionPaddingHeaderLen = 21
visionWireSize = 2048 // Xray's Vision buffer size, including the first UUID and header.
visionHeaderSize = 5
visionUUIDSize = 16
visionMaxContent = visionWireSize - visionUUIDSize - visionHeaderSize
CommandPaddingContinue = 0x00
CommandPaddingEnd = 0x01
CommandPaddingDirect = 0x02
visionContinue = 0
visionEnd = 1
visionDirect = 2
)
func ApplyVisionPaddingWithCmd(data []byte, uuid []byte, cmd byte) []byte {
paddingLen := 0
if len(data) < 900 {
paddingLen = 900 - len(data) + randInt(500)
} else {
paddingLen = randInt(256)
}
type visionState struct {
uuid [visionUUIDSize]byte
wire *visionTLSWire
frameLen := VisionPaddingHeaderLen + len(data) + paddingLen
frame := make([]byte, frameLen)
offset := 0
if uuid != nil && len(uuid) >= 16 {
copy(frame[offset:], uuid[:16])
}
offset += 16
frame[offset] = cmd
offset++
binary.BigEndian.PutUint16(frame[offset:], uint16(len(data)))
offset += 2
binary.BigEndian.PutUint16(frame[offset:], uint16(paddingLen))
offset += 2
copy(frame[offset:], data)
offset += len(data)
if paddingLen > 0 {
rand.Read(frame[offset:])
}
return frame
// Read owns the server handshake parser; Write only needs its final verdict.
serverTLS13 atomic.Bool
reader visionReader
hello visionServerHello
writer visionWriter
}
var ErrNotVisionFrame = errors.New("not a Vision frame")
var ErrVisionTimeout = errors.New("vision read timeout")
type visionReader struct {
header [visionUUIDSize + visionHeaderSize]byte
headerN int
first bool // The initial UUID has been consumed.
command byte
content int
padding int
finished bool
}
func ReadVisionPaddedWithTimeout(conn net.Conn, timeout time.Duration) ([]byte, byte, error) {
if timeout > 0 {
if tc, ok := conn.(interface{ SetReadDeadline(time.Time) error }); ok {
tc.SetReadDeadline(time.Now().Add(timeout))
defer tc.SetReadDeadline(time.Time{})
func (v *visionState) read(outer io.Reader, b []byte) (int, error) {
r := &v.reader
for !r.finished {
headerSize := visionHeaderSize
if !r.first {
headerSize += visionUUIDSize
}
}
firstByte := make([]byte, 1)
_, err := conn.Read(firstByte)
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
return nil, 0, ErrVisionTimeout
if r.headerN < headerSize {
n, err := io.ReadFull(outer, r.header[r.headerN:headerSize])
r.headerN += n
if err != nil {
if err == io.EOF && r.headerN != 0 {
err = io.ErrUnexpectedEOF
}
return 0, err
}
h := r.header[:headerSize]
if !r.first {
if !bytes.Equal(h[:visionUUIDSize], v.uuid[:]) {
return 0, errors.New("vless: invalid initial Vision UUID")
}
h = h[visionUUIDSize:]
}
r.command = h[0]
if r.command > visionDirect {
return 0, errors.New("vless: invalid Vision command")
}
r.content = int(binary.BigEndian.Uint16(h[1:3]))
r.padding = int(binary.BigEndian.Uint16(h[3:5]))
}
return nil, 0, err
if r.content != 0 {
n, err := outer.Read(b[:min(len(b), r.content)])
r.content -= n
if v.hello.observe(b[:n]) {
v.serverTLS13.Store(true)
}
if err == io.EOF && (r.content != 0 || r.padding != 0) {
err = io.ErrUnexpectedEOF
}
return n, err
}
if err := discardVisionBytes(outer, b, &r.padding); err != nil {
return 0, err
}
r.first = true
r.headerN = 0
r.finished = r.command != visionContinue
}
if r.command == visionDirect {
if v.wire == nil {
return 0, errors.New("vless: Vision direct requires a raw TLS transport")
}
return v.wire.reader.Read(b)
}
return outer.Read(b)
}
if firstByte[0] >= 0x14 && firstByte[0] <= 0x17 {
tlsRest := make([]byte, 4)
_, err := io.ReadFull(conn, tlsRest)
func discardVisionBytes(r io.Reader, scratch []byte, remaining *int) error {
for *remaining != 0 {
n, err := io.ReadFull(r, scratch[:min(len(scratch), *remaining)])
*remaining -= n
if err != nil {
return firstByte, 0, ErrNotVisionFrame
if err == io.EOF {
return io.ErrUnexpectedEOF
}
return err
}
tlsHeader := append(firstByte, tlsRest...)
return tlsHeader, 0, ErrNotVisionFrame
}
header := make([]byte, VisionPaddingHeaderLen)
header[0] = firstByte[0]
_, err = io.ReadFull(conn, header[1:])
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
return firstByte, 0, ErrNotVisionFrame
}
return nil, 0, err
}
cmd := header[16]
contentLen := binary.BigEndian.Uint16(header[17:19])
paddingLen := binary.BigEndian.Uint16(header[19:21])
if cmd > CommandPaddingDirect {
return header, cmd, ErrNotVisionFrame
}
if contentLen > 32768 || paddingLen > 4096 {
return header, cmd, ErrNotVisionFrame
}
totalLen := int(contentLen) + int(paddingLen)
if totalLen == 0 {
return []byte{}, cmd, nil
}
data := make([]byte, totalLen)
_, err = io.ReadFull(conn, data)
if err != nil {
return nil, cmd, err
}
return data[:contentLen], cmd, nil
return nil
}
func randInt(max int) int {
if max <= 0 {
return 0
type visionWriter struct {
frame [maxVLESSRequest + visionWireSize]byte
record tlsRecordStream
clientHello bool
command byte
}
func (v *visionState) write(outer io.Writer, request, data []byte) (int, error) {
w := &v.writer
written := 0
for len(data) != 0 {
switch w.command {
case visionEnd:
n, err := outer.Write(data)
return written + n, err
case visionDirect:
n, err := v.wire.Conn.Write(data)
return written + n, err
}
payload := data[:min(len(data), visionMaxContent)]
w.command = w.nextCommand(payload, v.wire != nil && v.serverTLS13.Load())
start := copy(w.frame[:], request)
if len(request) != 0 {
start += copy(w.frame[start:], v.uuid[:])
}
frame := w.frame[start:]
padding := visionRandom(256)
if w.clientHello && len(payload) < 900 {
padding = 900 - len(payload) + visionRandom(500)
}
padding = min(padding, visionMaxContent-len(payload))
frame[0] = w.command
binary.BigEndian.PutUint16(frame[1:3], uint16(len(payload)))
binary.BigEndian.PutUint16(frame[3:5], uint16(padding))
end := visionHeaderSize + copy(frame[visionHeaderSize:], payload)
clear(frame[end : end+padding])
if err := writeVLESSWire(outer, w.frame[:start+end+padding]); err != nil {
return written, err
}
written += len(payload)
data = data[len(payload):]
request = nil
}
b := make([]byte, 2)
rand.Read(b)
return int(binary.BigEndian.Uint16(b)) % max
return written, nil
}
func visionRandom(max uint32) int {
limit := (1 << 16) / max * max
for {
var data [2]byte
_, _ = rand.Read(data[:])
n := uint32(binary.BigEndian.Uint16(data[:]))
if n < limit {
return int(n % max)
}
}
}
const (
tlsChangeCipherSpec = 20
tlsAlert = 21
tlsHandshake = 22
tlsApplication = 23
tlsRecordHeader = 5
)
// tlsRecordStream finds record boundaries across arbitrary Read and Write splits.
type tlsRecordStream struct {
header [tlsRecordHeader]byte
headerN int
remaining int
}
func (r *tlsRecordStream) take(data []byte) (kind byte, body, rest []byte, valid bool) {
if r.headerN < len(r.header) {
n := copy(r.header[r.headerN:], data)
r.headerN += n
data = data[n:]
if r.header[0] < tlsChangeCipherSpec || r.header[0] > tlsApplication ||
(r.headerN >= 2 && r.header[1] != 3) || (r.headerN >= 3 && r.header[2] > 3) {
return 0, nil, nil, false
}
if r.headerN < len(r.header) {
return 0, nil, nil, true
}
r.remaining = int(binary.BigEndian.Uint16(r.header[3:]))
if r.remaining > 16384+2048 || (r.remaining == 0 && r.header[0] != tlsApplication) {
return 0, nil, nil, false
}
}
kind = r.header[0]
n := min(r.remaining, len(data))
r.remaining -= n
if r.remaining == 0 {
r.headerN = 0
}
return kind, data[:n], data[n:], true
}
func (w *visionWriter) nextCommand(data []byte, direct bool) byte {
for len(data) != 0 {
kind, body, rest, ok := w.record.take(data)
if !ok || (!w.clientHello && kind != 0 && kind != tlsHandshake) {
return visionEnd
}
data = rest
if !w.clientHello && len(body) != 0 {
if body[0] != 1 { // ClientHello handshake type.
return visionEnd
}
w.clientHello = true
}
if kind == tlsApplication {
if direct {
return visionDirect
}
return visionEnd
}
if kind == tlsAlert {
return visionEnd
}
}
return visionContinue
}
type visionServerHello struct {
record tlsRecordStream
header [4]byte
headerN int
body []byte
done bool
}
func (h *visionServerHello) observe(data []byte) bool {
for !h.done && len(data) != 0 {
kind, body, rest, ok := h.record.take(data)
data = rest
if !ok || (kind != 0 && kind != tlsHandshake && kind != tlsChangeCipherSpec) {
h.done = true
break
}
if kind != tlsHandshake {
continue
}
for len(body) != 0 {
if h.headerN < len(h.header) {
n := copy(h.header[h.headerN:], body)
h.headerN += n
body = body[n:]
if h.headerN < len(h.header) {
continue
}
size := int(h.header[1])<<16 | int(h.header[2])<<8 | int(h.header[3])
const maxServerHello = 2 + 32 + 1 + 32 + 2 + 1 + 2 + 65535
if h.header[0] != 2 || size < 38 || size > maxServerHello {
h.done = true
return false
}
h.body = make([]byte, 0, size)
}
n := min(len(body), cap(h.body)-len(h.body))
h.body = append(h.body, body[:n]...)
body = body[n:]
if len(h.body) == cap(h.body) {
direct, retry := visionTLS13Hello(h.body)
h.body = nil
h.headerN = 0
if !retry {
h.done = true
return direct
}
}
}
}
return false
}
func visionTLS13Hello(data []byte) (direct, retry bool) {
// RFC 8446 section 4.1.3: HelloRetryRequest uses the ServerHello format
// with a fixed Random. The negotiated result comes from the next ServerHello.
const retryRandom = "\xcf\x21\xad\x74\xe5\x9a\x61\x11\xbe\x1d\x8c\x02\x1e\x65\xb8\x91\xc2\xa2\x11\x16\x7a\xbb\x8c\x5e\x07\x9e\x09\xe2\xc8\xa8\x33\x9c"
hello := cryptobyte.String(data)
var version, suite uint16
var random []byte
var sessionID, extensions cryptobyte.String
var compression uint8
if !hello.ReadUint16(&version) || version != 0x0303 || !hello.ReadBytes(&random, 32) ||
!hello.ReadUint8LengthPrefixed(&sessionID) || len(sessionID) > 32 || !hello.ReadUint16(&suite) ||
!hello.ReadUint8(&compression) || compression != 0 || !hello.ReadUint16LengthPrefixed(&extensions) || !hello.Empty() {
return false, false
}
for !extensions.Empty() {
var extension uint16
var value cryptobyte.String
if !extensions.ReadUint16(&extension) || !extensions.ReadUint16LengthPrefixed(&value) {
return false, false
}
if extension != 43 { // supported_versions
continue
}
if !value.ReadUint16(&version) || version != 0x0304 || !value.Empty() {
return false, false
}
if string(random) == retryRandom {
return false, true
}
// The pinned peer only switches for TLS 1.3 AES-GCM, ChaCha20-Poly1305
// and AES-128-CCM, excluding the CCM_8 short authentication tag.
return suite >= 0x1301 && suite <= 0x1304, false
}
return false, false
}
// visionTLSWire limits TLS to one outer record at a time. Any read-ahead stays
// in reader, not in TLS's private raw buffer. The peer ends the outer stream
// with the complete direct frame (including its padding), then writes raw data.
// Consequently there are no further decrypted bytes to extract from TLS.
type visionTLSWire struct {
net.Conn
reader *bufio.Reader
header [tlsRecordHeader]byte
headerN int
remaining int
}
func newVisionTLSWire(conn net.Conn) *visionTLSWire {
return &visionTLSWire{Conn: conn, reader: bufio.NewReaderSize(conn, 16*1024)}
}
func (w *visionTLSWire) Read(data []byte) (int, error) {
if w.remaining != 0 {
n, err := w.reader.Read(data[:min(len(data), w.remaining)])
w.remaining -= n
return n, err
}
n, err := w.reader.Read(data[:min(len(data), len(w.header)-w.headerN)])
w.headerN += copy(w.header[w.headerN:], data[:n])
if w.headerN == len(w.header) {
w.remaining = int(binary.BigEndian.Uint16(w.header[3:]))
w.headerN = 0
}
return n, err
}
+523
View File
@@ -0,0 +1,523 @@
package vless
import (
"bufio"
"bytes"
"context"
"crypto/ecdh"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strconv"
"testing"
"testing/iotest"
"time"
"github.com/gofrs/uuid"
"git.eeee.moe/omar/zhguchiy_perchik/internal/upstream"
)
func TestVisionFragmentedFrames(t *testing.T) {
id := [16]byte{0x17, 0x03, 0x03, 1, 2, 3, 4, 5}
var frames bytes.Buffer
frames.Write(id[:])
frames.Write([]byte{0, 0, 3, 0, 2, 'a', 'b', 'c', 0xf1, 0xf2})
frames.Write([]byte{0, 0, 0, 0, 3, 0xf1, 0xf2, 0xf3}) // padding-only
frames.Write([]byte{1, 0, 2, 0, 1, 'd', 'e', 0xf3})
frames.WriteString("outer payload")
input := iotest.OneByteReader(&frames)
var got bytes.Buffer
state := visionState{uuid: id}
for {
var scratch [2]byte
n, err := state.read(input, scratch[:])
got.Write(scratch[:n])
if err == io.EOF {
break
}
if err != nil || n == 0 {
t.Fatalf("read = %d, %v", n, err)
}
}
if got.String() != "abcdeouter payload" {
t.Fatalf("decoded %q", got.String())
}
}
func TestVisionRejectsInvalidFrames(t *testing.T) {
for _, test := range []struct {
name string
input []byte
want error
}{
{"partial UUID", []byte{0, 0, 0}, io.ErrUnexpectedEOF},
{"wrong UUID", append(bytes.Repeat([]byte{1}, 16), 0, 0, 0, 0, 0), nil},
{"unknown command", append(make([]byte, 16), 3, 0, 0, 0, 0), nil},
{"truncated padding", append(make([]byte, 16), 1, 0, 0, 0, 2, 1), io.ErrUnexpectedEOF},
{"truncated content", append(make([]byte, 16), 1, 0, 2, 0, 0, 1), io.ErrUnexpectedEOF},
{"direct without TLS", append(make([]byte, 16), 2, 0, 0, 0, 0), nil},
} {
t.Run(test.name, func(t *testing.T) {
state := visionState{}
input := bytes.NewReader(test.input)
var scratch [8]byte
for {
_, err := state.read(input, scratch[:])
if err == nil {
continue
}
if err == io.EOF || (test.want != nil && !errors.Is(err, test.want)) {
t.Fatalf("wrong error: %v", err)
}
break
}
})
}
}
func TestVisionResumesAfterPartialHeaderDeadline(t *testing.T) {
client, peer := net.Pipe()
defer client.Close()
defer peer.Close()
state := visionState{}
prefix := make([]byte, 9)
done := make(chan error, 1)
resume := make(chan struct{}, 1)
defer close(resume)
go func() {
if _, err := peer.Write(prefix); err != nil {
done <- err
return
}
if err := client.SetReadDeadline(time.Now()); err != nil {
done <- err
return
}
<-resume
_, err := peer.Write(append(make([]byte, 7), 1, 0, 2, 0, 0, 'o', 'k'))
done <- err
}()
var data [2]byte
_, err := state.read(client, data[:])
if !errors.Is(err, os.ErrDeadlineExceeded) {
t.Fatalf("expected caller's deadline, got %v", err)
}
if err := client.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
t.Fatal(err)
}
resume <- struct{}{}
if n, err := state.read(client, data[:]); n != len(data) || err != nil || string(data[:]) != "ok" {
t.Fatalf("resumed read = %d, %v, %q", n, err, data)
}
if err := <-done; err != nil {
t.Fatal(err)
}
}
func TestVisionConcurrentReadAndWrite(t *testing.T) {
client, peer := net.Pipe()
defer client.Close()
defer peer.Close()
deadline := time.Now().Add(2 * time.Second)
if err := client.SetDeadline(deadline); err != nil {
t.Fatal(err)
}
if err := peer.SetDeadline(deadline); err != nil {
t.Fatal(err)
}
id := uuid.UUID{1, 2, 3}
const flow = "xtls-rprx-vision"
const dest = "127.0.0.1:80"
stream, err := NewConn(client, id.String(), flow, dest)
if err != nil {
t.Fatal(err)
}
requestHeaderLen := len(stream.request)
request := bytes.Repeat([]byte("HTTP application bytes\n"), 2048)
clientSent := make(chan error, 1)
go func() {
_, err := stream.Write(request)
clientSent <- err
}()
peerSent := make(chan error, 1)
go func() {
response := append([]byte{0, 0}, id[:]...)
response = append(response, 0, 0, 3, 0, 1, 'a', 'b', 'c', 0xf0)
response = append(response, 1, 0, 3, 0, 1, 'd', 'e', 'f', 0xf1, 'g')
_, err := peer.Write(response)
peerSent <- err
}()
peerReceived := make(chan error, 1)
go func() {
reader := bufio.NewReader(peer)
if _, err := io.CopyN(io.Discard, reader, int64(requestHeaderLen)); err != nil {
peerReceived <- err
return
}
var header [21]byte
if _, err := io.ReadFull(reader, header[:]); err != nil {
peerReceived <- err
return
}
if !bytes.Equal(header[:16], id[:]) || header[16] != 1 {
peerReceived <- errors.New("missing first UUID or HTTP padding end")
return
}
content := int(binary.BigEndian.Uint16(header[17:19]))
padding := int64(binary.BigEndian.Uint16(header[19:21]))
got := make([]byte, len(request))
if content > len(got) {
peerReceived <- errors.New("overlong first Vision content")
return
}
if _, err := io.ReadFull(reader, got[:content]); err != nil {
peerReceived <- err
return
}
if _, err := io.CopyN(io.Discard, reader, padding); err != nil {
peerReceived <- err
return
}
if _, err := io.ReadFull(reader, got[content:]); err != nil {
peerReceived <- err
return
}
if !bytes.Equal(got, request) {
peerReceived <- errors.New("request byte mismatch")
return
}
peerReceived <- nil
}()
var response [7]byte
if _, err := io.ReadFull(stream, response[:]); err != nil || string(response[:]) != "abcdefg" {
t.Fatalf("response = %q, %v", response, err)
}
for _, done := range []<-chan error{clientSent, peerSent, peerReceived} {
if err := <-done; err != nil {
t.Fatal(err)
}
}
}
func TestVisionTLSRecordBoundaries(t *testing.T) {
var server visionServerHello
// RFC 8446 ServerHello body: legacy version, random, empty session ID,
// AES-128-GCM, null compression, supported_versions = TLS 1.3.
hello := append([]byte{2, 0, 0, 46, 3, 3}, make([]byte, 32)...)
hello = append(hello, 0, 0x13, 1, 0, 0, 6, 0, 43, 0, 2, 3, 4)
wire := append(visionTestTLSRecord(22, hello[:9]), visionTestTLSRecord(22, hello[9:])...)
for i := range wire {
if got := server.observe(wire[i : i+1]); got != (i == len(wire)-1) {
t.Fatalf("unexpected server verdict %v at byte %d", got, i)
}
}
for _, test := range []struct {
name string
direct bool
want byte
}{
{"TLS13", true, visionDirect},
{"unconfirmed", false, visionEnd},
} {
t.Run(test.name, func(t *testing.T) {
var writer visionWriter
// An application record signature embedded inside a handshake record
// is not a record boundary. Split the actual application header.
start := visionTestTLSRecord(22, []byte{1, 0, 23, 3, 3, 0, 1, 0})
app := visionTestTLSRecord(23, []byte{1, 2, 3})
for _, piece := range [][]byte{start[:1], start[1:], app[:4]} {
if cmd := writer.nextCommand(piece, test.direct); cmd != visionContinue {
t.Fatalf("premature transition: %d", cmd)
}
}
if cmd := writer.nextCommand(app[4:], test.direct); cmd != test.want {
t.Fatalf("transition = %d, want %d", cmd, test.want)
}
})
}
}
func visionTestTLSRecord(kind byte, data []byte) []byte {
return append([]byte{kind, 3, 3, byte(len(data) >> 8), byte(len(data))}, data...)
}
func TestVisionDirectPreservesRawReadAhead(t *testing.T) {
id := [16]byte{1, 2, 3}
frame := append(id[:], 2, 0, 3, 0, 2, 'a', 'b', 'c', 'x', 'y')
raw := []byte("inner TLS bytes after outer record")
left, right := net.Pipe()
defer left.Close()
defer right.Close()
if err := left.SetDeadline(time.Now().Add(time.Second)); err != nil {
t.Fatal(err)
}
if err := right.SetDeadline(time.Now().Add(time.Second)); err != nil {
t.Fatal(err)
}
wire := newVisionTLSWire(left)
done := make(chan error, 1)
go func() {
// The simulated outer TLS reader may request far more than a record;
// this single socket write lets it demonstrate loss of raw read-ahead.
_, err := right.Write(append(visionTestTLSRecord(23, frame), raw...))
done <- err
}()
var record [1024]byte
if n, err := wire.Read(record[:]); n != 5 || err != nil {
t.Fatalf("outer record header = %d, %v", n, err)
}
bodyLen := int(binary.BigEndian.Uint16(record[3:5]))
if n, err := wire.Read(record[:]); n != bodyLen || err != nil {
t.Fatalf("outer record body = %d, %v", n, err)
}
state := visionState{uuid: id, wire: wire}
outer := bytes.NewReader(record[:bodyLen])
got := make([]byte, 3+len(raw))
for off := 0; off < len(got); {
n, err := state.read(outer, got[off:])
if err != nil || n == 0 {
t.Fatalf("reading direct frame = %d, %v", n, err)
}
off += n
}
if !bytes.Equal(got, append([]byte("abc"), raw...)) {
t.Fatalf("decoded %q", got)
}
if err := <-done; err != nil {
t.Fatal(err)
}
}
func TestRealityVisionXray(t *testing.T) {
bin := os.Getenv("XRAY_BIN")
if bin == "" {
t.Skip("XRAY_BIN must name the pinned Xray binary for REALITY interoperability")
}
cover := httptest.NewUnstartedServer(http.NotFoundHandler())
cover.EnableHTTP2 = true
cover.TLS = &tls.Config{MinVersion: tls.VersionTLS13, CurvePreferences: []tls.CurveID{tls.X25519}}
cover.StartTLS()
t.Cleanup(cover.Close)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/truncated" {
conn, rw, err := http.NewResponseController(w).Hijack()
if err != nil {
http.Error(w, "hijack failed", http.StatusInternalServerError)
return
}
defer conn.Close()
_, _ = rw.WriteString("HTTP/1.1 200 OK\r\nContent-Length: 20\r\nConnection: close\r\n\r\npartial")
_ = rw.Flush()
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 256*1024))
if err != nil || r.Method != http.MethodPost || r.URL.Path != "/echo" {
http.Error(w, "unexpected request", http.StatusBadRequest)
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
_, _ = w.Write(body)
})
plain := httptest.NewServer(handler)
t.Cleanup(plain.Close)
secure := httptest.NewUnstartedServer(handler)
secure.TLS = &tls.Config{MinVersion: tls.VersionTLS13, CurvePreferences: []tls.CurveID{tls.X25519}}
secure.StartTLS()
t.Cleanup(secure.Close)
roots := x509.NewCertPool()
roots.AddCert(secure.Certificate())
key, err := ecdh.X25519().GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
id, err := uuid.NewV4()
if err != nil {
t.Fatal(err)
}
var short [8]byte
_, _ = rand.Read(short[:])
shortID := hex.EncodeToString(short[:])
const serverName = "example.com" // SAN of the standard httptest cover certificate.
address := startVisionXray(t, bin, cover.Listener.Addr().String(), serverName,
id.String(), key.Bytes(), shortID, plain.Listener.Addr().(*net.TCPAddr).Port,
secure.Listener.Addr().(*net.TCPAddr).Port)
for _, test := range []struct {
name string
server *httptest.Server
useTLS bool
}{
{"HTTP", plain, false},
{"HTTPS", secure, true},
} {
t.Run(test.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 12*time.Second)
defer cancel()
dialer := net.Dialer{}
raw, err := dialer.DialContext(ctx, "tcp", address)
if err != nil {
t.Fatal(err)
}
defer raw.Close()
deadline, _ := ctx.Deadline()
if err := raw.SetDeadline(deadline); err != nil {
t.Fatal(err)
}
outer, err := streamRealityConn(ctx, raw, &upstream.VLESSConfig{
PublicKey: base64.RawURLEncoding.EncodeToString(key.PublicKey().Bytes()),
ShortID: shortID, Fingerprint: "firefox", Flow: "xtls-rprx-vision",
}, serverName)
if err != nil {
t.Fatalf("REALITY handshake: %v", err)
}
vless, err := NewConn(outer, id.String(), "xtls-rprx-vision", test.server.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer vless.Close()
var stream net.Conn = vless
if test.useTLS {
inner := tls.Client(stream, &tls.Config{MinVersion: tls.VersionTLS13, RootCAs: roots, ServerName: "127.0.0.1"})
if err := inner.HandshakeContext(ctx); err != nil {
t.Fatalf("origin TLS handshake: %v", err)
}
stream = inner
}
reader := bufio.NewReader(stream)
for i := byte(0); i < 3; i++ {
var nonce [24]byte
_, _ = rand.Read(nonce[:])
body := bytes.Repeat(append(nonce[:], i), 4096)
resp := visionOriginRequest(t, ctx, stream, reader, http.MethodPost, test.server.URL+"/echo", body)
got, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil || !bytes.Equal(got, body) || resp.Close {
t.Fatalf("keep-alive exchange %d: received %d/%d bytes, close=%v, err=%v", i, len(got), len(body), resp.Close, err)
}
}
if test.useTLS {
if vless.vision.writer.command != visionDirect || !vless.vision.reader.finished || vless.vision.reader.command != visionDirect {
t.Fatalf("Vision did not switch in both directions (write=%d, read=%d)", vless.vision.writer.command, vless.vision.reader.command)
}
} else if vless.vision.writer.command != visionEnd || vless.vision.reader.command == visionDirect {
t.Fatal("plain HTTP did not stay on the outer encrypted transport")
}
resp := visionOriginRequest(t, ctx, stream, reader, http.MethodGet, test.server.URL+"/truncated", nil)
got, err := io.ReadAll(resp.Body)
resp.Body.Close()
if string(got) != "partial" || !errors.Is(err, io.ErrUnexpectedEOF) {
t.Fatalf("truncated origin response = %q, %v", got, err)
}
})
}
}
func visionOriginRequest(t *testing.T, ctx context.Context, stream io.Writer, reader *bufio.Reader, method, target string, body []byte) *http.Response {
t.Helper()
req, err := http.NewRequestWithContext(ctx, method, target, bytes.NewReader(body))
if err != nil {
t.Fatal(err)
}
if err := req.Write(stream); err != nil {
t.Fatalf("request write: %v", err)
}
resp, err := http.ReadResponse(reader, req)
if err != nil {
t.Fatalf("response read: %v", err)
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
t.Fatalf("origin response status = %d", resp.StatusCode)
}
return resp
}
func startVisionXray(t *testing.T, bin, cover, sni, id string, key []byte, shortID string, httpPort, httpsPort int) string {
t.Helper()
listener, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := listener.Addr().(*net.TCPAddr)
if err := listener.Close(); err != nil {
t.Fatal(err)
}
config := map[string]any{
"log": map[string]any{"loglevel": "none"},
"inbounds": []any{map[string]any{
"listen": "127.0.0.1", "port": addr.Port, "protocol": "vless",
"settings": map[string]any{"decryption": "none", "clients": []any{map[string]any{"id": id, "flow": "xtls-rprx-vision"}}},
"streamSettings": map[string]any{
"network": "tcp", "security": "reality",
"realitySettings": map[string]any{
"target": cover, "serverNames": []string{sni}, "shortIds": []string{shortID},
"privateKey": base64.RawURLEncoding.EncodeToString(key),
},
},
}},
"outbounds": []any{
map[string]any{"protocol": "blackhole", "tag": "deny"},
map[string]any{"protocol": "freedom", "tag": "fixture"},
},
"routing": map[string]any{"rules": []any{map[string]any{
"type": "field", "ip": []string{"127.0.0.1/32"}, "network": "tcp",
"port": strconv.Itoa(httpPort) + "," + strconv.Itoa(httpsPort), "outboundTag": "fixture",
}}},
}
data, err := json.Marshal(config)
if err != nil {
t.Fatal(err)
}
path := filepath.Join(t.TempDir(), "xray.json")
if err := os.WriteFile(path, data, 0600); err != nil {
t.Fatal(err)
}
cmd := exec.CommandContext(t.Context(), bin, "run", "-config", path)
cmd.Stdout, cmd.Stderr = io.Discard, io.Discard
if err := cmd.Start(); err != nil {
t.Fatalf("start Xray: %v", err)
}
exited := make(chan struct{})
var exitErr error
go func() {
exitErr = cmd.Wait()
close(exited)
}()
t.Cleanup(func() {
_ = cmd.Process.Kill()
<-exited
})
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
tick := time.NewTicker(20 * time.Millisecond)
defer tick.Stop()
dialer := net.Dialer{Timeout: 100 * time.Millisecond}
for {
conn, err := dialer.DialContext(ctx, "tcp4", addr.String())
if err == nil {
conn.Close()
return addr.String()
}
select {
case <-exited:
t.Fatalf("Xray exited before listening: %v", exitErr)
case <-ctx.Done():
t.Fatalf("Xray did not start listening: %v", ctx.Err())
case <-tick.C:
}
}
}
+99 -68
View File
@@ -5,12 +5,12 @@ import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
"hash/fnv"
"io"
"math/rand"
"net"
"strconv"
"sync"
@@ -40,6 +40,7 @@ type Conn struct {
security byte
isAead bool
received bool
readLock sync.Mutex
}
func (vc *Conn) Write(b []byte) (int, error) {
@@ -47,6 +48,9 @@ func (vc *Conn) Write(b []byte) (int, error) {
}
func (vc *Conn) Read(b []byte) (int, error) {
vc.readLock.Lock()
defer vc.readLock.Unlock()
if vc.received {
return vc.reader.Read(b)
}
@@ -67,7 +71,9 @@ func (vc *Conn) sendRequest() error {
buf.WriteByte(vc.respV)
buf.WriteByte(OptionChunkStream)
p := rand.Intn(16)
var padding [16]byte
rand.Read(padding[:])
p := int(padding[0] & 15)
buf.WriteByte(byte(p<<4) | byte(vc.security))
buf.WriteByte(0)
if vc.dst.UDP {
@@ -80,11 +86,7 @@ func (vc *Conn) sendRequest() error {
buf.WriteByte(vc.dst.AddrType)
buf.Write(vc.dst.Addr)
if p > 0 {
padding := make([]byte, p)
rand.Read(padding)
buf.Write(padding)
}
buf.Write(padding[1 : 1+p])
fnv1a := fnv.New32a()
fnv1a.Write(buf.Bytes())
@@ -93,7 +95,10 @@ func (vc *Conn) sendRequest() error {
var fixedLengthCmdKey [16]byte
copy(fixedLengthCmdKey[:], vc.id.CmdKey)
vmessout := sealVMessAEADHeader(fixedLengthCmdKey, buf.Bytes(), timestamp)
_, err := vc.Conn.Write(vmessout)
n, err := vc.Conn.Write(vmessout)
if err == nil && n != len(vmessout) {
return io.ErrShortWrite
}
return err
}
@@ -146,12 +151,10 @@ func (vc *Conn) recvResponse() error {
}
func newConn(conn net.Conn, id *ID, dst *DstAddr, security Security) (*Conn, error) {
randBytes := make([]byte, 33)
rand.Read(randBytes)
reqBodyIV := make([]byte, 16)
reqBodyKey := make([]byte, 16)
copy(reqBodyIV[:], randBytes[:16])
copy(reqBodyKey[:], randBytes[16:32])
var randBytes [33]byte
rand.Read(randBytes[:])
reqBodyIV := randBytes[:16:16]
reqBodyKey := randBytes[16:32:32]
respV := randBytes[32]
bodyKey := sha256.Sum256(reqBodyKey)
@@ -246,110 +249,138 @@ func ParseDest(dest string) (*DstAddr, error) {
// AEAD reader/writer
// The counter occupies the first two bytes of each body-frame nonce.
const aeadFrameLimit = 1 << 16
var errAEADNonceExhausted = errors.New("vmess: AEAD frame nonce exhausted")
type aeadWriter struct {
io.Writer
cipher.AEAD
nonce [32]byte
count uint16
iv []byte
nonce [12]byte
count uint32
err error
writeLock sync.Mutex
}
func newAEADWriter(w io.Writer, aead cipher.AEAD, iv []byte) *aeadWriter {
return &aeadWriter{Writer: w, AEAD: aead, iv: iv}
writer := &aeadWriter{Writer: w, AEAD: aead}
copy(writer.nonce[2:], iv[2:12])
return writer
}
func (w *aeadWriter) Write(b []byte) (n int, err error) {
func (w *aeadWriter) Write(b []byte) (int, error) {
if len(b) == 0 {
return 0, nil
}
w.writeLock.Lock()
defer w.writeLock.Unlock()
buf := make([]byte, maxSize+lenSize)
length := len(b)
for {
if length == 0 {
break
}
readLen := chunkSize - w.Overhead()
if length < readLen {
readLen = length
}
payloadBuf := buf[lenSize : lenSize+chunkSize-w.Overhead()]
copy(payloadBuf, b[n:n+readLen])
if w.err != nil {
return 0, w.err
}
if w.count >= aeadFrameLimit {
return 0, errAEADNonceExhausted
}
binary.BigEndian.PutUint16(buf[:lenSize], uint16(readLen+w.Overhead()))
binary.BigEndian.PutUint16(w.nonce[:2], w.count)
copy(w.nonce[2:], w.iv[2:12])
w.Seal(payloadBuf[:0], w.nonce[:w.NonceSize()], payloadBuf[:readLen], nil)
overhead := w.Overhead()
maxPayload := chunkSize - overhead
buf := make([]byte, lenSize, lenSize+min(len(b), maxPayload)+overhead)
n := 0
for n < len(b) {
if w.count >= aeadFrameLimit {
return n, errAEADNonceExhausted
}
payloadSize := min(len(b)-n, maxPayload)
binary.BigEndian.PutUint16(buf, uint16(payloadSize+overhead))
binary.BigEndian.PutUint16(w.nonce[:2], uint16(w.count))
frame := w.Seal(buf, w.nonce[:], b[n:n+payloadSize], nil)
w.count++
_, err = w.Writer.Write(buf[:lenSize+readLen+w.Overhead()])
written, err := w.Writer.Write(frame)
if written == len(frame) {
n += payloadSize
} else if err == nil {
err = io.ErrShortWrite
}
if err != nil {
break
// A partial frame cannot be resumed with a new nonce.
w.err = err
return n, err
}
n += readLen
length -= readLen
}
return
return n, nil
}
type aeadReader struct {
io.Reader
cipher.AEAD
nonce [32]byte
nonce [12]byte
buf []byte
offset int
iv []byte
sizeBuf []byte
count uint16
sizeBuf [lenSize]byte
count uint32
err error
}
func newAEADReader(r io.Reader, aead cipher.AEAD, iv []byte) *aeadReader {
return &aeadReader{Reader: r, AEAD: aead, iv: iv, sizeBuf: make([]byte, lenSize)}
reader := &aeadReader{Reader: r, AEAD: aead}
copy(reader.nonce[2:], iv[2:12])
return reader
}
func (r *aeadReader) Read(b []byte) (int, error) {
if r.buf != nil {
n := copy(b, r.buf[r.offset:])
r.offset += n
if r.offset == len(r.buf) {
if len(b) == 0 {
return 0, nil
}
if len(r.buf) > 0 {
n := copy(b, r.buf)
r.buf = r.buf[n:]
if len(r.buf) == 0 {
r.buf = nil
}
return n, nil
}
if r.err != nil {
return 0, r.err
}
if r.count >= aeadFrameLimit {
return 0, errAEADNonceExhausted
}
_, err := io.ReadFull(r.Reader, r.sizeBuf)
n, err := io.ReadFull(r.Reader, r.sizeBuf[:])
if err != nil {
if n > 0 {
r.err = err
}
return 0, err
}
size := int(binary.BigEndian.Uint16(r.sizeBuf))
if size > maxSize {
return 0, errors.New("buffer is larger than standard")
size := int(binary.BigEndian.Uint16(r.sizeBuf[:]))
if size < r.Overhead() || size > maxSize {
r.err = errors.New("vmess: invalid AEAD frame size")
return 0, r.err
}
buf := make([]byte, size)
_, err = io.ReadFull(r.Reader, buf)
if err != nil {
if _, err := io.ReadFull(r.Reader, buf); err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
r.err = err
return 0, err
}
binary.BigEndian.PutUint16(r.nonce[:2], r.count)
copy(r.nonce[2:], r.iv[2:12])
_, err = r.Open(buf[:0], r.nonce[:r.NonceSize()], buf[:size], nil)
binary.BigEndian.PutUint16(r.nonce[:2], uint16(r.count))
plaintext, err := r.Open(buf[:0], r.nonce[:], buf, nil)
r.count++
if err != nil {
r.err = err
return 0, err
}
realLen := size - r.Overhead()
n := copy(b, buf[:realLen])
if len(b) >= realLen {
return n, nil
n = copy(b, plaintext)
if n < len(plaintext) {
r.buf = plaintext[n:]
}
r.offset = n
r.buf = buf[:realLen]
return n, nil
}
+204
View File
@@ -0,0 +1,204 @@
package vmess
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"errors"
"io"
"net"
"testing"
"golang.org/x/crypto/chacha20poly1305"
)
const testBodyIV = "0123456789abcdef"
func testAESGCM(t *testing.T) cipher.AEAD {
t.Helper()
block, err := aes.NewCipher([]byte("0123456789abcdef"))
if err != nil {
t.Fatal(err)
}
aead, err := cipher.NewGCM(block)
if err != nil {
t.Fatal(err)
}
return aead
}
func testBodyAEADs(t *testing.T, test func(*testing.T, cipher.AEAD)) {
t.Helper()
t.Run("AES-GCM", func(t *testing.T) {
test(t, testAESGCM(t))
})
t.Run("ChaCha20-Poly1305", func(t *testing.T) {
aead, err := chacha20poly1305.New([]byte("0123456789abcdef0123456789abcdef"))
if err != nil {
t.Fatal(err)
}
test(t, aead)
})
}
// Independent frame encoding: the size excludes its own prefix and the two
// nonce bytes are the big-endian wire counter, not the initial IV prefix.
func appendTestFrame(dst []byte, aead cipher.AEAD, counter uint16, plaintext []byte) []byte {
nonce := [12]byte{byte(counter >> 8), byte(counter)}
copy(nonce[2:], testBodyIV[2:])
dst = binary.BigEndian.AppendUint16(dst, uint16(len(plaintext)+aead.Overhead()))
return aead.Seal(dst, nonce[:], plaintext, nil)
}
func TestAEADWriterNonceExhaustion(t *testing.T) {
testBodyAEADs(t, func(t *testing.T, aead cipher.AEAD) {
var wire bytes.Buffer
w := newAEADWriter(&wire, aead, []byte(testBodyIV))
w.count = 0xfffe
previous := []byte("previous")
if n, err := w.Write(previous); n != len(previous) || err != nil {
t.Fatalf("penultimate frame: got (%d, %v)", n, err)
}
lastSize := chunkSize - aead.Overhead()
payload := bytes.Repeat([]byte{0xa5}, lastSize+1)
if n, err := w.Write(payload); n != lastSize || !errors.Is(err, errAEADNonceExhausted) {
t.Fatalf("boundary write: got (%d, %v), want (%d, nonce exhausted)", n, err, lastSize)
}
if n, err := w.Write(payload[lastSize:]); n != 0 || !errors.Is(err, errAEADNonceExhausted) {
t.Fatalf("write after exhaustion: got (%d, %v)", n, err)
}
want := appendTestFrame(nil, aead, 0xfffe, previous)
want = appendTestFrame(want, aead, 0xffff, payload[:lastSize])
if !bytes.Equal(wire.Bytes(), want) {
t.Fatalf("wire does not contain exactly the final two frames: got %d bytes, want %d", wire.Len(), len(want))
}
})
}
func TestAEADReaderNonceExhaustion(t *testing.T) {
testBodyAEADs(t, func(t *testing.T, aead cipher.AEAD) {
previous := []byte("first")
last := []byte("last valid frame")
wire := appendTestFrame(nil, aead, 0xfffe, previous)
wire = appendTestFrame(wire, aead, 0xffff, last)
source := bytes.NewReader(append(wire, 0x42))
r := newAEADReader(source, aead, []byte(testBodyIV))
r.count = 0xfffe
got := make([]byte, len(previous))
if n, err := r.Read(got); n != len(previous) || err != nil || !bytes.Equal(got, previous) {
t.Fatalf("penultimate frame: got (%d, %v, %q)", n, err, got)
}
got = make([]byte, len(last))
for off := 0; off < len(got); {
part := got[off:min(off+3, len(got))]
n, err := r.Read(part)
if n != len(part) || err != nil {
t.Fatalf("last frame at offset %d: got (%d, %v), want (%d, nil)", off, n, err, len(part))
}
off += n
}
if !bytes.Equal(got, last) {
t.Fatalf("last frame: got %q, want %q", got, last)
}
for range 2 {
if n, err := r.Read(got); n != 0 || !errors.Is(err, errAEADNonceExhausted) {
t.Fatalf("read after exhaustion: got (%d, %v)", n, err)
}
}
if source.Len() != 1 {
t.Fatal("reader consumed wire data after nonce exhaustion")
}
})
}
type testFrameWriter func([]byte) (int, error)
func (f testFrameWriter) Write(p []byte) (int, error) { return f(p) }
func TestAEADWriterFrameWriteFailureIsTerminal(t *testing.T) {
wireErr := errors.New("write failed")
for _, tt := range []struct {
name string
truncated bool
wireErr error
wantErr error
}{
{"short write without error", true, nil, io.ErrShortWrite},
{"short write with error", true, wireErr, wireErr},
{"complete frame with error", false, wireErr, wireErr},
} {
t.Run(tt.name, func(t *testing.T) {
calls := 0
sink := testFrameWriter(func(frame []byte) (int, error) {
calls++
if tt.truncated {
return len(frame) - 1, tt.wireErr
}
return len(frame), tt.wireErr
})
w := newAEADWriter(sink, testAESGCM(t), []byte(testBodyIV))
payload := []byte("frame")
wantN := len(payload)
if tt.truncated {
wantN = 0
}
if n, err := w.Write(payload); n != wantN || !errors.Is(err, tt.wantErr) {
t.Fatalf("failed write: got (%d, %v), want (%d, %v)", n, err, wantN, tt.wantErr)
}
if n, err := w.Write(payload); n != 0 || !errors.Is(err, tt.wantErr) || calls != 1 {
t.Fatalf("write after failure: got (%d, %v), underlying calls = %d", n, err, calls)
}
})
}
}
func TestAEADReaderFrameFailureIsTerminal(t *testing.T) {
aead := testAESGCM(t)
frame := appendTestFrame(nil, aead, 0, []byte("frame"))
corrupt := bytes.Clone(frame)
corrupt[len(corrupt)-1] ^= 1
next := appendTestFrame(nil, aead, 1, []byte("next frame"))
for _, tt := range []struct {
name string
wire []byte
wantErr error
}{
{"truncated length", frame[:1], io.ErrUnexpectedEOF},
{"missing body", frame[:2], io.ErrUnexpectedEOF},
{"truncated body", frame[:len(frame)-1], io.ErrUnexpectedEOF},
{"size below tag length", append([]byte{0, 1}, next...), nil},
{"size above maximum", append(binary.BigEndian.AppendUint16(nil, maxSize+1), next...), nil},
{"invalid tag", append(corrupt, next...), nil},
} {
t.Run(tt.name, func(t *testing.T) {
source := bytes.NewReader(tt.wire)
r := newAEADReader(source, aead, []byte(testBodyIV))
var buf [32]byte
n, err := r.Read(buf[:])
if n != 0 || err == nil || (tt.wantErr != nil && !errors.Is(err, tt.wantErr)) {
t.Fatalf("broken frame: got (%d, %v), expected framing error %v", n, err, tt.wantErr)
}
remaining := source.Len()
if n, retryErr := r.Read(buf[:]); n != 0 || retryErr != err || source.Len() != remaining {
t.Fatalf("read after failure: got (%d, %v), consumed %d more bytes", n, retryErr, remaining-source.Len())
}
})
}
}
type shortRequestConn struct{ net.Conn }
func (shortRequestConn) Write(b []byte) (int, error) { return len(b) - 1, nil }
func TestNewConnRejectsShortRequestHeaderWrite(t *testing.T) {
id := &ID{CmdKey: make([]byte, IDBytesLen)}
dst := &DstAddr{AddrType: AtypIPv4, Addr: []byte{192, 0, 2, 1}, Port: 80}
conn, err := newConn(shortRequestConn{}, id, dst, SecurityAES128GCM)
if conn != nil || !errors.Is(err, io.ErrShortWrite) {
t.Fatalf("short request header write: want nil conn and ErrShortWrite, got nonnil=%t error=%v", conn != nil, err)
}
}
+12 -19
View File
@@ -18,9 +18,16 @@ import (
type Dialer struct {
DialTimeout time.Duration
Log *slog.Logger
Open transport.DialContextFunc
}
func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (net.Conn, error) {
return transport.DialSetup(ctx, d.Open, d.DialTimeout, func(ctx context.Context, open transport.DialContextFunc) (net.Conn, error) {
return d.dial(ctx, open, up, dest)
})
}
func (d *Dialer) dial(ctx context.Context, open transport.DialContextFunc, up *upstream.Upstream, dest string) (net.Conn, error) {
if up.VMess == nil {
return nil, fmt.Errorf("vmess: missing config")
}
@@ -29,11 +36,6 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (
d.Log.Debug("vmess dial", "upstream", up.Address(), "dest", dest, "security", up.VMess.Security, "transport", up.Transport)
}
timeout := d.DialTimeout
if timeout <= 0 {
timeout = 10 * time.Second
}
var tlsConfig *tls.Config
if up.VMess.TLS {
sni := up.VMess.ServerName
@@ -52,12 +54,11 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (
if host == "" && tlsConfig != nil {
host = tlsConfig.ServerName
}
c, err = transport.DialWS(ctx, up.Address(), up.Path, host, tlsConfig)
case up.Transport == "grpc" && tlsConfig != nil:
c, err = transport.DialGRPC(ctx, up.Address(), up.ServiceName, tlsConfig)
case up.Transport == "" || up.Transport == "tcp" || up.Transport == "raw" || up.Transport == "grpc":
dialer := net.Dialer{Timeout: timeout}
c, err = dialer.DialContext(ctx, "tcp", up.Address())
c, err = transport.DialWS(ctx, up.Address(), up.Path, host, tlsConfig, open)
case up.Transport == "grpc":
c, err = transport.DialGRPC(ctx, up.Address(), up.ServiceName, tlsConfig, open)
case up.Transport == "" || up.Transport == "tcp" || up.Transport == "raw":
c, err = open(ctx, "tcp", up.Address())
if err == nil && tlsConfig != nil {
tlsConn := tls.Client(c, tlsConfig)
if err = tlsConn.HandshakeContext(ctx); err != nil {
@@ -66,14 +67,6 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) (
}
c = tlsConn
}
if err == nil && up.Transport == "grpc" {
grpcConn, grpcErr := transport.DialGRPCOverConn(ctx, c, up.Address(), up.ServiceName)
if grpcErr != nil {
c.Close()
return nil, fmt.Errorf("vmess: connect: %w", grpcErr)
}
c = grpcConn
}
default:
return nil, fmt.Errorf("vmess: unsupported transport")
}
+139
View File
@@ -0,0 +1,139 @@
package gateway
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"errors"
"net/http"
"strconv"
"strings"
"github.com/gofrs/uuid"
)
const nodeUsernamePrefix = "node-"
var gatewayBasicEncoding = base64.StdEncoding.Strict()
// Credentials derives stable node passwords in the namespace of one store.
type Credentials struct {
secret [32]byte
storePrefix string
}
// NewCredentials binds the key to the canonical UUID of the initialized store.
func NewCredentials(storeUUID string, secret [32]byte) (Credentials, error) {
id, err := uuid.FromString(storeUUID)
if err != nil || id == uuid.Nil {
return Credentials{}, errors.New("invalid gateway store UUID")
}
if secret == [32]byte{} {
return Credentials{}, errors.New("invalid gateway node secret")
}
return Credentials{secret: secret, storePrefix: "gateway/v1:" + id.String() + ":"}, nil
}
// Password returns the proxy password for a positive, stable proxy ID.
func (c Credentials) Password(id int64) string {
if id <= 0 || c.storePrefix == "" {
return ""
}
password := c.nodePassword(id)
return string(password[:])
}
func (c Credentials) nodePassword(id int64) (password [gatewaySecretEncodedLen]byte) {
var message [len("gateway/v1:") + 36 + 1 + 19]byte
var digest [sha256.Size]byte
h := hmac.New(sha256.New, c.secret[:])
_, _ = h.Write(strconv.AppendInt(append(message[:0], c.storePrefix...), id, 10))
gatewaySecretEncoding.Encode(password[:], h.Sum(digest[:0]))
return password
}
// AuthenticateProxy verifies only the credentials of this request. Node
// readiness (including expiry and removal) must be checked by the caller.
func (c Credentials) AuthenticateProxy(r *http.Request) (int64, bool) {
if c.storePrefix == "" {
return 0, false
}
encoded, ok := gatewayAuthorization(r.Header.Values("Proxy-Authorization"), "Basic")
const maxUserPassLen = len(nodeUsernamePrefix) + 19 + 1 + gatewaySecretEncodedLen
const maxBasicEncodedLen = (maxUserPassLen + 2) / 3 * 4
if !ok || len(encoded) > maxBasicEncodedLen {
return 0, false
}
var decoded [maxBasicEncodedLen / 4 * 3]byte
n, err := gatewayBasicEncoding.Decode(decoded[:], []byte(encoded))
if err != nil {
return 0, false
}
user, password, ok := bytes.Cut(decoded[:n], []byte(":"))
if !ok || len(password) != gatewaySecretEncodedLen || !bytes.HasPrefix(user, []byte(nodeUsernamePrefix)) {
return 0, false
}
decimal := user[len(nodeUsernamePrefix):]
if len(decimal) == 0 || len(decimal) > 19 || decimal[0] < '1' || decimal[0] > '9' {
return 0, false
}
for _, digit := range decimal[1:] {
if digit < '0' || digit > '9' {
return 0, false
}
}
id, err := strconv.ParseInt(string(decimal), 10, 64)
if err != nil {
return 0, false
}
expected := c.nodePassword(id)
if subtle.ConstantTimeCompare(password, expected[:]) != 1 {
return 0, false
}
return id, true
}
// RequireProxyAuth authenticates each request before passing the selected ID
// to next. It removes only the proxy header, not origin Authorization.
func (c Credentials) RequireProxyAuth(next func(http.ResponseWriter, *http.Request, int64)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id, ok := c.AuthenticateProxy(r)
if !ok {
w.Header().Set("Proxy-Authenticate", `Basic realm="http-gateway"`)
http.Error(w, "proxy authentication required", http.StatusProxyAuthRequired)
return
}
r.Header.Del("Proxy-Authorization")
next(w, r, id)
})
}
// RequireBearerAuth protects catalog endpoints and marks even auth failures
// as non-cacheable. Proxy credentials cannot authenticate to this middleware.
func RequireBearerAuth(token string, next http.Handler) http.Handler {
_, configured := decodeGatewaySecret(token)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
provided, ok := gatewayAuthorization(r.Header.Values("Authorization"), "Bearer")
if !configured || !ok || subtle.ConstantTimeCompare([]byte(provided), []byte(token)) != 1 {
w.Header().Set("WWW-Authenticate", "Bearer")
http.Error(w, "authentication required", http.StatusUnauthorized)
return
}
r.Header.Del("Authorization")
next.ServeHTTP(w, r)
})
}
func gatewayAuthorization(values []string, scheme string) (string, bool) {
if len(values) != 1 {
return "", false
}
prefix, credential, ok := strings.Cut(values[0], " ")
if !ok || len(prefix) != len(scheme) || !strings.EqualFold(prefix, scheme) || credential == "" || strings.ContainsAny(credential, " ,\t\r\n") {
return "", false
}
return credential, true
}
+213
View File
@@ -0,0 +1,213 @@
package gateway
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"math"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
const identityTestStore = "839bcbe2-348e-4d7a-8744-d0b53bd1ff81"
func identityTestCredentials(t *testing.T, store string, key [32]byte) Credentials {
t.Helper()
credentials, err := NewCredentials(store, key)
if err != nil {
t.Fatal(err)
}
return credentials
}
func identityTestBasic(user, password string) string {
return "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+password))
}
func TestGatewayNodePasswordNamespace(t *testing.T) {
key := identityTestKey(2)
credentials := identityTestCredentials(t, identityTestStore, key)
restarted := identityTestCredentials(t, strings.ToUpper(identityTestStore), key)
otherStore := identityTestCredentials(t, "88246114-2b66-46bd-913a-64c749d1437e", key)
rotated := identityTestCredentials(t, identityTestStore, identityTestKey(3))
seen := make(map[string]bool)
for _, id := range []int64{1, 42, math.MaxInt64} {
mac := hmac.New(sha256.New, key[:])
_, _ = fmt.Fprintf(mac, "gateway/v1:%s:%d", identityTestStore, id)
want := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
password := credentials.Password(id)
if password != want || password != restarted.Password(id) || seen[password] {
t.Errorf("password for node %d disagreed with the HMAC contract or was not unique and stable", id)
}
seen[password] = true
req := httptest.NewRequest(http.MethodGet, "http://origin.example/", nil)
req.Header.Set("Proxy-Authorization", identityTestBasic(fmt.Sprintf("node-%d", id), password))
if got, ok := restarted.AuthenticateProxy(req); !ok || got != id {
t.Errorf("node %d was not authenticated after reconstruction", id)
}
for _, changed := range []Credentials{otherStore, rotated} {
if got, ok := changed.AuthenticateProxy(req); ok || got != 0 {
t.Errorf("old credential for node %d survived store or key replacement", id)
}
}
}
for _, id := range []int64{0, -1, math.MinInt64} {
if credentials.Password(id) != "" {
t.Errorf("issued a password for an invalid ID: %d", id)
}
}
if _, err := NewCredentials(identityTestStore, [32]byte{}); err == nil {
t.Error("zero master key accepted")
}
for _, uuid := range []string{"", "not-a-uuid", "00000000-0000-0000-0000-000000000000"} {
if _, err := NewCredentials(uuid, key); err == nil {
t.Error("invalid or uninitialized store UUID accepted")
}
}
}
func TestGatewayProxyAuthRejectsAmbiguousCredentials(t *testing.T) {
credentials := identityTestCredentials(t, identityTestStore, identityTestKey(2))
pass := credentials.Password(42)
valid := identityTestBasic("node-42", pass)
for _, tc := range []struct {
name string
values []string
}{
{name: "missing"},
{name: "wrong password", values: []string{identityTestBasic("node-42", credentials.Password(1))}},
{name: "wrong ID", values: []string{identityTestBasic("node-43", pass)}},
{name: "duplicate", values: []string{valid, valid}},
{name: "conflicting duplicate", values: []string{valid, identityTestBasic("node-1", credentials.Password(1))}},
{name: "folded values", values: []string{valid + ", " + valid}},
{name: "wrong scheme", values: []string{"Bearer " + identityTestToken(1)}},
{name: "extra separator", values: []string{"Basic " + strings.TrimPrefix(valid, "Basic")}},
{name: "tab separator", values: []string{"Basic\t" + strings.TrimPrefix(valid, "Basic ")}},
{name: "bad base64", values: []string{"Basic invalid*base64"}},
{name: "missing padding", values: []string{"Basic " + base64.RawStdEncoding.EncodeToString([]byte("node-1:"+credentials.Password(1)))}},
{name: "missing colon", values: []string{"Basic " + base64.StdEncoding.EncodeToString([]byte("node-42"+pass))}},
{name: "multiple colons", values: []string{identityTestBasic("node-42", ":"+pass)}},
{name: "overlong value", values: []string{"Basic " + strings.Repeat("A", 512)}},
} {
t.Run(tc.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "http://origin.example/", nil)
for _, value := range tc.values {
r.Header.Add("Proxy-Authorization", value)
}
if id, ok := credentials.AuthenticateProxy(r); ok || id != 0 {
t.Error("ambiguous or invalid proxy credentials were accepted")
}
})
}
for _, user := range []string{
"Node-42", "node-", "node-0", "node-00", "node-042", "node-+42", "node--42", "node-42x", "node-42 ",
"node-42", "node-9223372036854775808", "node-18446744073709551615", "node-1000000000000000000000",
} {
t.Run(user, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "http://origin.example/", nil)
r.Header.Set("Proxy-Authorization", identityTestBasic(user, pass))
if id, ok := credentials.AuthenticateProxy(r); ok || id != 0 {
t.Error("noncanonical or overflowing node ID was accepted")
}
})
}
}
func TestGatewayCredentialMiddlewareSeparation(t *testing.T) {
credentials := identityTestCredentials(t, identityTestStore, identityTestKey(2))
token := identityTestToken(1)
password := credentials.Password(42)
basic := identityTestBasic("node-42", password)
originAuth := "Bearer origin-owned-credential"
verifyAPI := RequireBearerAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "" {
t.Error("authenticated API still held its Bearer token")
}
w.WriteHeader(http.StatusNoContent)
}))
verifyProxy := credentials.RequireProxyAuth(func(w http.ResponseWriter, r *http.Request, id int64) {
if r.Header.Get("Proxy-Authorization") != "" || r.Header.Get("Authorization") != originAuth {
t.Error("proxy did not strip only the hop's credentials")
}
fmt.Fprint(w, id)
})
for _, tc := range []struct {
name, auth, proxy, query string
extraAuth string
want int
}{
{name: "missing", want: http.StatusUnauthorized},
{name: "wrong", auth: "Bearer " + identityTestToken(2), want: http.StatusUnauthorized},
{name: "valid case-insensitive scheme", auth: "bEaReR " + token, want: http.StatusNoContent},
{name: "correct token only in query", query: "?access_token=" + token, want: http.StatusUnauthorized},
{name: "proxy header", proxy: basic, want: http.StatusUnauthorized},
{name: "basic in authorization", auth: basic, want: http.StatusUnauthorized},
{name: "duplicate bearer", auth: "Bearer " + token, extraAuth: "Bearer " + token, want: http.StatusUnauthorized},
{name: "joined bearer", auth: "Bearer " + token + ", Bearer " + token, want: http.StatusUnauthorized},
} {
t.Run("API "+tc.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/v1/proxies"+tc.query, nil)
if tc.auth != "" {
r.Header.Set("Authorization", tc.auth)
}
if tc.extraAuth != "" {
r.Header.Add("Authorization", tc.extraAuth)
}
if tc.proxy != "" {
r.Header.Set("Proxy-Authorization", tc.proxy)
}
r.Header.Set("Origin", "https://untrusted.example")
w := httptest.NewRecorder()
verifyAPI.ServeHTTP(w, r)
if w.Code != tc.want || w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("Access-Control-Allow-Origin") != "" {
t.Errorf("unexpected API status/cache/CORS policy: status %d, want %d", w.Code, tc.want)
}
if w.Code == http.StatusUnauthorized && w.Header().Get("WWW-Authenticate") != "Bearer" {
t.Error("missing Bearer challenge")
}
if strings.Contains(w.Body.String(), token) || strings.Contains(w.Body.String(), password) {
t.Error("API response leaked a fixture credential")
}
})
}
for _, tc := range []struct {
name, auth, proxy, wantBody string
want int
}{
{"authorized node", originAuth, "bAsIc " + strings.TrimPrefix(basic, "Basic "), "42", http.StatusOK},
{"missing after success", originAuth, "", "", http.StatusProxyAuthRequired},
{"different node", originAuth, identityTestBasic("node-1", credentials.Password(1)), "1", http.StatusOK},
{"node creds in wrong header", basic, "", "", http.StatusProxyAuthRequired},
{"api token", "Bearer " + token, "", "", http.StatusProxyAuthRequired},
{"api token impersonating proxy auth", originAuth, "Bearer " + token, "", http.StatusProxyAuthRequired},
{"api token as node password", originAuth, identityTestBasic("node-42", token), "", http.StatusProxyAuthRequired},
} {
t.Run("proxy "+tc.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "http://origin.example/", nil)
r.Header.Set("Authorization", tc.auth)
if tc.proxy != "" {
r.Header.Set("Proxy-Authorization", tc.proxy)
}
w := httptest.NewRecorder()
verifyProxy.ServeHTTP(w, r)
if w.Code != tc.want {
t.Errorf("proxy status = %d, want %d", w.Code, tc.want)
}
if w.Code == http.StatusProxyAuthRequired && w.Header().Get("Proxy-Authenticate") != `Basic realm="http-gateway"` {
t.Error("missing gateway Basic challenge")
}
if tc.wantBody != "" && w.Body.String() != tc.wantBody {
t.Error("proxy middleware served the wrong node ID")
}
if strings.Contains(w.Body.String(), token) || strings.Contains(w.Body.String(), password) {
t.Error("proxy response leaked a fixture credential")
}
})
}
}
+192
View File
@@ -0,0 +1,192 @@
package gateway
import (
"bufio"
"context"
"encoding/csv"
"encoding/json"
"net"
"net/http"
"net/url"
"strconv"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
)
type catalogStore interface {
GatewayCatalog(context.Context, db.GatewayCatalogFilter, time.Time) (db.GatewayCatalogResult, error)
}
type catalogHandler struct {
store catalogStore
creds Credentials
host string
port uint16
authority string
}
// NewCatalog builds RuntimeComponents.Catalog. The API runtime owns routing and
// bearer authentication; do not mount this component on an unprotected route.
func NewCatalog(store catalogStore, cfg Config, creds Credentials) http.Handler {
return &catalogHandler{
store: store,
creds: creds,
host: cfg.PublicProxyHost,
port: cfg.PublicProxyPort,
authority: net.JoinHostPort(cfg.PublicProxyHost, strconv.Itoa(int(cfg.PublicProxyPort))),
}
}
func (h *catalogHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
if !gatewayGET(w, r) {
return
}
q, ok := parseCatalogQuery(r.URL.RawQuery)
if !ok {
http.Error(w, "invalid catalog query", http.StatusBadRequest)
return
}
// The store uses the database clock and commits its read-only snapshot
// before any credential derivation or writes to the response.
out, err := h.store.GatewayCatalog(r.Context(), q.filter, time.Time{})
if err != nil {
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
return
}
switch q.format {
case catalogJSON:
h.writeJSON(w, out)
case catalogCSV:
h.writeCSV(w, out)
case catalogTXT, catalogURLs:
h.writeText(w, out.Items, q.format == catalogURLs)
}
}
func (h *catalogHandler) proxyURL(username, password string) string {
u := url.URL{Scheme: "http", Host: h.authority, User: url.UserPassword(username, password)}
return u.String()
}
type catalogJSONMetadata struct {
SessionID *int64 `json:"session_id"`
SessionFinishedAt *time.Time `json:"session_finished_at"`
AsOf time.Time `json:"as_of"`
Total int64 `json:"total"`
}
// List the public fields explicitly so additions to the store model cannot
// implicitly become part of a credential-bearing response.
type catalogJSONItem struct {
ProxyID string `json:"proxy_id"`
Host string `json:"host"`
Port uint16 `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
ProxyURL string `json:"proxy_url"`
Country string `json:"country"`
Protocol string `json:"protocol"`
ExitIP string `json:"exit_ip"`
SpeedMbps *float64 `json:"speed_mbps"`
LatencyMs int32 `json:"latency_ms"`
CheckedAt time.Time `json:"checked_at"`
}
func (h *catalogHandler) writeJSON(w http.ResponseWriter, out db.GatewayCatalogResult) {
meta := catalogJSONMetadata{SessionID: out.SessionID, AsOf: out.AsOf.UTC(), Total: out.Total}
if out.SessionFinishedAt != nil {
finished := out.SessionFinishedAt.UTC()
meta.SessionFinishedAt = &finished
}
prefix, err := json.Marshal(meta)
if err != nil {
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "application/json")
buf := bufio.NewWriter(w)
// Stream the array without making a second catalog-sized slice or buffer.
_, _ = buf.Write(prefix[:len(prefix)-1]) // omit the metadata object's closing brace
_, _ = buf.WriteString(`,"items":[`)
enc := json.NewEncoder(buf)
for i := range out.Items {
item := &out.Items[i]
if i > 0 {
if err := buf.WriteByte(','); err != nil {
return
}
}
id := strconv.FormatInt(item.ProxyID, 10)
username, password := nodeUsernamePrefix+id, h.creds.Password(item.ProxyID)
if err := enc.Encode(catalogJSONItem{
ProxyID: id, Host: h.host, Port: h.port, Username: username, Password: password,
ProxyURL: h.proxyURL(username, password), Country: item.Country, Protocol: item.Protocol,
ExitIP: item.ExitIP, SpeedMbps: item.SpeedMbps, LatencyMs: item.LatencyMs, CheckedAt: item.CheckedAt.UTC(),
}); err != nil {
// A partial success must not be mistaken for a complete export.
panic(http.ErrAbortHandler)
}
}
_, _ = buf.WriteString("]}\n")
_ = buf.Flush()
}
func (h *catalogHandler) writeCSV(w http.ResponseWriter, out db.GatewayCatalogResult) {
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
writer := csv.NewWriter(w)
if err := writer.Write([]string{
"proxy_id", "host", "port", "username", "password", "proxy_url", "country", "protocol",
"exit_ip", "speed_mbps", "latency_ms", "checked_at", "session_finished_at",
}); err != nil {
return
}
finished := ""
if out.SessionFinishedAt != nil {
finished = out.SessionFinishedAt.UTC().Format(time.RFC3339Nano)
}
port := strconv.Itoa(int(h.port))
var record [13]string
for i := range out.Items {
item := &out.Items[i]
id := strconv.FormatInt(item.ProxyID, 10)
username, password := nodeUsernamePrefix+id, h.creds.Password(item.ProxyID)
speed := ""
if item.SpeedMbps != nil {
speed = strconv.FormatFloat(*item.SpeedMbps, 'g', -1, 64)
}
record = [13]string{id, h.host, port, username, password, h.proxyURL(username, password),
item.Country, item.Protocol, item.ExitIP, speed, strconv.FormatInt(int64(item.LatencyMs), 10),
item.CheckedAt.UTC().Format(time.RFC3339Nano), finished}
if err := writer.Write(record[:]); err != nil {
return
}
}
writer.Flush()
}
func (h *catalogHandler) writeText(w http.ResponseWriter, items []db.GatewayCatalogItem, asURL bool) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
if len(items) == 0 {
return
}
buf := bufio.NewWriter(w)
for i := range items {
id := items[i].ProxyID
username, password := nodeUsernamePrefix+strconv.FormatInt(id, 10), h.creds.Password(id)
if asURL {
_, _ = buf.WriteString(h.proxyURL(username, password))
} else {
_, _ = buf.WriteString(h.authority)
_ = buf.WriteByte(':')
_, _ = buf.WriteString(username)
_ = buf.WriteByte(':')
_, _ = buf.WriteString(password)
}
if err := buf.WriteByte('\n'); err != nil {
return
}
}
_ = buf.Flush()
}
+383
View File
@@ -0,0 +1,383 @@
package gateway
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/csv"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"slices"
"strconv"
"strings"
"testing"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
)
type catalogTestStoreFunc func(context.Context, db.GatewayCatalogFilter, time.Time) (db.GatewayCatalogResult, error)
func (f catalogTestStoreFunc) GatewayCatalog(ctx context.Context, filter db.GatewayCatalogFilter, at time.Time) (db.GatewayCatalogResult, error) {
return f(ctx, filter, at)
}
const catalogTestStoreUUID = "4a19d06c-04dc-4784-973a-f6ef9b2cc548"
func catalogTestConfig(host string) Config {
return Config{
PublicProxyHost: host,
PublicProxyPort: 18081,
APIToken: base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{54}, 32)),
NodeSecret: [32]byte{1, 2, 3, 4, 5},
DBDSN: "postgres://do-not-export-database-credentials@db.invalid/test",
}
}
func catalogTestHandler(t *testing.T, cfg Config, store catalogTestStoreFunc) http.Handler {
t.Helper()
creds, err := NewCredentials(catalogTestStoreUUID, cfg.NodeSecret)
if err != nil {
t.Fatal("could not construct test credentials")
}
return RequireBearerAuth(cfg.APIToken, NewCatalog(store, cfg, creds))
}
func catalogTestRequest(h http.Handler, method, query, bearer string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, "/v1/proxies", nil)
r.Host = "ignore-client.example"
r.URL.RawQuery = query
if bearer != "" {
r.Header.Set("Authorization", "Bearer "+bearer)
}
r.Header.Set("X-Forwarded-Host", "ignore-forwarded.example:9999")
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
func assertCatalogResponse(t *testing.T, w *httptest.ResponseRecorder, status int, contentType string) {
t.Helper()
if w.Code != status || w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("Access-Control-Allow-Origin") != "" {
t.Fatalf("unexpected status or cache/CORS headers (status %d, want %d)", w.Code, status)
}
if got := w.Header().Get("Content-Type"); got != contentType {
t.Fatalf("Content-Type = %q, want %q", got, contentType)
}
}
func assertCatalogPrivateFieldsAbsent(t *testing.T, w *httptest.ResponseRecorder, cfg Config) {
t.Helper()
for _, forbidden := range []string{
cfg.APIToken, base64.RawURLEncoding.EncodeToString(cfg.NodeSecret[:]), cfg.DBDSN,
catalogTestStoreUUID, "canonical_url", "store_uuid", "source_url", "subscription_token",
"vless://", "provider-credential", "ignore-client.example", "ignore-forwarded.example",
} {
if bytes.Contains(w.Body.Bytes(), []byte(forbidden)) {
t.Fatal("catalog response exposed private or request-derived data")
}
for _, values := range w.Header() {
for _, value := range values {
if strings.Contains(value, forbidden) {
t.Fatal("catalog response header exposed private or request-derived data")
}
}
}
}
}
var catalogTestFormats = [...]struct{ name, contentType string }{
{"json", "application/json"},
{"csv", "text/csv; charset=utf-8"},
{"txt", "text/plain; charset=utf-8"},
{"proxy-url-list-txt", "text/plain; charset=utf-8"},
}
func TestGatewayCatalogExports(t *testing.T) {
zone := time.FixedZone("fixture", 2*60*60)
finished := time.Date(2026, 1, 2, 3, 4, 5, 0, zone)
checked := finished.Add(time.Minute + 123456*time.Microsecond)
asOf := finished.Add(2 * time.Minute)
sessionID, speed := int64(73), 5.5
const largeID = int64(9007199254740993) // not exactly representable as a JavaScript number
out := db.GatewayCatalogResult{
SessionID: &sessionID, SessionFinishedAt: &finished, AsOf: asOf, Total: 7,
Items: []db.GatewayCatalogItem{
{ProxyID: largeID, Country: "XX", Protocol: "ss", ExitIP: "2001:db8::1", LatencyMs: 0, CheckedAt: checked},
{ProxyID: 42, Country: "DE", Protocol: "vless", ExitIP: "192.0.2.1", SpeedMbps: &speed, LatencyMs: 19, CheckedAt: checked},
},
}
store := catalogTestStoreFunc(func(ctx context.Context, f db.GatewayCatalogFilter, at time.Time) (db.GatewayCatalogResult, error) {
if ctx.Err() != nil || !at.IsZero() || !slices.Equal(f.Countries, []string{"DE", "XX", "NL"}) ||
!slices.Equal(f.Protocols, []string{"ss", "vless"}) || f.Sort != db.GatewaySortLatency ||
f.MaxLatencyMs == nil || *f.MaxLatencyMs != 19 || f.MinSpeedMbps != nil || f.Limit == nil || *f.Limit != 2 || f.Offset != 1 {
return db.GatewayCatalogResult{}, errors.New("incorrect filter or request time")
}
return out, nil
})
for _, address := range []struct{ host, authority string }{
{"127.0.0.1", "127.0.0.1:18081"},
{"gateway.test", "gateway.test:18081"},
{"2001:db8::42", "[2001:db8::42]:18081"},
} {
t.Run(address.host, func(t *testing.T) {
cfg := catalogTestConfig(address.host)
h := catalogTestHandler(t, cfg, store)
for _, format := range catalogTestFormats {
t.Run(format.name, func(t *testing.T) {
t.Parallel() // same handler and result, concurrent encoders
w := catalogTestRequest(h, http.MethodGet, "country=DE,XX&country=NL&protocol=ss&protocol=vless&sort=latency&max_latency_ms=19&limit=2&offset=1&format="+format.name, cfg.APIToken)
assertCatalogResponse(t, w, http.StatusOK, format.contentType)
assertCatalogPrivateFieldsAbsent(t, w, cfg)
switch format.name {
case "json":
assertCatalogJSON(t, w.Body, cfg, address.authority)
case "csv":
assertCatalogCSV(t, w.Body.Bytes(), cfg, address.authority)
default:
assertCatalogText(t, w.Body.String(), cfg, address.authority, format.name == "proxy-url-list-txt")
}
})
}
})
}
}
func catalogExpectedPassword(cfg Config, id string) string {
mac := hmac.New(sha256.New, cfg.NodeSecret[:])
_, _ = io.WriteString(mac, "gateway/v1:"+catalogTestStoreUUID+":"+id)
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}
func assertCatalogProxyURL(t *testing.T, rawURL, authority, username, password string) {
t.Helper()
u, err := url.Parse(rawURL)
if err != nil || u.Scheme != "http" || u.Host != authority || u.Path != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" || u.User == nil {
t.Fatal("catalog did not return a parsed HTTP gateway URL for the configured authority")
}
gotPassword, ok := u.User.Password()
if !ok || u.User.Username() != username || gotPassword != password {
t.Fatal("catalog URL did not carry the matching derived node credentials")
}
}
func assertCatalogJSON(t *testing.T, body io.Reader, cfg Config, authority string) {
t.Helper()
var doc struct {
SessionID int64 `json:"session_id"`
SessionFinishedAt string `json:"session_finished_at"`
AsOf string `json:"as_of"`
Total int64 `json:"total"`
Items []struct {
ID string `json:"proxy_id"`
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
ProxyURL string `json:"proxy_url"`
Country string `json:"country"`
Protocol string `json:"protocol"`
ExitIP string `json:"exit_ip"`
Speed json.RawMessage `json:"speed_mbps"`
Latency *int `json:"latency_ms"`
CheckedAt string `json:"checked_at"`
} `json:"items"`
}
dec := json.NewDecoder(body)
dec.DisallowUnknownFields()
if err := dec.Decode(&doc); err != nil {
t.Fatal("catalog response did not decode as the client JSON schema")
}
if err := dec.Decode(new(any)); err != io.EOF {
t.Fatal("JSON catalog has trailing data")
}
if doc.SessionID != 73 || doc.SessionFinishedAt != "2026-01-02T01:04:05Z" || doc.AsOf != "2026-01-02T01:06:05Z" || doc.Total != 7 || len(doc.Items) != 2 {
t.Fatal("catalog JSON did not preserve snapshot metadata and pre-pagination total")
}
for i, want := range []struct {
id, country, protocol, exitIP, speed string
latency int
}{
{"9007199254740993", "XX", "ss", "2001:db8::1", "null", 0},
{"42", "DE", "vless", "192.0.2.1", "5.5", 19},
} {
item := doc.Items[i]
if item.ID != want.id || item.Host != cfg.PublicProxyHost || item.Port != int(cfg.PublicProxyPort) ||
item.Country != want.country || item.Protocol != want.protocol || item.ExitIP != want.exitIP ||
string(item.Speed) != want.speed || item.Latency == nil || *item.Latency != want.latency || item.CheckedAt != "2026-01-02T01:05:05.123456Z" {
t.Fatalf("JSON row %d did not preserve the selected item and metric fields", i)
}
username, password := "node-"+want.id, catalogExpectedPassword(cfg, want.id)
if item.Username != username || item.Password != password {
t.Fatalf("JSON row %d did not carry the derived node credentials", i)
}
assertCatalogProxyURL(t, item.ProxyURL, authority, username, password)
}
}
func catalogCSVHeader() []string {
return []string{"proxy_id", "host", "port", "username", "password", "proxy_url", "country", "protocol",
"exit_ip", "speed_mbps", "latency_ms", "checked_at", "session_finished_at"}
}
func readCatalogCSV(t *testing.T, body []byte) [][]string {
t.Helper()
if bytes.HasPrefix(body, []byte{0xef, 0xbb, 0xbf}) {
t.Fatal("unexpected UTF-8 BOM")
}
rows, err := csv.NewReader(bytes.NewReader(body)).ReadAll()
if err != nil || len(rows) == 0 || !slices.Equal(rows[0], catalogCSVHeader()) {
t.Fatal("CSV catalog did not parse with the public column order")
}
return rows[1:]
}
func assertCatalogCSV(t *testing.T, body []byte, cfg Config, authority string) {
t.Helper()
rows := readCatalogCSV(t, body)
if len(rows) != 2 {
t.Fatal("CSV did not contain exactly the selected page")
}
for i, want := range []struct{ id, country, protocol, exitIP, speed, latency string }{
{"9007199254740993", "XX", "ss", "2001:db8::1", "", "0"},
{"42", "DE", "vless", "192.0.2.1", "5.5", "19"},
} {
row := rows[i]
username, password := "node-"+want.id, catalogExpectedPassword(cfg, want.id)
if row[0] != want.id || row[1] != cfg.PublicProxyHost || row[2] != strconv.Itoa(int(cfg.PublicProxyPort)) ||
row[3] != username || row[4] != password || !slices.Equal(row[6:], []string{
want.country, want.protocol, want.exitIP, want.speed, want.latency, "2026-01-02T01:05:05.123456Z", "2026-01-02T01:04:05Z",
}) {
t.Fatalf("CSV row %d did not preserve credential, metric or timestamp fields", i)
}
assertCatalogProxyURL(t, row[5], authority, username, password)
}
}
func assertCatalogText(t *testing.T, body string, cfg Config, authority string, asURL bool) {
t.Helper()
lines := strings.Split(body, "\n")
if len(lines) != 3 || lines[2] != "" {
t.Fatal("TXT catalog did not end both records with LF")
}
for i, id := range []string{"9007199254740993", "42"} {
username, password := "node-"+id, catalogExpectedPassword(cfg, id)
if asURL {
assertCatalogProxyURL(t, lines[i], authority, username, password)
continue
}
last := strings.LastIndexByte(lines[i], ':')
if last == -1 {
t.Fatal("TXT record is missing password delimiter")
}
hostUser, gotPassword := lines[i][:last], lines[i][last+1:]
last = strings.LastIndexByte(hostUser, ':')
if last == -1 {
t.Fatal("TXT record is missing username delimiter")
}
gotAuthority, gotUsername := hostUser[:last], hostUser[last+1:]
host, port, err := net.SplitHostPort(gotAuthority)
if err != nil || gotAuthority != authority || host != cfg.PublicProxyHost || port != strconv.Itoa(int(cfg.PublicProxyPort)) || gotUsername != username || gotPassword != password {
t.Fatalf("TXT row %d did not parse as the configured authority and derived credentials", i)
}
}
}
func TestGatewayCatalogEmptyAndUnavailable(t *testing.T) {
asOf := time.Date(2026, 1, 2, 1, 6, 5, 0, time.UTC)
session := int64(73)
cfg := catalogTestConfig("gateway.test")
for _, tc := range []struct {
name string
out db.GatewayCatalogResult
err error
}{
{"before publication", db.GatewayCatalogResult{AsOf: asOf}, nil},
{"empty publication", db.GatewayCatalogResult{SessionID: &session, SessionFinishedAt: &asOf, AsOf: asOf}, nil},
{"offset beyond end", db.GatewayCatalogResult{SessionID: &session, SessionFinishedAt: &asOf, AsOf: asOf, Total: 4}, nil},
{"database failure", db.GatewayCatalogResult{AsOf: asOf, Items: []db.GatewayCatalogItem{{ProxyID: 42}}}, errors.New("provider-credential for vless://private cannot be read")},
} {
t.Run(tc.name, func(t *testing.T) {
h := catalogTestHandler(t, cfg, func(_ context.Context, f db.GatewayCatalogFilter, _ time.Time) (db.GatewayCatalogResult, error) {
if f.Offset != 9223372036854775807 || f.Limit != nil || f.Sort != db.GatewaySortID {
return db.GatewayCatalogResult{}, errors.New("did not preserve offset without a limit")
}
return tc.out, tc.err
})
for _, format := range catalogTestFormats {
t.Run(format.name, func(t *testing.T) {
w := catalogTestRequest(h, http.MethodGet, "offset=9223372036854775807&format="+format.name, cfg.APIToken)
assertCatalogPrivateFieldsAbsent(t, w, cfg)
if tc.err != nil {
assertCatalogResponse(t, w, http.StatusServiceUnavailable, "text/plain; charset=utf-8")
if w.Body.String() != "gateway unavailable\n" {
t.Fatal("catalog exposed data or unsanitized error on storage failure")
}
return
}
assertCatalogResponse(t, w, http.StatusOK, format.contentType)
switch format.name {
case "json":
var doc map[string]json.RawMessage
if err := json.Unmarshal(w.Body.Bytes(), &doc); err != nil || len(doc) != 5 || string(doc["items"]) != "[]" || string(doc["total"]) != strconv.FormatInt(tc.out.Total, 10) || string(doc["as_of"]) != `"2026-01-02T01:06:05Z"` {
t.Fatal("empty JSON catalog lost metadata, total or the empty items array")
}
wantID, wantFinished := "null", "null"
if tc.out.SessionID != nil {
wantID, wantFinished = "73", `"2026-01-02T01:06:05Z"`
}
if string(doc["session_id"]) != wantID || string(doc["session_finished_at"]) != wantFinished {
t.Fatal("JSON lost the distinction between no snapshot and an empty snapshot")
}
case "csv":
if len(readCatalogCSV(t, w.Body.Bytes())) != 0 {
t.Fatal("empty CSV must have only the header")
}
default:
if w.Body.Len() != 0 {
t.Fatal("empty TXT must have a zero-length body")
}
}
})
}
})
}
}
func TestGatewayCatalogRejectsRequestBeforeReadingStore(t *testing.T) {
cfg := catalogTestConfig("gateway.test")
h := catalogTestHandler(t, cfg, func(context.Context, db.GatewayCatalogFilter, time.Time) (db.GatewayCatalogResult, error) {
t.Fatal("rejected catalog request reached storage")
return db.GatewayCatalogResult{}, nil
})
for _, tc := range []struct {
method, query, bearer, body string
status int
}{
{http.MethodGet, "format=csv", "", "authentication required\n", http.StatusUnauthorized},
{http.MethodGet, "format=csv", "invalid", "authentication required\n", http.StatusUnauthorized},
{http.MethodPost, "format=txt", cfg.APIToken, "method not allowed\n", http.StatusMethodNotAllowed},
{http.MethodGet, "format=txt&limit=1&l%69mit=2", cfg.APIToken, "invalid catalog query\n", http.StatusBadRequest},
{http.MethodGet, "format=csv&country=%zz", cfg.APIToken, "invalid catalog query\n", http.StatusBadRequest},
{http.MethodGet, "limit=9223372036854775808", cfg.APIToken, "invalid catalog query\n", http.StatusBadRequest},
{http.MethodGet, "format=proxy-url-list-txt&token=" + cfg.APIToken, cfg.APIToken, "invalid catalog query\n", http.StatusBadRequest},
{http.MethodGet, "sort=latency%3B+SELECT+provider-credential", cfg.APIToken, "invalid catalog query\n", http.StatusBadRequest},
} {
w := catalogTestRequest(h, tc.method, tc.query, tc.bearer)
assertCatalogResponse(t, w, tc.status, "text/plain; charset=utf-8")
assertCatalogPrivateFieldsAbsent(t, w, cfg)
if w.Body.String() != tc.body {
t.Fatal("catalog error is not the expected sanitized message")
}
if tc.status == http.StatusMethodNotAllowed && w.Header().Get("Allow") != http.MethodGet {
t.Fatal("catalog did not advertise its allowed method")
}
}
}
+243
View File
@@ -0,0 +1,243 @@
package gateway
import (
"encoding/base64"
"errors"
"net"
"net/netip"
"net/url"
"os"
"strconv"
"strings"
"git.eeee.moe/omar/zhguchiy_perchik/internal/netpolicy"
"github.com/jackc/pgx/v5/pgxpool"
)
// Config is the validated, operator-supplied process configuration.
type Config struct {
DBDSN string
PublicProxyHost string
PublicProxyPort uint16
APIToken string
NodeSecret [32]byte
ProbeURL *url.URL
AllowedDestinations map[string]struct{} // normalized DNS name and port
UpstreamNetworks []netip.Prefix // operator-owned underlay enrollment
}
// LoadConfig parses the environment without printing any configured values.
func LoadConfig() (Config, error) {
return parseGatewayConfig(os.Getenv)
}
func parseGatewayConfig(getenv func(string) string) (Config, error) {
var cfg Config
cfg.DBDSN = getenv("GATEWAY_DB_DSN")
if strings.TrimSpace(cfg.DBDSN) == "" {
return Config{}, errors.New("GATEWAY_DB_DSN is required")
}
if _, err := pgxpool.ParseConfig(cfg.DBDSN); err != nil {
return Config{}, errors.New("GATEWAY_DB_DSN must be a valid PostgreSQL connection string")
}
var ok bool
cfg.PublicProxyHost, cfg.PublicProxyPort, ok = parseGatewayPublicAddress(getenv("GATEWAY_PUBLIC_PROXY_ADDR"))
if !ok {
return Config{}, errors.New("GATEWAY_PUBLIC_PROXY_ADDR must be a reachable host:port (bracket IPv6)")
}
cfg.APIToken = getenv("GATEWAY_API_TOKEN")
apiKey, ok := decodeGatewaySecret(cfg.APIToken)
if !ok {
return Config{}, errors.New("GATEWAY_API_TOKEN must be 32 random bytes encoded as unpadded base64url")
}
cfg.NodeSecret, ok = decodeGatewaySecret(getenv("GATEWAY_NODE_SECRET"))
if !ok {
return Config{}, errors.New("GATEWAY_NODE_SECRET must be 32 random bytes encoded as unpadded base64url")
}
if apiKey == cfg.NodeSecret {
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 list unique 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 _, 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)")
}
return cfg, nil
}
const gatewaySecretEncodedLen = 43 // raw base64 encoding of exactly 32 bytes
var gatewaySecretEncoding = base64.RawURLEncoding.Strict()
func decodeGatewaySecret(encoded string) ([32]byte, bool) {
var key [32]byte
if len(encoded) != gatewaySecretEncodedLen {
return key, false
}
n, err := gatewaySecretEncoding.Decode(key[:], []byte(encoded))
return key, err == nil && n == len(key) && key != [32]byte{}
}
func parseGatewayPublicAddress(raw string) (string, uint16, bool) {
host, port, err := net.SplitHostPort(raw)
if err != nil {
return "", 0, false
}
n, ok := parseGatewayPort(port)
if !ok {
return "", 0, false
}
bracketed := strings.HasPrefix(raw, "[")
if ip, err := netip.ParseAddr(host); err == nil {
if bracketed != ip.Is6() || ip.Zone() != "" || ip.Is4In6() || ip.IsUnspecified() || ip.IsMulticast() || ip == netip.AddrFrom4([4]byte{255, 255, 255, 255}) {
return "", 0, false
}
return ip.String(), n, true
}
if bracketed {
return "", 0, false
}
host, ok = normalizeGatewayDNSName(host)
if !ok {
return "", 0, false
}
return host, n, true
}
func parseGatewayPort(raw string) (uint16, bool) {
if len(raw) == 0 || len(raw) > 5 {
return 0, false
}
for i := range len(raw) {
if raw[i] < '0' || raw[i] > '9' {
return 0, false
}
}
port, err := strconv.ParseUint(raw, 10, 16)
return uint16(port), err == nil && port != 0
}
func normalizeGatewayDNSName(host string) (string, bool) {
host = strings.TrimSuffix(host, ".")
if len(host) == 0 || len(host) > 253 {
return "", false
}
allNumeric := true
for label := range strings.SplitSeq(host, ".") {
if len(label) == 0 || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
return "", false
}
for i := range len(label) {
c := label[i]
switch {
case c >= '0' && c <= '9':
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c == '-':
allNumeric = false
default:
return "", false
}
}
}
// Avoid accepting malformed or alternate numeric IP spellings as DNS names.
if allNumeric {
return "", false
}
return strings.ToLower(host), true
}
func parseGatewayDestinations(raw string) (map[string]struct{}, bool) {
allowed := make(map[string]struct{})
for entry := range strings.SplitSeq(raw, ",") {
host, port, err := net.SplitHostPort(strings.TrimSpace(entry))
if err != nil || strings.HasPrefix(strings.TrimSpace(entry), "[") {
return nil, false
}
host, ok := normalizeGatewayDNSName(host)
if !ok {
return nil, false
}
n, ok := parseGatewayPort(port)
if !ok {
return nil, false
}
authority := net.JoinHostPort(host, strconv.Itoa(int(n)))
if _, exists := allowed[authority]; exists {
return nil, false
}
allowed[authority] = struct{}{}
}
return allowed, true
}
func parseGatewayProbeURL(raw string) (*url.URL, bool) {
if strings.ContainsAny(raw, "?#\\") || strings.IndexFunc(raw, func(r rune) bool { return r <= ' ' || r == 127 }) >= 0 {
return nil, false
}
u, err := url.Parse(raw)
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || strings.HasPrefix(u.Host, "[") {
return nil, false
}
host, ok := normalizeGatewayDNSName(u.Hostname())
if !ok {
return nil, false
}
port := u.Port()
if port == "" && !strings.Contains(u.Host, ":") {
port = "443"
}
n, ok := parseGatewayPort(port)
if !ok {
return nil, false
}
u.Host = net.JoinHostPort(host, strconv.Itoa(int(n)))
return u, true
}
const maxGatewayUpstreamNetworks = 32
func parseGatewayUpstreamNetworks(raw string) ([]netip.Prefix, bool) {
count := strings.Count(raw, ",") + 1
if count > maxGatewayUpstreamNetworks {
return nil, false
}
prefixes := make([]netip.Prefix, 0, count)
for entry := range strings.SplitSeq(raw, ",") {
entry = strings.TrimSpace(entry)
prefix, err := netip.ParsePrefix(entry)
if err != nil {
ip, err := netip.ParseAddr(entry)
if err != nil || ip.Zone() != "" {
return nil, false
}
prefix = netip.PrefixFrom(ip, ip.BitLen())
}
minBits := 24
if prefix.Addr().Is6() {
minBits = 64
}
if prefix.Bits() < minBits || !netpolicy.IsPublicPrefix(prefix) {
return nil, false
}
for _, existing := range prefixes {
if existing == prefix {
return nil, false
}
}
prefixes = append(prefixes, prefix)
}
return prefixes, true
}
+220
View File
@@ -0,0 +1,220 @@
package gateway
import (
"encoding/base64"
"fmt"
"net"
"net/netip"
"reflect"
"strconv"
"strings"
"testing"
)
func identityTestKey(first byte) [32]byte { return [32]byte{first, 2, 3, 4} }
func identityTestToken(first byte) string {
key := identityTestKey(first)
return base64.RawURLEncoding.EncodeToString(key[:])
}
func identityTestEnv() map[string]string {
return map[string]string{
"GATEWAY_DB_DSN": "postgres://gateway:test-only@localhost/gateway",
"GATEWAY_PUBLIC_PROXY_ADDR": "[FD12:3456:0000::9]:8081",
"GATEWAY_API_TOKEN": identityTestToken(1),
"GATEWAY_NODE_SECRET": identityTestToken(2),
"GATEWAY_PROBE_URL": "https://Probe.Example./checks/live%20ok",
"GATEWAY_ALLOWED_DESTINATIONS": "origin.example:80, PROBE.EXAMPLE.:443, origin.example:8443",
"GATEWAY_UPSTREAM_NETWORKS": "1.1.1.0/24, 8.8.8.8, 2606:4700::/64",
}
}
func TestGatewayLaunchConfig(t *testing.T) {
env := identityTestEnv()
cfg, err := parseGatewayConfig(func(k string) string { return env[k] })
if err != nil {
t.Fatal(err)
}
if cfg.PublicProxyHost != "fd12:3456::9" || cfg.PublicProxyPort != 8081 || cfg.DBDSN != env["GATEWAY_DB_DSN"] {
t.Fatal("validated process endpoints did not match configuration")
}
if cfg.APIToken != identityTestToken(1) || cfg.NodeSecret != identityTestKey(2) {
t.Fatal("API and node keys did not retain their independent values")
}
if cfg.ProbeURL.String() != "https://probe.example:443/checks/live%20ok" {
t.Fatal("probe URL was not normalized without changing its path")
}
wantDestinations := map[string]struct{}{"origin.example:80": {}, "origin.example:8443": {}, "probe.example:443": {}}
if !reflect.DeepEqual(cfg.AllowedDestinations, wantDestinations) {
t.Errorf("destination allowlist = %v, want %v", cfg.AllowedDestinations, wantDestinations)
}
wantNetworks := []netip.Prefix{netip.MustParsePrefix("1.1.1.0/24"), netip.MustParsePrefix("8.8.8.8/32"), netip.MustParsePrefix("2606:4700::/64")}
if !reflect.DeepEqual(cfg.UpstreamNetworks, wantNetworks) {
t.Errorf("enrolled networks = %v, want %v", cfg.UpstreamNetworks, wantNetworks)
}
for key := range env {
t.Run("missing "+key, func(t *testing.T) {
got, err := parseGatewayConfig(func(k string) string {
if k == key {
return ""
}
return env[k]
})
if err == nil || !strings.Contains(err.Error(), key) || !reflect.DeepEqual(got, Config{}) {
t.Errorf("did not reject missing %s with a zero config and actionable error", key)
}
})
}
}
func TestGatewayLaunchConfigRejectsInvalidPolicyAndRedactsValues(t *testing.T) {
for _, tc := range []struct {
name, key, value string
}{
{"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"},
{"shared secrets", "GATEWAY_NODE_SECRET", identityTestToken(1)},
{"probe port not enrolled", "GATEWAY_PROBE_URL", "https://probe.example:444/check"},
{"probe host not enrolled", "GATEWAY_PROBE_URL", "https://other.example/check"},
{"probe userinfo", "GATEWAY_PROBE_URL", "https://user:sensitive-probe-marker@probe.example/check"},
{"destination wildcard", "GATEWAY_ALLOWED_DESTINATIONS", "*.example:443"},
{"broad upstream", "GATEWAY_UPSTREAM_NETWORKS", "1.1.0.0/16"},
} {
t.Run(tc.name, func(t *testing.T) {
env := identityTestEnv()
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 sanitized %s error and no partially configured service", tc.key)
} else if strings.Contains(err.Error(), tc.value) || strings.Contains(err.Error(), "sensitive-") {
t.Error("configuration error included rejected input")
}
})
}
}
func TestGatewaySecretEncoding(t *testing.T) {
valid := identityTestToken(1)
if got, ok := decodeGatewaySecret(valid); !ok || got != identityTestKey(1) {
t.Fatal("valid raw base64url key rejected")
}
for _, tc := range []struct{ name, encoded string }{
{"empty", ""},
{"short", valid[:len(valid)-1]},
{"long", valid + "A"},
{"padding", valid + "="},
{"whitespace", valid[:len(valid)-1] + "\n"},
{"noncanonical trailing bits", valid[:len(valid)-1] + "B"},
{"standard alphabet", "+" + valid[1:]},
{"all zero", strings.Repeat("A", 43)},
} {
t.Run(tc.name, func(t *testing.T) {
if _, ok := decodeGatewaySecret(tc.encoded); ok {
t.Error("invalid key encoding accepted")
}
})
}
}
func TestGatewayPublicProxyAddress(t *testing.T) {
for _, tc := range []struct {
raw, host string
port uint16
}{
{"vpn.Example.:8081", "vpn.example", 8081},
{"127.0.0.1:1", "127.0.0.1", 1},
{"192.168.10.1:65535", "192.168.10.1", 65535},
{"[2001:0DB8::123]:443", "2001:db8::123", 443},
{raw: ""}, {raw: "vpn.example"}, {raw: ":8081"}, {raw: "vpn.example:"},
{raw: "http://vpn.example:8081"}, {raw: "user@vpn.example:8081"},
{raw: "vpn.example:8081/proxy"}, {raw: "vpn.example:8081?key=value"},
{raw: "vpn.example:8081#section"}, {raw: " vpn.example:8081"},
{raw: "vpn.example:0"}, {raw: "vpn.example:65536"}, {raw: "vpn.example:+80"},
{raw: "2001:db8::123:443"}, {raw: "[vpn.example]:8081"}, {raw: "[127.0.0.1]:80"},
{raw: "[::ffff:8.8.8.8]:443"}, {raw: "[fe80::1%eth0]:8081"},
{raw: "0.0.0.0:8081"}, {raw: "[::]:8081"}, {raw: "255.255.255.255:8081"},
{raw: "[ff02::1]:8081"}, {raw: "127.01.0.1:8081"}, {raw: "2130706433:8081"},
{raw: "bad..example:80"}, {raw: "-bad.example:80"}, {raw: "bad-.example:80"},
{raw: strings.Repeat("a", 64) + ".example:80"},
} {
t.Run(tc.raw, func(t *testing.T) {
host, port, ok := parseGatewayPublicAddress(tc.raw)
if host != tc.host || port != tc.port || ok != (tc.host != "") {
t.Errorf("address parsed as (%q, %d, %t), want (%q, %d, %t)", host, port, ok, tc.host, tc.port, tc.host != "")
}
})
}
}
func TestGatewayDestinationAndProbePolicy(t *testing.T) {
for _, candidate := range []string{
"", "probe.example", "probe.example:0", "probe.example:65536", "*.example:443",
"https://probe.example:443", "probe.example:443/path", "user@probe.example:443",
"1.1.1.1:443", "[2606:4700::1]:443", "[probe.example]:443", "probe_example:443",
"probe.example:443, PROBE.EXAMPLE.:00443", "probe.example:443,", ",probe.example:443",
} {
if _, ok := parseGatewayDestinations(candidate); ok {
t.Errorf("destination policy accepted %q", candidate)
}
}
probe, ok := parseGatewayProbeURL("https://PROBE.example.:8443/control")
if !ok || probe.String() != "https://probe.example:8443/control" {
t.Error("probe parser failed to normalize an allowed explicit port")
}
for _, candidate := range []string{
"", "http://probe.example/check", "https:probe.example/check", "//probe.example/check",
"https://@probe.example/check", "https://user:secret@probe.example/check",
"https://probe.example/check?", "https://probe.example/check?key=value",
"https://probe.example/check#", "https://probe.example/check#section",
"https://probe.example:/check", "https://probe.example:65536/check",
"https://probe.example\\/check", "https://probe.example/check path", "https://probe.example/check\n",
"https://1.1.1.1/check", "https://[2606:4700::1]/check",
} {
if _, ok := parseGatewayProbeURL(candidate); ok {
t.Errorf("invalid HTTPS probe URL accepted: %q", candidate)
}
}
}
func TestGatewayUpstreamEnrollmentBounds(t *testing.T) {
addresses := make([]string, 33)
for i := range addresses {
addresses[i] = fmt.Sprintf("8.8.4.%d", i)
}
if got, ok := parseGatewayUpstreamNetworks(strings.Join(addresses[:32], ",")); !ok || len(got) != 32 {
t.Error("configuration rejected exactly 32 distinct public addresses")
}
for _, candidate := range []string{
"", strings.Join(addresses, ","), "example.org", "8.8.8.8:443", "8.8.8.8,",
"8.8.8.8,8.8.8.8/32", "8.8.8.8/24", "8.8.8.0/23", "0.0.0.0/0",
"2606:4700::/63", "2606:4700::1/64", "2606:4700::1%eth0", "::/0",
"127.0.0.1", "10.1.2.0/24", "169.254.1.0/24", "192.0.2.0/24", "2001:db8::/64",
"::ffff:8.8.8.8/128", "64:ff9b::808:808", "ff02::/64", "1.1.1.1, fd00::1",
} {
if _, ok := parseGatewayUpstreamNetworks(candidate); ok {
t.Errorf("upstream enrollment accepted %q", candidate)
}
}
}
func FuzzGatewayPublicProxyAddress(f *testing.F) {
for _, seed := range []string{"vpn.example.:8081", "127.0.0.1:65535", "[fd00::1]:8081", "[::ffff:127.0.0.1]:80", "https://user@vpn.example:443/path", "a..b:5", "host:0"} {
f.Add(seed)
}
f.Fuzz(func(t *testing.T, raw string) {
host, port, ok := parseGatewayPublicAddress(raw)
if !ok {
return
}
if host == "" || port == 0 || strings.ContainsAny(host, "% /?#@[]\\\t\r\n") {
t.Fatal("accepted an unsafe host or empty port")
}
canonical := net.JoinHostPort(host, strconv.Itoa(int(port)))
if h, p, ok := parseGatewayPublicAddress(canonical); !ok || h != host || p != port {
t.Fatal("accepted authority does not round-trip canonically")
}
})
}
+128
View File
@@ -0,0 +1,128 @@
package gateway
import (
"net/url"
"strconv"
"strings"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
)
type catalogFormat string
const (
catalogJSON catalogFormat = "json"
catalogCSV catalogFormat = "csv"
catalogTXT catalogFormat = "txt"
catalogURLs catalogFormat = "proxy-url-list-txt"
)
type catalogQuery struct {
filter db.GatewayCatalogFilter
format catalogFormat
}
func parseCatalogQuery(raw string) (catalogQuery, bool) {
params, err := url.ParseQuery(raw)
if err != nil {
// ParseQuery may return a partial map with an error. Never apply it.
return catalogQuery{}, false
}
q := catalogQuery{format: catalogJSON, filter: db.GatewayCatalogFilter{Sort: db.GatewaySortID}}
for key, values := range params {
switch key {
case "country", "protocol":
for _, value := range values {
for item := range strings.SplitSeq(value, ",") {
if key == "country" {
if len(item) != 2 || item[0] < 'A' || item[0] > 'Z' || item[1] < 'A' || item[1] > 'Z' {
return catalogQuery{}, false
}
q.filter.Countries = append(q.filter.Countries, item)
} else {
switch item {
case "vless", "vmess", "trojan", "ss":
q.filter.Protocols = append(q.filter.Protocols, item)
default:
return catalogQuery{}, false
}
}
}
}
continue
}
if len(values) != 1 {
return catalogQuery{}, false
}
value := values[0]
switch key {
case "format":
q.format = catalogFormat(value)
switch q.format {
case catalogJSON, catalogCSV, catalogTXT, catalogURLs:
default:
return catalogQuery{}, false
}
case "sort":
q.filter.Sort = db.GatewayCatalogSort(value)
switch q.filter.Sort {
case db.GatewaySortID, db.GatewaySortSpeed, db.GatewaySortLatency, db.GatewaySortCountry:
default:
return catalogQuery{}, false
}
case "min_speed_mbps":
n, ok := parseCatalogSpeed(value)
if !ok {
return catalogQuery{}, false
}
q.filter.MinSpeedMbps = &n
case "limit", "offset", "max_latency_ms":
n, ok := parseCatalogInt(value)
if !ok || (key == "limit" && n == 0) {
return catalogQuery{}, false
}
switch key {
case "limit":
q.filter.Limit = &n
case "offset":
q.filter.Offset = n
case "max_latency_ms":
q.filter.MaxLatencyMs = &n
}
default:
return catalogQuery{}, false
}
}
return q, true
}
func parseCatalogInt(raw string) (int64, bool) {
for i := range len(raw) {
if raw[i] < '0' || raw[i] > '9' {
return 0, false
}
}
n, err := strconv.ParseInt(raw, 10, 64)
return n, err == nil
}
func parseCatalogSpeed(raw string) (float64, bool) {
// Allow decimal floats (including scientific notation), not Go literals,
// non-finite values, whitespace or leading signs.
nonZeroMantissa, exponent := false, false
for i := range len(raw) {
switch b := raw[i]; {
case b >= '0' && b <= '9':
nonZeroMantissa = nonZeroMantissa || (!exponent && b != '0')
case b == 'e' || b == 'E':
exponent = true
case b == '.':
case (b == '-' || b == '+') && i > 0 && (raw[i-1] == 'e' || raw[i-1] == 'E'):
default:
return 0, false
}
}
n, err := strconv.ParseFloat(raw, 64)
// Underflow must not silently turn a positive lower bound into zero.
return n, err == nil && (n != 0 || !nonZeroMantissa)
}
+157
View File
@@ -0,0 +1,157 @@
package gateway
import (
"math"
"net/url"
"reflect"
"strconv"
"strings"
"testing"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
)
func TestGatewayCatalogQuery(t *testing.T) {
zeroSpeed, speed, tiny, maxSpeed := 0.0, 5.5, math.SmallestNonzeroFloat64, math.MaxFloat64
zero, one, two, latency, maxInt := int64(0), int64(1), int64(2), int64(800), int64(math.MaxInt64)
tests := []struct {
name string
raw string
format catalogFormat
filter db.GatewayCatalogFilter
}{
{"defaults", "", catalogJSON, db.GatewayCatalogFilter{Sort: db.GatewaySortID}},
{"CSV and repeated multi-value filters", "country=D%45%2CNL&country=XX&protocol=vless&protocol=vmess,trojan,ss&min_speed_mbps=5.5e%2B0&max_latency_ms=800&sort=latency&limit=2&offset=1&format=csv", catalogCSV,
db.GatewayCatalogFilter{Countries: []string{"DE", "NL", "XX"}, Protocols: []string{"vless", "vmess", "trojan", "ss"}, MinSpeedMbps: &speed, MaxLatencyMs: &latency, Sort: db.GatewaySortLatency, Limit: &two, Offset: 1}},
{"zeros are explicit", "min_speed_mbps=0&max_latency_ms=0&offset=0&limit=01&sort=speed&format=txt", catalogTXT,
db.GatewayCatalogFilter{MinSpeedMbps: &zeroSpeed, MaxLatencyMs: &zero, Sort: db.GatewaySortSpeed, Limit: &one}},
{"largest integers and smallest float", "limit=9223372036854775807&offset=9223372036854775807&max_latency_ms=9223372036854775807&min_speed_mbps=5e-324&sort=country&format=proxy-url-list-txt", catalogURLs,
db.GatewayCatalogFilter{MinSpeedMbps: &tiny, MaxLatencyMs: &maxInt, Sort: db.GatewaySortCountry, Limit: &maxInt, Offset: maxInt}},
{"maximum finite speed", "min_speed_mbps=1.7976931348623157e308&sort=id&format=json", catalogJSON,
db.GatewayCatalogFilter{MinSpeedMbps: &maxSpeed, Sort: db.GatewaySortID}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, ok := parseCatalogQuery(tc.raw)
if !ok || got.format != tc.format || !reflect.DeepEqual(got.filter, tc.filter) {
t.Fatalf("catalog query did not preserve the requested format and filter: %+v, valid=%t", got, ok)
}
})
}
}
func TestGatewayCatalogQueryRejectsInvalidInput(t *testing.T) {
tests := []struct{ name, raw string }{
{"missing values", "country"},
{"unknown parameter", "country=DE&extra=1"},
{"case-sensitive parameter", "Country=DE"},
{"empty key", "=DE"},
{"bad escaped key", "country=DE&%zz=NL"},
{"bad escaped value", "country=DE&protocol=%xx"},
{"incomplete escape", "offset=%0"},
{"illegal separator", "country=DE;sort=id"},
{"unsupported format", "format=xml"},
{"empty format", "format="},
{"unsupported sort", "sort=desc"},
{"sort injection", "sort=id%3B+SELECT+1"},
{"empty sort", "sort="},
{"short country", "country=D"},
{"lowercase country", "country=de"},
{"Unicode country", "country=%C3%84"},
{"invalid UTF-8", "country=%ff%ff"},
{"nul in country", "country=%00E"},
{"empty country", "country="},
{"empty element", "country=DE,,NL"},
{"invalid repeated value", "country=DE&country="},
{"trailing comma", "protocol=vless,"},
{"empty protocol", "protocol="},
{"unsupported protocol", "protocol=socks5"},
{"whitespace in array", "country=DE,+NL"},
{"encoded ampersand is data", "country=DE%26protocol=ss"},
{"negative limit", "limit=-1"},
{"zero limit", "limit=0"},
{"negative offset", "offset=-1"},
{"fractional offset", "offset=1.5"},
{"signed latency", "max_latency_ms=%2B3"},
{"negative latency", "max_latency_ms=-1"},
{"fractional latency", "max_latency_ms=1.0"},
{"whitespace integer", "offset=1+"},
{"empty integer", "offset="},
{"negative speed", "min_speed_mbps=-1"},
{"NaN speed", "min_speed_mbps=NaN"},
{"infinite speed", "min_speed_mbps=Inf"},
{"float overflow", "min_speed_mbps=1e309"},
{"float underflow", "min_speed_mbps=1e-9999"},
{"hex float", "min_speed_mbps=0x1p0"},
{"Go float separator", "min_speed_mbps=1_000"},
{"empty speed", "min_speed_mbps="},
{"whitespace speed", "min_speed_mbps=+5"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
assertCatalogQueryInvalid(t, tc.raw)
})
}
for _, pair := range []string{"sort=id", "format=txt", "limit=3", "offset=0", "max_latency_ms=7", "min_speed_mbps=5"} {
k, v, _ := strings.Cut(pair, "=")
t.Run("duplicate "+k, func(t *testing.T) {
assertCatalogQueryInvalid(t, pair+"&"+pair)
// Reject duplicates after decoding the key as well.
escaped := "%" + strconv.FormatUint(uint64(k[0]), 16) + k[1:]
assertCatalogQueryInvalid(t, pair+"&"+escaped+"="+v)
})
}
for _, key := range []string{"limit", "offset", "max_latency_ms"} {
t.Run("overflow "+key, func(t *testing.T) {
assertCatalogQueryInvalid(t, key+"=9223372036854775808")
})
}
}
func assertCatalogQueryInvalid(t *testing.T, raw string) {
t.Helper()
if got, ok := parseCatalogQuery(raw); ok || !reflect.DeepEqual(got, catalogQuery{}) {
t.Fatal("invalid query was accepted or returned a partial filter")
}
}
func FuzzGatewayCatalogQuery(f *testing.F) {
for _, seed := range []string{
"", "country=DE%2CNL&country=XX&protocol=ss,vless&sort=latency&limit=2&offset=0&format=csv",
"min_speed_mbps=1.5e%2B2&max_latency_ms=9223372036854775807", "country=DE&%63ountry=NL",
"limit=1&l%69mit=2", "format=txt&format=csv", "country=DE&protocol=%ff", "sort=id%3BSELECT+1",
"limit=9223372036854775808", "min_speed_mbps=1e-999999", "protocol=vless%26format=txt", "bad=%zz",
} {
f.Add(seed)
}
f.Fuzz(func(t *testing.T, raw string) {
q, ok := parseCatalogQuery(raw)
if !ok {
if !reflect.DeepEqual(q, catalogQuery{}) {
t.Fatal("invalid query returned a partial filter")
}
return
}
canonical := url.Values{"format": {string(q.format)}, "sort": {string(q.filter.Sort)}}
for _, country := range q.filter.Countries {
canonical.Add("country", country)
}
for _, protocol := range q.filter.Protocols {
canonical.Add("protocol", protocol)
}
if q.filter.MinSpeedMbps != nil {
canonical.Set("min_speed_mbps", strconv.FormatFloat(*q.filter.MinSpeedMbps, 'g', -1, 64))
}
if q.filter.MaxLatencyMs != nil {
canonical.Set("max_latency_ms", strconv.FormatInt(*q.filter.MaxLatencyMs, 10))
}
if q.filter.Limit != nil {
canonical.Set("limit", strconv.FormatInt(*q.filter.Limit, 10))
}
canonical.Set("offset", strconv.FormatInt(q.filter.Offset, 10))
normalized, ok := parseCatalogQuery(canonical.Encode())
if !ok || !reflect.DeepEqual(normalized, q) {
t.Fatal("canonical query changed the parsed filters or format")
}
})
}
+404
View File
@@ -0,0 +1,404 @@
package gateway
import (
"bytes"
"context"
"errors"
"io"
"maps"
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
"git.eeee.moe/omar/zhguchiy_perchik/internal/dialer"
"git.eeee.moe/omar/zhguchiy_perchik/internal/upstream"
)
// GatewayNodeStore selects one node from the current published snapshot.
type GatewayNodeStore interface {
LookupGatewayNode(context.Context, int64, time.Time) (*db.GatewayNode, error)
LookupGatewayProbeNode(context.Context, int64, int64) (*db.GatewayNode, error)
}
type forwardTiming struct {
setup, idle, halfCloseGrace time.Duration
}
// ForwardProxy owns the request budgets and all active proxy requests, including
// connections that have been hijacked from the HTTP server.
type ForwardProxy struct {
store GatewayNodeStore
resolveRequest func(context.Context, *http.Request) (string, string, error)
dispatcher dialer.Dialer
tickets *probeTickets
users chan struct{}
probes chan struct{}
timing forwardTiming
lifetime context.Context
stop context.CancelFunc
mu sync.Mutex
active int
drained chan struct{}
}
// NewForwardProxy binds forwarding to a policy and a dispatcher with a guarded
// upstream socket opener.
func NewForwardProxy(store GatewayNodeStore, policy *RoutePolicy, dispatcher dialer.Dialer, tickets *probeTickets) *ForwardProxy {
lifetime, stop := context.WithCancel(context.Background())
return &ForwardProxy{
store: store,
resolveRequest: policy.ResolveRequest,
dispatcher: dispatcher,
tickets: tickets,
users: make(chan struct{}, 256),
probes: make(chan struct{}, 8),
timing: forwardTiming{setup: 8 * time.Second, idle: 2 * time.Minute, halfCloseGrace: 5 * time.Second},
lifetime: lifetime,
stop: stop,
drained: make(chan struct{}),
}
}
// ServeProxy is called only after authenticating this request and selecting its ID.
func (p *ForwardProxy) ServeProxy(w http.ResponseWriter, r *http.Request, id int64) {
membership, isProbe := p.tickets.consume(r, id)
if isProbe && membership <= 0 {
forwardError(w, http.StatusForbidden)
return
}
slots := p.users
if isProbe {
slots = p.probes
}
if !p.begin() {
forwardError(w, http.StatusServiceUnavailable)
return
}
defer p.end()
select {
case slots <- struct{}{}:
defer func() { <-slots }()
default:
w.Header().Set("Retry-After", "1")
forwardError(w, http.StatusServiceUnavailable)
return
}
ctx, cancel := context.WithCancel(r.Context())
stop := context.AfterFunc(p.lifetime, cancel)
defer cancel()
defer stop()
conn, status := p.open(ctx, r, id, membership)
if status != 0 {
forwardError(w, status)
return
}
if r.Method == http.MethodConnect {
p.connect(w, conn)
return
}
defer conn.Close()
p.forwardHTTP(ctx, w, r, conn)
}
func (p *ForwardProxy) open(ctx context.Context, r *http.Request, id, membership int64) (net.Conn, int) {
timeout := p.timing.setup
if membership > 0 {
// Leave time for the monitor to receive a node failure before its
// end-to-end probe deadline expires.
timeout = min(timeout, probeTicketTTL-time.Second)
}
setup, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
var node *db.GatewayNode
var err error
if membership > 0 {
node, err = p.store.LookupGatewayProbeNode(setup, id, membership)
} else {
// Use the DB clock for the same freshness predicate as the catalog.
node, err = p.store.LookupGatewayNode(setup, id, time.Time{})
}
if err != nil {
return nil, http.StatusServiceUnavailable
}
if node == nil || node.ProxyID != id || (membership > 0 && node.MembershipID != membership) {
if membership > 0 {
return nil, http.StatusConflict
}
return nil, http.StatusServiceUnavailable
}
_, destination, err := p.resolveRequest(setup, r)
if err != nil {
switch {
case forwardTimeout(setup, err):
if membership > 0 {
return nil, http.StatusServiceUnavailable
}
return nil, http.StatusGatewayTimeout
case errors.Is(err, ErrInvalidDestination):
return nil, http.StatusBadRequest
default:
return nil, http.StatusForbidden
}
}
up, err := upstream.ParseURL(node.CanonicalURL)
if err != nil {
return nil, http.StatusBadGateway
}
if err := setup.Err(); err != nil {
if membership > 0 {
return nil, http.StatusServiceUnavailable
}
return nil, forwardUpstreamStatus(setup, err)
}
conn, err := p.dispatcher.Dial(setup, up, destination)
if err == nil {
err = setup.Err()
}
if err != nil || conn == nil {
if conn != nil {
_ = conn.Close()
}
return nil, forwardUpstreamStatus(setup, err)
}
return conn, 0
}
func (p *ForwardProxy) forwardHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request, conn net.Conn) {
// A request gets one already-open tunnel. Transport has no route to dial
// directly, to retry through another node, or to reuse another request's peer.
var claimed atomic.Bool
wire := &forwardResponseConn{Conn: conn}
transport := &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if !claimed.CompareAndSwap(false, true) {
return nil, net.ErrClosed
}
return wire, nil
},
DisableCompression: true,
ResponseHeaderTimeout: p.timing.setup,
MaxResponseHeaderBytes: maxForwardResponseHeaderBytes,
}
// Closing this one-request transport without sending Connection: close
// lets a conforming origin send its own connection options unmodified.
defer transport.CloseIdleConnections()
out := r.WithContext(ctx)
out.RequestURI = ""
out.Close = false
out.TransferEncoding = nil
out.Trailer = nil
stripForwardHopHeaders(out.Header, out.Header.Values("Connection"))
rc := http.NewResponseController(w)
// The origin may send a response before a streaming upload is finished.
_ = rc.EnableFullDuplex()
// Cancellation must also interrupt a blocked client upload or response
// write. Do not let the callback outlive this request's use of the socket.
interrupted := make(chan struct{})
interrupt := context.AfterFunc(ctx, func() {
deadline := time.Now()
_ = rc.SetReadDeadline(deadline)
_ = rc.SetWriteDeadline(deadline)
close(interrupted)
})
defer func() {
if !interrupt() {
<-interrupted
}
}()
resp, err := transport.RoundTrip(out)
if err != nil {
forwardError(w, forwardUpstreamStatus(ctx, err))
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusSwitchingProtocols || !wire.done {
forwardError(w, http.StatusBadGateway)
return
}
stripForwardHopHeaders(resp.Header, []string{string(wire.options)})
maps.Copy(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
// Put the status on the wire before consuming the body. Never let a read
// failure produce a valid terminating chunk for a truncated response.
if err := rc.Flush(); err != nil {
panic(http.ErrAbortHandler)
}
var dst io.Writer = w
if resp.ContentLength < 0 || strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
dst = flushingForwardWriter{Writer: w, flush: rc.Flush}
}
if _, err := io.Copy(dst, resp.Body); err != nil {
panic(http.ErrAbortHandler)
}
}
type flushingForwardWriter struct {
io.Writer
flush func() error
}
func (w flushingForwardWriter) Write(b []byte) (int, error) {
n, err := w.Writer.Write(b)
if err == nil {
err = w.flush()
}
return n, err
}
func stripForwardHopHeaders(h http.Header, connection []string) {
for _, value := range connection {
for field := range strings.SplitSeq(value, ",") {
h.Del(strings.TrimSpace(field))
}
}
for _, name := range [...]string{
"Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", "Proxy-Connection",
"Te", "Trailer", "Transfer-Encoding", "Upgrade", probeTicketHeader,
} {
h.Del(name)
}
}
const maxForwardResponseHeaderBytes = 32 << 10
// net/http drops all Connection lines if even one contains "close". Observe
// only the original option list, leaving status, framing and body parsing to
// Transport. It publishes the response after the final header has been read;
// done and options are immutable from that point.
type forwardResponseConn struct {
net.Conn
partial, options []byte
seen int
status, interim, field, done bool
}
func (c *forwardResponseConn) Read(p []byte) (int, error) {
n, err := c.Conn.Read(p)
if c.done {
return n, err
}
data := p[:n]
for len(data) > 0 && !c.done {
available := min(len(data), maxForwardResponseHeaderBytes-c.seen)
if available == 0 {
return 0, errors.New("upstream response header too large")
}
end := bytes.IndexByte(data[:available], '\n')
if end < 0 {
c.partial = append(c.partial, data[:available]...)
c.seen += available
data = data[available:]
continue
}
line := data[:end]
if len(c.partial) > 0 {
c.partial = append(c.partial, line...)
line = c.partial
}
c.captureLine(bytes.TrimSuffix(line, []byte("\r")))
c.partial = c.partial[:0]
c.seen += end + 1
data = data[end+1:]
}
return n, err
}
func (c *forwardResponseConn) captureLine(line []byte) {
if !c.status {
_, rest, _ := bytes.Cut(line, []byte(" "))
code, _, _ := bytes.Cut(bytes.TrimLeft(rest, " "), []byte(" "))
c.interim = len(code) == 3 && code[0] == '1' && !bytes.Equal(code, []byte("101"))
c.status = true
return
}
if len(line) == 0 {
if c.interim {
c.options = c.options[:0]
c.status, c.field = false, false
} else {
c.done = true
}
return
}
if line[0] == ' ' || line[0] == '\t' {
if c.field {
c.options = append(c.options, ' ')
c.options = append(c.options, bytes.Trim(line, " \t")...)
}
return
}
name, value, ok := bytes.Cut(line, []byte(":"))
c.field = ok && bytes.EqualFold(name, []byte("Connection"))
if c.field {
if len(c.options) > 0 {
c.options = append(c.options, ',')
}
c.options = append(c.options, bytes.Trim(value, " \t")...)
}
}
func forwardTimeout(ctx context.Context, err error) bool {
var timeout net.Error
return errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) ||
(errors.As(err, &timeout) && timeout.Timeout())
}
func forwardUpstreamStatus(ctx context.Context, err error) int {
if forwardTimeout(ctx, err) {
return http.StatusGatewayTimeout
}
return http.StatusBadGateway
}
func forwardError(w http.ResponseWriter, status int) {
http.Error(w, http.StatusText(status), status)
}
func (p *ForwardProxy) begin() bool {
p.mu.Lock()
defer p.mu.Unlock()
if p.lifetime.Err() != nil {
return false
}
p.active++
return true
}
func (p *ForwardProxy) end() {
p.mu.Lock()
defer p.mu.Unlock()
p.active--
if p.active == 0 && p.lifetime.Err() != nil {
close(p.drained)
}
}
// Shutdown cancels active requests and waits until their handlers, including
// both CONNECT copying directions, have released their connections.
func (p *ForwardProxy) Shutdown(ctx context.Context) error {
p.mu.Lock()
if p.lifetime.Err() == nil {
p.stop()
if p.active == 0 {
close(p.drained)
}
}
p.mu.Unlock()
select {
case <-p.drained:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
+437
View File
@@ -0,0 +1,437 @@
package gateway
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
"git.eeee.moe/omar/zhguchiy_perchik/internal/upstream"
)
const (
forwardTestAuthority = "control.fixture:443"
forwardTestDeadline = 3 * time.Second
)
type forwardTestStore struct {
ready func(int64) (*db.GatewayNode, error)
probe func(int64, int64) (*db.GatewayNode, error)
}
func (s forwardTestStore) LookupGatewayNode(_ context.Context, id int64, _ time.Time) (*db.GatewayNode, error) {
if s.ready == nil {
return nil, nil
}
return s.ready(id)
}
func (s forwardTestStore) LookupGatewayProbeNode(_ context.Context, id, membership int64) (*db.GatewayNode, error) {
if s.probe == nil {
return nil, nil
}
return s.probe(id, membership)
}
func forwardTestNode(id, membership int64) *db.GatewayNode {
return &db.GatewayNode{
ProxyID: id,
MembershipID: membership,
CanonicalURL: fmt.Sprintf("trojan://fixture@peer%d.fixture:443", id),
}
}
func forwardTestReady(id int64) (*db.GatewayNode, error) { return forwardTestNode(id, 1), nil }
type forwardTestDial func(context.Context, *upstream.Upstream, string) (net.Conn, error)
func (f forwardTestDial) Dial(ctx context.Context, up *upstream.Upstream, dest string) (net.Conn, error) {
return f(ctx, up, dest)
}
func newForwardTestProxy(store forwardTestStore, dial forwardTestDial, tickets *probeTickets, dest string) *ForwardProxy {
p := NewForwardProxy(store, NewRoutePolicy(Config{}), dial, tickets)
p.resolveRequest = func(_ context.Context, r *http.Request) (string, string, error) {
return r.URL.Host, dest, nil
}
return p
}
func serveForwardTest(t *testing.T, p *ForwardProxy) (string, Credentials) {
t.Helper()
listener, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
credentials, err := NewCredentials("838e3104-6966-4644-b625-932c6e6f62a9", [32]byte{1})
if err != nil {
_ = listener.Close()
t.Fatal(err)
}
server := gatewayHTTPServer(context.Background(), credentials.RequireProxyAuth(proxyFormHandler(p)))
exited := make(chan error, 1)
go func() { exited <- server.Serve(listener) }()
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), forwardTestDeadline)
defer cancel()
if err := p.Shutdown(ctx); err != nil {
t.Error(err)
}
_ = server.Close()
if err := forwardTestReceive(t, exited); !errors.Is(err, http.ErrServerClosed) {
t.Errorf("proxy stopped: %v", err)
}
})
return listener.Addr().String(), credentials
}
func forwardTestReceive[T any](t *testing.T, c <-chan T) T {
t.Helper()
select {
case value := <-c:
return value
case <-time.After(forwardTestDeadline):
t.Fatal("timed out waiting for socket test event")
var zero T
return zero
}
}
func forwardTestClient(t *testing.T, addr string, credentials Credentials, id int64, roots *x509.CertPool) *http.Client {
t.Helper()
proxy := &url.URL{Scheme: "http", Host: addr, User: url.UserPassword(fmt.Sprintf("node-%d", id), credentials.Password(id))}
tr := &http.Transport{
Proxy: http.ProxyURL(proxy),
TLSClientConfig: &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12},
}
t.Cleanup(tr.CloseIdleConnections)
return &http.Client{
Transport: tr,
Timeout: forwardTestDeadline,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
}
func forwardTestTCP(t *testing.T, addr string) (*net.TCPConn, *bufio.Reader) {
t.Helper()
c, err := net.DialTimeout("tcp", addr, forwardTestDeadline)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = c.Close() })
if err := c.SetDeadline(time.Now().Add(forwardTestDeadline)); err != nil {
t.Fatal(err)
}
return c.(*net.TCPConn), bufio.NewReader(c)
}
func forwardTestBasic(credentials Credentials, id int64) string {
return "Proxy-Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("node-%d:%s", id, credentials.Password(id)))) + "\r\n"
}
func forwardTestResponse(t *testing.T, r *bufio.Reader, method string, status int) *http.Response {
t.Helper()
resp, err := http.ReadResponse(r, &http.Request{Method: method})
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != status {
_ = resp.Body.Close()
t.Fatalf("status = %d, want %d", resp.StatusCode, status)
}
return resp
}
func forwardTestConnect(t *testing.T, c *net.TCPConn, r *bufio.Reader, auth, ticket, early string, status int) *http.Response {
t.Helper()
var header string
if ticket != "" {
header = probeTicketHeader + ": " + ticket + "\r\n"
}
if _, err := fmt.Fprintf(c, "CONNECT %[1]s HTTP/1.1\r\nHost: %[1]s\r\n%[2]s%[3]s\r\n%[4]s", forwardTestAuthority, auth, header, early); err != nil {
t.Fatal(err)
}
resp := forwardTestResponse(t, r, http.MethodConnect, status)
if status != http.StatusOK {
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
}
return resp
}
func TestForwardHTTPRouteAndHeaders(t *testing.T) {
var routeHits [2]atomic.Int32
payload := bytes.Repeat([]byte("upload\x00data"), 8192)
origins := make([]*httptest.Server, len(routeHits))
for i := range origins {
origins[i] = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
routeHits[i].Add(1)
if r.Host != "web.fixture:80" || r.RequestURI != "/echo?nonce=fixture" || r.Method != http.MethodPost {
t.Error("wrong origin form, authority, or method")
}
if r.Header.Get("Authorization") != "Bearer origin-only" || r.Header.Get("X-End-To-End") != "request" {
t.Error("origin authorization or end-to-end field was dropped")
}
for _, key := range []string{"Proxy-Authorization", "Proxy-Connection", "X-First-Hop", "X-Second-Hop", "X-Third-Hop", probeTicketHeader} {
if r.Header.Get(key) != "" {
t.Errorf("origin received %s", key)
}
}
w.Header().Set("X-End-To-End", "response")
w.Header().Set("Authorization", "Bearer origin-response")
w.Header().Set("X-Route", fmt.Sprint(i+1))
w.Header().Add("Connection", "X-Response-Hop")
w.Header().Add("Connection", "X-Other-Hop, X-Last-Hop")
for _, key := range []string{"Proxy-Authenticate", "Proxy-Authorization", "X-Response-Hop", "X-Other-Hop", "X-Last-Hop", probeTicketHeader} {
w.Header().Set(key, "not-end-to-end")
}
// Intentionally send opaque encoded bytes to exercise forwarding without
// transparent decompression by the gateway's HTTP transport.
w.Header().Set("Content-Encoding", "gzip")
_ = http.NewResponseController(w).EnableFullDuplex()
if _, err := io.Copy(w, r.Body); err != nil {
t.Errorf("echoing upload: %v", err)
}
}))
t.Cleanup(origins[i].Close)
}
var dialHits [2]atomic.Int32
p := newForwardTestProxy(forwardTestStore{ready: forwardTestReady}, func(ctx context.Context, up *upstream.Upstream, dest string) (net.Conn, error) {
if dest != "192.0.2.77:80" {
return nil, errors.New("unexpected pinned fixture destination")
}
for i, origin := range origins {
if up.Host == fmt.Sprintf("peer%d.fixture", i+1) {
dialHits[i].Add(1)
return new(net.Dialer).DialContext(ctx, "tcp", origin.Listener.Addr().String())
}
}
return nil, errors.New("unexpected selected fixture peer")
}, nil, "192.0.2.77:80")
addr, credentials := serveForwardTest(t, p)
for id := int64(1); id <= 2; id++ {
client := forwardTestClient(t, addr, credentials, id, nil)
req, err := http.NewRequest(http.MethodPost, "http://web.fixture:80/echo?nonce=fixture", bytes.NewReader(payload))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer origin-only")
req.Header.Set("Accept-Encoding", "gzip")
req.Header.Set("X-End-To-End", "request")
req.Header.Add("Connection", "X-First-Hop")
req.Header.Add("Connection", "X-Second-Hop, x-third-hop")
for _, key := range []string{"Proxy-Connection", "X-First-Hop", "X-Second-Hop", "X-Third-Hop"} {
req.Header.Set(key, "not-end-to-end")
}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
got, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil || resp.StatusCode != http.StatusOK || !bytes.Equal(got, payload) {
t.Fatalf("node %d response: status=%d size=%d err=%v", id, resp.StatusCode, len(got), err)
}
if resp.Header.Get("X-Route") != fmt.Sprint(id) || resp.Header.Get("X-End-To-End") != "response" ||
resp.Header.Get("Authorization") != "Bearer origin-response" || resp.Header.Get("Content-Encoding") != "gzip" {
t.Fatal("wrong origin or lost end-to-end response field")
}
for _, key := range []string{"Connection", "Proxy-Authenticate", "Proxy-Authorization", "X-Response-Hop", "X-Other-Hop", "X-Last-Hop", probeTicketHeader} {
if resp.Header.Get(key) != "" {
t.Errorf("client received %s", key)
}
}
}
for i := range dialHits {
if dialHits[i].Load() != 1 || routeHits[i].Load() != 1 {
t.Errorf("peer %d counted %d dials, %d requests", i+1, dialHits[i].Load(), routeHits[i].Load())
}
}
}
func TestForwardKeepAliveReauthenticatesAndDoesNotFailOver(t *testing.T) {
var originHits atomic.Int32
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
originHits.Add(1)
_, _ = io.WriteString(w, "one")
}))
defer origin.Close()
var up1, up2 atomic.Int32
store := forwardTestStore{ready: func(id int64) (*db.GatewayNode, error) {
if id == 3 {
return nil, nil
}
if id == 4 {
return nil, errors.New("DB unavailable")
}
return forwardTestReady(id)
}}
p := newForwardTestProxy(store, func(ctx context.Context, up *upstream.Upstream, _ string) (net.Conn, error) {
switch up.Host {
case "peer1.fixture":
up1.Add(1)
return new(net.Dialer).DialContext(ctx, "tcp", origin.Listener.Addr().String())
case "peer2.fixture":
up2.Add(1)
return nil, errors.New("selected peer down")
default:
return nil, errors.New("unexpected dial for missing node")
}
}, nil, origin.Listener.Addr().String())
addr, credentials := serveForwardTest(t, p)
c, r := forwardTestTCP(t, addr)
// The origin is itself reachable; falling back to a direct dial would pass.
for _, tc := range []struct {
id int64
status int
}{{1, 200}, {0, 407}, {2, 502}, {3, 503}, {4, 503}, {1, 200}} {
var auth string
if tc.id > 0 {
auth = forwardTestBasic(credentials, tc.id)
}
if _, err := fmt.Fprintf(c, "GET %s/route HTTP/1.1\r\nHost: %s\r\n%s\r\n", origin.URL, origin.Listener.Addr(), auth); err != nil {
t.Fatal(err)
}
resp := forwardTestResponse(t, r, http.MethodGet, tc.status)
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil || (tc.status == 200 && string(body) != "one") {
t.Fatalf("node %d read: %q, %v", tc.id, body, err)
}
if tc.status == 407 && resp.Header.Get("Proxy-Authenticate") != `Basic realm="http-gateway"` {
t.Fatal("missing proxy authentication challenge")
}
}
if up1.Load() != 2 || up2.Load() != 1 || originHits.Load() != 2 {
t.Fatalf("unexpected dials/requests after failure: %d %d %d", up1.Load(), up2.Load(), originHits.Load())
}
}
func TestForwardHTTPSAndResponseHeaderTimeout(t *testing.T) {
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/secure" || r.TLS == nil || r.Header.Get("Proxy-Authorization") != "" {
t.Error("wrong HTTPS traffic at origin")
}
_, _ = io.WriteString(w, "tls origin")
}))
defer origin.Close()
p := newForwardTestProxy(forwardTestStore{ready: forwardTestReady}, func(ctx context.Context, up *upstream.Upstream, dest string) (net.Conn, error) {
return new(net.Dialer).DialContext(ctx, "tcp", dest)
}, nil, origin.Listener.Addr().String())
addr, credentials := serveForwardTest(t, p)
roots := x509.NewCertPool()
roots.AddCert(origin.Certificate())
resp, err := forwardTestClient(t, addr, credentials, 1, roots).Get(origin.URL + "/secure")
if err != nil {
t.Fatal(err)
}
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil || string(body) != "tls origin" || resp.StatusCode != 200 {
t.Fatalf("HTTPS response: status=%d body=%q err=%v", resp.StatusCode, body, err)
}
t.Run("unresponsive HTTP origin", func(t *testing.T) {
blocked := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { <-r.Context().Done() }))
defer blocked.Close()
p := newForwardTestProxy(forwardTestStore{ready: forwardTestReady}, func(ctx context.Context, _ *upstream.Upstream, dest string) (net.Conn, error) {
return new(net.Dialer).DialContext(ctx, "tcp", dest)
}, nil, blocked.Listener.Addr().String())
p.timing.setup = 300 * time.Millisecond
addr, credentials := serveForwardTest(t, p)
resp, err := forwardTestClient(t, addr, credentials, 1, nil).Get(blocked.URL)
if err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
if resp.StatusCode != 504 {
t.Fatalf("status = %d, want 504", resp.StatusCode)
}
})
}
func TestForwardAbortsStartedTruncatedResponse(t *testing.T) {
for _, tc := range []struct{ name, framing, part string }{
{"length", "Content-Length: 12", "part"},
{"chunked", "Transfer-Encoding: chunked", "4\r\npart\r\n"},
} {
t.Run(tc.name, func(t *testing.T) {
reset := make(chan struct{})
var resetOnce sync.Once
triggerReset := func() { resetOnce.Do(func() { close(reset) }) }
defer triggerReset()
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
c, rw, err := http.NewResponseController(w).Hijack()
if err != nil {
t.Error(err)
return
}
defer c.Close()
head := "HTTP/1.1 103 Early Hints\r\nConnection: X-Final-End-To-End\r\n\r\n" +
"HTTP/1.1 200 OK\r\nConnection: close, X-First-Hop\r\nConnection: X-Second-Hop,\r\n\tX-Folded-Hop\r\n" +
"X-First-Hop: remove\r\nX-Second-Hop: remove\r\nX-Folded-Hop: remove\r\nX-Final-End-To-End: keep\r\n"
if _, err := fmt.Fprintf(rw, "%s%s\r\n\r\n%s", head, tc.framing, tc.part); err != nil {
t.Error(err)
return
}
if err := rw.Flush(); err != nil {
t.Error(err)
return
}
<-reset
_ = c.(*net.TCPConn).SetLinger(0)
}))
defer origin.Close()
p := newForwardTestProxy(forwardTestStore{ready: forwardTestReady}, func(ctx context.Context, _ *upstream.Upstream, dest string) (net.Conn, error) {
return new(net.Dialer).DialContext(ctx, "tcp", dest)
}, nil, origin.Listener.Addr().String())
addr, credentials := serveForwardTest(t, p)
resp, err := forwardTestClient(t, addr, credentials, 1, nil).Get(origin.URL)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("status = %d, want a started 200 response", resp.StatusCode)
}
for _, key := range []string{"X-First-Hop", "X-Second-Hop", "X-Folded-Hop"} {
if resp.Header.Get(key) != "" {
t.Errorf("raw origin Connection nomination %s was forwarded", key)
}
}
if resp.Header.Get("X-Final-End-To-End") != "keep" {
t.Error("interim Connection nomination incorrectly removed a final response header")
}
var prefix [4]byte
// A known-length body may be buffered by net/http. Receiving the
// chunked prefix proves the abort happens after streaming bytes.
if tc.name == "chunked" {
if _, err := io.ReadFull(resp.Body, prefix[:]); err != nil || string(prefix[:]) != "part" {
t.Fatalf("first chunk not streamed: %q, %v", prefix, err)
}
}
triggerReset()
rest, err := io.ReadAll(resp.Body)
if err == nil || strings.Contains(string(rest), "Bad Gateway") {
t.Fatalf("reset was reported as a complete or synthetic HTTP body: %q, err=%v", rest, err)
}
})
}
}
@@ -0,0 +1,256 @@
//go:build gateway_e2e && linux
package gateway
import (
"bytes"
"context"
"encoding/base64"
"encoding/csv"
"encoding/json"
"io"
"net"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"testing"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
)
func (r *chainRuntime) waitStatus(t *testing.T, sessionID, ready int64, since time.Time) db.GatewayStatus {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)
defer cancel()
tick := time.NewTicker(50 * time.Millisecond)
defer tick.Stop()
var got db.GatewayStatus
for {
resp, err := r.get(ctx, "/v1/status", r.token)
if err == nil {
if resp.StatusCode == http.StatusOK {
got = db.GatewayStatus{}
err = json.NewDecoder(io.LimitReader(resp.Body, 16<<10)).Decode(&got)
}
_ = resp.Body.Close()
if err == nil && resp.StatusCode == http.StatusOK && got.State == "idle" && got.LastErrorCode == nil &&
got.SessionID != nil && *got.SessionID == sessionID && got.CandidateCount == 2 && got.ReadyCount == ready &&
got.IntervalMinutes != nil && *got.IntervalMinutes == 15 && got.NextFullAt != nil &&
got.LastSuccessAt != nil && got.LastSuccessAt.After(since) {
return got
}
}
select {
case <-r.done:
t.Fatalf("runtime exited while awaiting monitor status: %v", r.err)
case <-ctx.Done():
code := ""
if got.LastErrorCode != nil {
code = *got.LastErrorCode
}
t.Fatalf("monitor did not report a new healthy pass (%d ready): state=%q code=%q ready=%d candidates=%d", ready, got.State, code, got.ReadyCount, got.CandidateCount)
case <-tick.C:
}
}
}
func (r *chainRuntime) requireStatus(t *testing.T, path, token string, status int) {
t.Helper()
resp, err := r.get(t.Context(), path, token)
if err != nil {
t.Fatalf("gateway status request: %v", wireClientError(err))
}
defer resp.Body.Close()
if resp.StatusCode != status || resp.Header.Get("Cache-Control") != "no-store" {
t.Fatalf("GET %s: want HTTP %d and no-store, got HTTP %d", path, status, resp.StatusCode)
}
}
type chainCatalog struct {
runtime *chainRuntime
sessionID int64
finished time.Time
forbidden []string
}
// Client-facing record, declared independently of the server's DTO and writers.
type chainExportRow struct {
ID int64 `json:"proxy_id,string"`
Host string `json:"host"`
Port uint16 `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
URL string `json:"proxy_url"`
Country string `json:"country"`
Protocol string `json:"protocol"`
ExitIP string `json:"exit_ip"`
Speed *float64 `json:"speed_mbps"`
Latency int `json:"latency_ms"`
Checked time.Time `json:"checked_at"`
}
func (c chainCatalog) body(t *testing.T, filter, format, contentType string) []byte {
t.Helper()
resp, err := c.runtime.get(t.Context(), "/v1/proxies?format="+format+"&"+filter, c.runtime.token)
if err != nil {
t.Fatalf("read %s export: %v", format, wireClientError(err))
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK || resp.Header.Get("Content-Type") != contentType || resp.Header.Get("Cache-Control") != "no-store" {
t.Fatalf("%s export has HTTP %d or incorrect content/cache headers", format, resp.StatusCode)
}
const max = 16 << 10
body, err := io.ReadAll(io.LimitReader(resp.Body, max+1))
if err != nil || len(body) > max {
t.Fatalf("read bounded %s export body", format)
}
for _, value := range c.forbidden {
if bytes.Contains(body, []byte(value)) {
t.Fatalf("%s export leaked provider data or API credentials", format)
}
}
return body
}
// Compare all formats as an independent client and pass each format's actual
// parsed URLs to forwarding checks. Return the URLs from the url-list export.
func (c chainCatalog) exports(t *testing.T, filter string, want []db.SessionProxy, use func([]*url.URL)) []*url.URL {
t.Helper()
var catalog struct {
SessionID int64 `json:"session_id"`
Finished time.Time `json:"session_finished_at"`
AsOf time.Time `json:"as_of"`
Total int `json:"total"`
Items []chainExportRow `json:"items"`
}
dec := json.NewDecoder(bytes.NewReader(c.body(t, filter, "json", "application/json")))
dec.DisallowUnknownFields()
if dec.Decode(&catalog) != nil || dec.Decode(new(json.RawMessage)) != io.EOF || catalog.SessionID != c.sessionID ||
!catalog.Finished.Truncate(time.Second).Equal(c.finished.Truncate(time.Second)) || catalog.AsOf.Before(catalog.Finished) ||
catalog.Total != len(want) || catalog.Items == nil || len(catalog.Items) != len(want) {
t.Fatal("JSON export had incorrect metadata, result count, or shape")
}
jsonURLs := make([]*url.URL, len(want))
for i, row := range catalog.Items {
w := want[i]
if row.ID != w.ProxyID || row.Username != "node-"+strconv.FormatInt(w.ProxyID, 10) || row.Country != w.Country ||
row.Protocol != w.Protocol || row.ExitIP != w.ExitIP || row.Speed == nil || *row.Speed != w.SpeedMbps ||
row.Latency < 0 || row.Latency >= w.LatencyMs || row.Checked.Before(catalog.Finished) || row.Checked.After(catalog.AsOf) {
t.Fatalf("JSON export metadata did not match snapshot/probe for node %d", w.ProxyID)
}
jsonURLs[i] = c.parseURL(t, "json", row.URL)
if !chainURLMatches(jsonURLs[i], row.Host, strconv.Itoa(int(row.Port)), row.Username, row.Password) {
t.Fatal("JSON fields disagree with its proxy URL")
}
}
if use != nil {
use(jsonURLs)
}
csvBody := c.body(t, filter, "csv", "text/csv; charset=utf-8")
header := strings.Split("proxy_id,host,port,username,password,proxy_url,country,protocol,exit_ip,speed_mbps,latency_ms,checked_at,session_finished_at", ",")
csvReader := csv.NewReader(bytes.NewReader(csvBody))
csvReader.FieldsPerRecord = len(header)
records, err := csvReader.ReadAll()
if err != nil || len(records) != len(want)+1 || !slices.Equal(records[0], header) {
t.Fatal("CSV export had incorrect header or row count")
}
csvURLs := make([]*url.URL, len(want))
for i, fields := range records[1:] {
row := catalog.Items[i]
speed, speedErr := strconv.ParseFloat(fields[9], 64)
latency, latencyErr := strconv.Atoi(fields[10])
checked, checkedErr := time.Parse(time.RFC3339, fields[11])
finished, finishedErr := time.Parse(time.RFC3339, fields[12])
if fields[0] != strconv.FormatInt(row.ID, 10) || fields[6] != row.Country || fields[7] != row.Protocol || fields[8] != row.ExitIP ||
speedErr != nil || speed != *row.Speed || latencyErr != nil || latency != row.Latency ||
checkedErr != nil || !checked.Equal(row.Checked) || finishedErr != nil || !finished.Equal(catalog.Finished) {
t.Fatalf("CSV export metrics disagree for node %d", row.ID)
}
csvURLs[i] = c.parseURL(t, "csv", fields[5])
if !chainURLMatches(csvURLs[i], fields[1], fields[2], fields[3], fields[4]) {
t.Fatal("CSV fields disagree with its proxy URL")
}
}
chainSameURLs(t, jsonURLs, csvURLs)
if use != nil {
use(csvURLs)
}
textURLs := make([]*url.URL, len(want))
for i, line := range c.lines(t, filter, "txt", len(want)) {
last := strings.LastIndexByte(line, ':')
// Split credentials from the right so a bracketed IPv6 authority is intact.
if last < 0 {
t.Fatal("malformed TXT proxy record")
}
beforePassword, password := line[:last], line[last+1:]
end := strings.LastIndexByte(beforePassword, ':')
if end < 0 {
t.Fatal("malformed TXT proxy record")
}
address, user := beforePassword[:end], beforePassword[end+1:]
if _, _, err := net.SplitHostPort(address); err != nil {
t.Fatal("malformed TXT proxy authority")
}
textURLs[i] = &url.URL{Scheme: "http", Host: address, User: url.UserPassword(user, password)}
}
chainSameURLs(t, jsonURLs, textURLs)
if use != nil {
use(textURLs)
}
urlListURLs := make([]*url.URL, len(want))
for i, line := range c.lines(t, filter, "proxy-url-list-txt", len(want)) {
urlListURLs[i] = c.parseURL(t, "proxy-url-list-txt", line)
}
chainSameURLs(t, jsonURLs, urlListURLs)
if use != nil {
use(urlListURLs)
}
return urlListURLs
}
func (c chainCatalog) lines(t *testing.T, filter, format string, count int) []string {
t.Helper()
body := c.body(t, filter, format, "text/plain; charset=utf-8")
if count == 0 && len(body) == 0 {
return nil
}
text, ok := strings.CutSuffix(string(body), "\n")
lines := strings.Split(text, "\n")
if count == 0 || !ok || len(lines) != count || strings.ContainsRune(text, '\r') {
t.Fatalf("%s export had an incorrect line count or ending", format)
}
return lines
}
func (c chainCatalog) parseURL(t *testing.T, format, raw string) *url.URL {
t.Helper()
u, err := url.Parse(raw)
if err != nil || u.Scheme != "http" || u.Host != c.runtime.endpoint.ProxyAddr || u.User == nil ||
u.Path != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
t.Fatalf("%s export did not return a URL for the bound proxy", format)
}
password, ok := u.User.Password()
decoded, err := base64.RawURLEncoding.Strict().DecodeString(password)
if !ok || err != nil || len(decoded) != 32 {
t.Fatalf("%s export has an invalid proxy password", format)
}
return u
}
func chainURLMatches(u *url.URL, host, port, user, pass string) bool {
password, ok := u.User.Password()
return ok && u.Host == net.JoinHostPort(host, port) && u.User.Username() == user && password == pass
}
func chainSameURLs(t *testing.T, first, second []*url.URL) {
t.Helper()
if !slices.EqualFunc(first, second, func(a, b *url.URL) bool { return a.String() == b.String() }) {
t.Fatal("ordered node URLs or credentials changed between exports")
}
}
+326
View File
@@ -0,0 +1,326 @@
//go:build gateway_e2e && linux
package gateway
import (
"context"
"crypto/rand"
"crypto/x509"
"encoding/base64"
"net"
"net/http"
"net/netip"
"net/url"
"os"
"strconv"
"strings"
"testing"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/config"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
"git.eeee.moe/omar/zhguchiy_perchik/internal/gateway/testfixture"
"github.com/jackc/pgx/v5"
)
func TestGatewayE2EFullChain(t *testing.T) {
xray, dsn := os.Getenv("XRAY_BIN"), os.Getenv("TEST_DATABASE_URL")
if xray == "" || dsn == "" {
t.Fatal("XRAY_BIN and TEST_DATABASE_URL are required for gateway full-chain acceptance")
}
withWireCA(t, func(ca *testfixture.Authority) {
store, dsn := openChainDB(t, dsn)
origin := testfixture.NewOrigin(t, ca, wireOriginName)
cases := testfixture.Cases()
first := testfixture.StartPeer(t, xray, origin, ca, cases[0]) // SS AEAD
second := testfixture.StartPeer(t, xray, origin, ca, cases[1]) // VLESS over TCP/TLS
control := origin.EnableControl(t, first.Source, second.Source)
policy, opens := newWireRoutePolicy(t, origin, first, second)
// Direct control may open only the fixture's HTTPS port. Forwarding still
// goes through the guarded dispatcher and the independent Xray processes.
opens.allowed[origin.HTTPSAddr.String()] = struct{}{}
probeURL, err := url.Parse(origin.HTTPSURL + control.Path)
if err != nil {
t.Fatal("construct fixture probe URL")
}
cfg := Config{DBDSN: dsn, ProbeURL: probeURL, AllowedDestinations: policy.destinations}
var apiKey [32]byte
_, _ = rand.Read(apiKey[:])
_, _ = rand.Read(cfg.NodeSecret[:])
cfg.APIToken = base64.RawURLEncoding.EncodeToString(apiKey[:])
a := db.SessionProxy{CanonicalURL: first.URL, Protocol: cases[0].Protocol, Host: testfixture.PeerName,
Port: int(first.Addr.Port()), Country: "DE", SourceName: "fixture-provider-ss", SpeedMbps: 10, ExitIP: "8.8.8.8", LatencyMs: 1_000_000}
b := db.SessionProxy{CanonicalURL: second.URL, Protocol: cases[1].Protocol, Host: testfixture.PeerName,
Port: int(second.Addr.Port()), Country: "NL", SourceName: "fixture-provider-vless", SpeedMbps: 20, ExitIP: a.ExitIP, LatencyMs: a.LatencyMs}
sessionID, finished := publishChainSnapshot(t, store, &a, &b)
runtime := startChainRuntime(t, cfg, policy, ca.Roots, "127.0.0.1:0")
ready := runtime.waitStatus(t, sessionID, 2, time.Time{})
direct := netip.MustParseAddr("127.0.0.1")
if control.Hits(direct) != 2 || control.Hits(first.Source) != 1 || control.Hits(second.Source) != 1 {
t.Fatal("initial pass did not run direct controls and probe each independent HTTPS route")
}
const all = "country=DE,NL&protocol=vless&protocol=ss&min_speed_mbps=10&sort=speed"
const onlyFirst = "country=DE&protocol=ss&min_speed_mbps=10&sort=speed"
catalog := chainCatalog{runtime: runtime, sessionID: sessionID, finished: finished,
forbidden: []string{first.URL, second.URL, testfixture.PeerName, a.SourceName, b.SourceName, cfg.APIToken}}
runtime.requireStatus(t, "/readyz", "", http.StatusOK)
runtime.requireStatus(t, "/v1/proxies", "", http.StatusUnauthorized)
runtime.requireStatus(t, "/v1/proxies", "not-the-token", http.StatusUnauthorized)
initial := catalog.exports(t, all, []db.SessionProxy{b, a}, func(proxies []*url.URL) {
mark := opens.mark()
for i, peer := range []*testfixture.Peer{second, first} {
client := newWireClient(t, proxies[i], ca.Roots)
wireRoundTrip(t, client, origin, peer, origin.HTTPURL, http.MethodGet, nil, []byte("catalog HTTP route"), true)
wireRoundTrip(t, client, origin, peer, origin.HTTPSURL, http.MethodGet, nil, []byte("catalog HTTPS route"), false)
}
opens.requireSince(t, mark, second.Addr.String(), second.Addr.String(), first.Addr.String(), first.Addr.String())
})
filtered := catalog.exports(t, onlyFirst, []db.SessionProxy{a}, nil)
firstPassword, _ := initial[1].User.Password()
secondPassword, _ := initial[0].User.Password()
if firstPassword == secondPassword || filtered[0].String() != initial[1].String() {
t.Fatal("catalog filtering changed node identity or did not select distinct credentials")
}
firstClient := newWireClient(t, initial[1], ca.Roots)
secondClient := newWireClient(t, initial[0], ca.Roots)
first.Stop(t)
mark := opens.mark()
chainRequireForwardStatus(t, firstClient, origin, first, http.StatusBadGateway)
opens.requireSince(t, mark, first.Addr.String())
wireRoundTrip(t, secondClient, origin, second, origin.HTTPURL, http.MethodGet, nil, []byte("other route survives"), true)
// Use the database clock to expire this positive sample without waiting
// a wall-clock TTL or changing production timing or forwarding policy.
expired, err := store.Pool().Exec(t.Context(), `UPDATE gateway_node_health
SET checked_at = statement_timestamp() - interval '30 minutes' WHERE proxy_id = $1 AND ok`, a.ProxyID)
if err != nil || expired.RowsAffected() != 1 {
t.Fatal("expire one successful fixture sample")
}
mark = opens.mark()
chainRequireForwardStatus(t, firstClient, origin, first, http.StatusServiceUnavailable)
catalog.exports(t, onlyFirst, nil, nil)
opens.requireSince(t, mark)
// Replacing a membership in the same published snapshot triggers an
// immediate-on-next-poll real recheck without moving the full-pass schedule.
chainDBOK(t, "remove stale membership", store.DeleteSessionProxies(t.Context(), sessionID, []int64{a.ProxyID}))
chainDBOK(t, "reinsert stopped peer", store.AddSessionProxy(t.Context(), &a, sessionID))
down := runtime.waitStatus(t, sessionID, 1, *ready.LastSuccessAt)
chainRequireHealth(t, store, a.ProxyID, false)
if !down.NextFullAt.Equal(*ready.NextFullAt) || control.Hits(direct) != 4 || control.Hits(first.Source) != 1 || control.Hits(second.Source) != 1 {
t.Fatal("early recheck did not isolate the stopped route, or shifted the full pass")
}
mark = opens.mark()
chainRequireForwardStatus(t, firstClient, origin, first, http.StatusServiceUnavailable)
opens.requireSince(t, mark)
catalog.exports(t, all, []db.SessionProxy{b}, nil)
first = first.Restart(t)
chainDBOK(t, "remove failed membership", store.DeleteSessionProxies(t.Context(), sessionID, []int64{a.ProxyID}))
chainDBOK(t, "reinsert recovered peer", store.AddSessionProxy(t.Context(), &a, sessionID))
recovered := runtime.waitStatus(t, sessionID, 2, *down.LastSuccessAt)
chainRequireHealth(t, store, a.ProxyID, true)
if !recovered.NextFullAt.Equal(*ready.NextFullAt) || control.Hits(direct) != 6 || control.Hits(first.Source) != 2 {
t.Fatal("early recovery did not complete its authenticated probe and both direct controls")
}
afterRecovery := catalog.exports(t, all, []db.SessionProxy{b, a}, nil)
chainSameURLs(t, initial, afterRecovery)
wireRoundTrip(t, firstClient, origin, first, origin.HTTPSURL, http.MethodGet, nil, []byte("original URL recovered"), false)
proxyAddr := runtime.endpoint.ProxyAddr
runtime.stop(t)
catalog.runtime = startChainRuntime(t, cfg, policy, ca.Roots, proxyAddr)
catalog.runtime.waitStatus(t, sessionID, 2, *recovered.LastSuccessAt)
chainSameURLs(t, initial, catalog.exports(t, all, []db.SessionProxy{b, a}, nil))
wireRoundTrip(t, firstClient, origin, first, origin.HTTPURL, http.MethodGet, nil, []byte("original URL after restart"), true)
wireRoundTrip(t, secondClient, origin, second, origin.HTTPSURL, http.MethodGet, nil, []byte("second URL after restart"), false)
})
}
func openChainDB(t *testing.T, dsn string) (*db.DB, string) {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
admin, err := pgx.Connect(ctx, dsn)
chainDBOK(t, "connect to PostgreSQL fixture", err)
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = admin.Close(ctx)
})
var version int
chainDBOK(t, "read PostgreSQL fixture version", admin.QueryRow(ctx, "SELECT current_setting('server_version_num')::int").Scan(&version))
if version/10_000 != 16 {
t.Fatalf("full-chain fixture needs PostgreSQL 16, got version %d", version)
}
schema := "gateway_chain_" + strings.ToLower(rand.Text())
quoted := pgx.Identifier{schema}.Sanitize()
_, err = admin.Exec(ctx, `CREATE SCHEMA `+quoted)
chainDBOK(t, "create isolated schema", err)
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := admin.Exec(ctx, `DROP SCHEMA `+quoted+` CASCADE`); err != nil {
t.Error("drop isolated gateway schema")
}
})
if u, err := url.Parse(dsn); err == nil && (u.Scheme == "postgres" || u.Scheme == "postgresql") {
q := u.Query()
q.Set("search_path", schema)
u.RawQuery = q.Encode()
dsn = u.String()
} else {
dsn += " search_path=" + schema
}
store, err := db.New(ctx, dsn)
chainDBOK(t, "open isolated gateway store", err)
t.Cleanup(store.Close)
chainDBOK(t, "apply checker schema", store.ApplySchema(ctx))
chainDBOK(t, "configure fixture interval", store.SetSetting(ctx, config.KeyGatewayCheckIntervalMinutes, "15"))
return store, dsn
}
func publishChainSnapshot(t *testing.T, store *db.DB, nodes ...*db.SessionProxy) (int64, time.Time) {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
sessionID, err := store.CreateSession(ctx, "manual")
chainDBOK(t, "stage checker session", err)
for _, node := range nodes {
id, _, err := store.EnsureProxy(ctx, node.CanonicalURL, node.Protocol, node.Host, node.Port, nil, node.SourceName)
chainDBOK(t, "insert fixture proxy", err)
node.ProxyID = id
chainDBOK(t, "stage membership", store.AddSessionProxy(ctx, node, sessionID))
chainDBOK(t, "stage protocol totals", store.BumpProtocolStat(ctx, sessionID, node.Protocol, true))
chainDBOK(t, "stage source totals", store.UpsertSourceStat(ctx, sessionID, node.SourceName, 1, 1))
chainDBOK(t, "stage source passes", store.BumpSourcePassed(ctx, sessionID, node.SourceName))
}
n := len(nodes)
chainDBOK(t, "stage session totals", store.SetSessionTotals(ctx, sessionID, n, n, 0, n))
chainDBOK(t, "stage checker progress", store.UpdateSessionProgress(ctx, sessionID, n, n, 0))
chainDBOK(t, "publish completed snapshot", store.CompleteSession(ctx, sessionID, 1))
session, err := store.GetCurrentSession(ctx)
chainDBOK(t, "read published snapshot", err)
if session == nil || session.ID != sessionID || session.FinishedAt == nil {
t.Fatal("checker did not publish the fixture snapshot")
}
return sessionID, *session.FinishedAt
}
func chainRequireHealth(t *testing.T, store *db.DB, id int64, wantOK bool) {
t.Helper()
var ok, hasLatency bool
chainDBOK(t, "read committed fixture health", store.Pool().QueryRow(t.Context(), `SELECT h.ok, h.latency_ms IS NOT NULL
FROM gateway_node_health h JOIN gateway_candidates c
ON c.proxy_id = h.proxy_id AND c.membership_id = h.tested_membership_id WHERE h.proxy_id = $1`, id).Scan(&ok, &hasLatency))
if ok != wantOK || hasLatency != wantOK {
t.Fatalf("current membership %d health/latency presence = %t/%t, want %t/%t", id, ok, hasLatency, wantOK, wantOK)
}
}
func chainDBOK(t *testing.T, operation string, err error) {
t.Helper()
if err != nil {
// PostgreSQL/driver errors can include secret-bearing input values.
t.Fatalf("%s failed (%T)", operation, err)
}
}
type chainRuntime struct {
endpoint RuntimeEndpoints
client *http.Client
token string
cancel context.CancelFunc
done chan struct{}
err error // Published by closing done.
}
func startChainRuntime(t *testing.T, cfg Config, policy *RoutePolicy, roots *x509.CertPool, proxyAddr string) *chainRuntime {
t.Helper()
ctx, cancel := context.WithCancel(t.Context())
runtime := &chainRuntime{cancel: cancel, done: make(chan struct{}), token: cfg.APIToken}
store, err := db.New(ctx, cfg.DBDSN)
if err != nil {
cancel()
chainDBOK(t, "open runtime database pool", err)
}
endpoints := make(chan RuntimeEndpoints, 1)
go func() {
runtime.err = Run(ctx, store, cfg, RuntimeOptions{
ProxyAddr: proxyAddr, APIAddr: "127.0.0.1:0",
Build: func(_ context.Context, e RuntimeEndpoints) (RuntimeComponents, error) {
host, port, err := net.SplitHostPort(e.ProxyAddr)
if err != nil {
return RuntimeComponents{}, err
}
number, err := strconv.ParseUint(port, 10, 16)
if err != nil {
return RuntimeComponents{}, err
}
bound := cfg
bound.PublicProxyHost, bound.PublicProxyPort = host, uint16(number)
components, err := newRuntimeComponents(store, bound, e, policy, roots)
if err == nil {
endpoints <- e
}
return components, err
},
})
store.Close()
close(runtime.done)
}()
t.Cleanup(func() { runtime.stop(t) })
select {
case runtime.endpoint = <-endpoints:
case <-runtime.done:
t.Fatalf("runtime exited before startup: %v", runtime.err)
case <-time.After(wireTimeout):
t.Fatal("runtime did not build its components")
}
transport := &http.Transport{DisableKeepAlives: true}
t.Cleanup(transport.CloseIdleConnections)
runtime.client = &http.Client{Transport: transport, Timeout: 3 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
return runtime
}
func (r *chainRuntime) stop(t *testing.T) {
t.Helper()
r.cancel()
select {
case <-r.done:
if r.err != nil {
t.Errorf("gateway shutdown: %v", r.err)
}
case <-time.After(15 * time.Second):
t.Error("gateway remained active after shutdown")
}
}
func (r *chainRuntime) get(ctx context.Context, path, token string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+r.endpoint.APIAddr+path, nil)
if err != nil {
return nil, err
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
return r.client.Do(req)
}
func chainRequireForwardStatus(t *testing.T, client *http.Client, origin *testfixture.Origin, peer *testfixture.Peer, want int) {
t.Helper()
x := origin.Expect(t, peer.Source, testfixture.Exchange{Response: []byte("unexpected route")})
connections := origin.Connections()
resp, err := client.Do(newWireRequest(t, t.Context(), origin.HTTPURL, x.Path, http.MethodGet, nil))
if err != nil {
t.Fatalf("gateway error response: %v", wireClientError(err))
}
defer resp.Body.Close()
if resp.StatusCode != want || x.Hits() != 0 || origin.Connections() != connections {
t.Fatalf("proxy status = %d, want %d, or unexpected origin dial", resp.StatusCode, want)
}
}
+336
View File
@@ -0,0 +1,336 @@
//go:build gateway_e2e && linux
package gateway
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"strings"
"testing"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/gateway/testfixture"
)
func TestGatewayE2EWire(t *testing.T) {
xrayBin := os.Getenv("XRAY_BIN")
if xrayBin == "" {
if os.Getenv("CI") != "" {
t.Fatal("XRAY_BIN is required for gateway wire acceptance in CI")
}
t.Skip("XRAY_BIN must point to the pinned Xray reference binary")
}
withWireCA(t, func(ca *testfixture.Authority) {
origin := testfixture.NewOrigin(t, ca, wireOriginName)
upload, download := make([]byte, 256<<10), make([]byte, 256<<10)
if _, err := rand.Read(upload); err != nil {
t.Fatal(err)
}
if _, err := rand.Read(download); err != nil {
t.Fatal(err)
}
cases := testfixture.Cases()
for _, tc := range cases {
t.Run(tc.Name, func(t *testing.T) {
peer := testfixture.StartPeer(t, xrayBin, origin, ca, tc)
base, creds, opens := wireForwarder(t, origin, peer)
client := newWireClient(t, wireProxyURL(base, creds, 1), ca.Roots)
for _, target := range []struct {
name, url string
strip bool
}{
{"http", origin.HTTPURL, true},
{"https-connect", origin.HTTPSURL, false},
} {
t.Run(target.name, func(t *testing.T) {
mark := opens.mark()
wireRoundTrip(t, client, origin, peer, target.url, http.MethodGet, nil, []byte("fixture GET"), target.strip)
wireRoundTrip(t, client, origin, peer, target.url, http.MethodPost, upload, download, target.strip)
opens.requireSince(t, mark, peer.Addr.String(), peer.Addr.String())
})
}
t.Run("truncated-reply", func(t *testing.T) {
mark := opens.mark()
wireTruncatedResponse(t, client, origin, peer)
wireRoundTrip(t, client, origin, peer, origin.HTTPURL, http.MethodGet, nil, []byte("after truncation"), true)
opens.requireSince(t, mark, peer.Addr.String(), peer.Addr.String())
})
})
}
t.Run("selected-peer-only", func(t *testing.T) {
if len(cases) < 2 {
t.Fatal("wire selection test needs two independent peers")
}
first := testfixture.StartPeer(t, xrayBin, origin, ca, cases[0])
second := testfixture.StartPeer(t, xrayBin, origin, ca, cases[1])
if first.Source == second.Source {
t.Fatal("wire peers must use distinct origin-side source IPs")
}
base, creds, opens := wireForwarder(t, origin, first, second)
client1 := newWireClient(t, wireProxyURL(base, creds, 1), ca.Roots)
client2 := newWireClient(t, wireProxyURL(base, creds, 2), ca.Roots)
mark := opens.mark()
wireRoundTrip(t, client1, origin, first, origin.HTTPURL, http.MethodGet, nil, []byte("selected first"), true)
wireRoundTrip(t, client2, origin, second, origin.HTTPURL, http.MethodGet, nil, []byte("selected second"), true)
opens.requireSince(t, mark, first.Addr.String(), second.Addr.String())
t.Run("buffered-connect", func(t *testing.T) {
mark := opens.mark()
wireBufferedConnect(t, base, creds, 1, origin, first)
opens.requireSince(t, mark, first.Addr.String())
})
t.Run("client-cancel", func(t *testing.T) {
mark := opens.mark()
wireClientAbort(t, client1, origin, first)
opens.requireSince(t, mark, first.Addr.String())
})
first.Stop(t)
mark = opens.mark()
connections := origin.Connections()
x := origin.Expect(t, first.Source, testfixture.Exchange{Method: http.MethodGet, Response: []byte("must not arrive")})
request := newWireRequest(t, t.Context(), origin.HTTPURL, x.Path, http.MethodGet, nil)
response, err := client1.Do(request)
if err != nil {
t.Fatalf("request to stopped peer: %v", wireClientError(err))
}
_ = response.Body.Close()
if response.StatusCode != http.StatusBadGateway {
t.Fatalf("stopped peer returned HTTP %d, want 502", response.StatusCode)
}
if x.Hits() != 0 || origin.Connections() != connections {
t.Fatal("request to stopped peer reached origin directly or via another peer")
}
opens.requireSince(t, mark, first.Addr.String())
wireRoundTrip(t, client2, origin, second, origin.HTTPURL, http.MethodGet, nil, []byte("second still healthy"), true)
})
})
}
func wireRoundTrip(t *testing.T, client *http.Client, origin *testfixture.Origin, peer *testfixture.Peer, baseURL, method string, upload, download []byte, strip bool) {
t.Helper()
const endToEnd = "wire-origin-response"
originURL, err := url.Parse(baseURL)
if err != nil {
t.Fatal(err)
}
headers := http.Header{"X-Wire-End-To-End": {endToEnd}}
if strip {
headers.Add("Connection", "X-Wire-Reply-First")
headers.Add("Connection", "X-Wire-Reply-Second")
headers.Set("X-Wire-Reply-First", "hop-by-hop")
headers.Set("X-Wire-Reply-Second", "hop-by-hop")
headers.Set("Proxy-Authenticate", "Basic realm=fixture")
}
x := origin.Expect(t, peer.Source, testfixture.Exchange{
Method: method,
Body: upload,
Response: download,
ResponseHeader: headers,
Check: func(r *http.Request) bool {
return r.Host == originURL.Host && wireOriginHeaders(r)
},
})
request := newWireRequest(t, t.Context(), baseURL, x.Path, method, upload)
if strip {
request.Header.Add("Connection", "X-Wire-Send-First")
request.Header.Add("Connection", "X-Wire-Send-Second")
request.Header.Set("X-Wire-Send-First", "hop-by-hop")
request.Header.Set("X-Wire-Send-Second", "hop-by-hop")
}
response, err := client.Do(request)
if err != nil {
t.Fatalf("%s round-trip: %v (origin hits: %d, verified: %t)", method, wireClientError(err), x.Hits(), x.Verified())
}
defer response.Body.Close()
wireCheckResponse(t, response, download)
if response.Header.Get("X-Wire-End-To-End") != endToEnd {
t.Fatal("end-to-end response header was not forwarded")
}
if strip {
for _, h := range []string{"X-Wire-Reply-First", "X-Wire-Reply-Second", "Proxy-Authenticate"} {
if len(response.Header.Values(h)) > 0 {
t.Errorf("hop-by-hop %s response header was forwarded", h)
}
}
}
wireCheckWitness(t, x)
}
func wireOriginHeaders(r *http.Request) bool {
if r.Header.Get("Authorization") != wireOriginAuth {
return false
}
for _, h := range []string{"Proxy-Authorization", "X-Gateway-Probe", "X-Wire-Send-First", "X-Wire-Send-Second"} {
if len(r.Header.Values(h)) > 0 {
return false
}
}
return true
}
func newWireRequest(t *testing.T, ctx context.Context, baseURL, path, method string, body []byte) *http.Request {
t.Helper()
request, err := http.NewRequestWithContext(ctx, method, strings.TrimSuffix(baseURL, "/")+path, bytes.NewReader(body))
if err != nil {
t.Fatal(wireClientError(err))
}
request.Header.Set("Authorization", wireOriginAuth)
return request
}
func wireClientError(err error) error {
var wrapped *url.Error
if errors.As(err, &wrapped) {
return wrapped.Err
}
return err
}
func wireCheckResponse(t *testing.T, response *http.Response, want []byte) {
t.Helper()
if response.StatusCode != http.StatusOK {
t.Fatalf("origin response HTTP %d, want 200", response.StatusCode)
}
checksum := sha256.New()
n, err := io.Copy(checksum, io.LimitReader(response.Body, int64(len(want))+1))
if err != nil {
t.Fatalf("reading origin response: %v", err)
}
wantSum := sha256.Sum256(want)
if n != int64(len(want)) || !bytes.Equal(checksum.Sum(nil), wantSum[:]) {
t.Fatalf("origin response size or checksum mismatch: received %d, want %d bytes", n, len(want))
}
}
func wireCheckWitness(t *testing.T, x *testfixture.Expectation) {
t.Helper()
if x.Hits() != 1 || !x.Verified() {
t.Fatalf("origin witness failed: hits=%d verified=%t", x.Hits(), x.Verified())
}
}
func wireTruncatedResponse(t *testing.T, client *http.Client, origin *testfixture.Origin, peer *testfixture.Peer) {
t.Helper()
x := origin.Expect(t, peer.Source, testfixture.Exchange{
Method: http.MethodGet, Response: []byte("partial response"), Check: wireOriginHeaders, Truncate: true,
ResponseHeader: http.Header{
"Connection": {"close, X-Wire-Truncated-First", "X-Wire-Truncated-Second"},
"X-Wire-Truncated-First": {"hop-by-hop"},
"X-Wire-Truncated-Second": {"hop-by-hop"},
},
})
request := newWireRequest(t, t.Context(), origin.HTTPURL, x.Path, http.MethodGet, nil)
response, err := client.Do(request)
if err != nil {
t.Fatalf("gateway did not forward truncated response headers: %v", wireClientError(err))
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
t.Fatalf("truncated origin response returned HTTP %d", response.StatusCode)
}
for _, name := range []string{"X-Wire-Truncated-First", "X-Wire-Truncated-Second"} {
if len(response.Header.Values(name)) != 0 {
t.Errorf("gateway forwarded truncated response's hop-by-hop %s header", name)
}
}
_, err = io.Copy(io.Discard, response.Body)
if err == nil {
t.Fatal("truncated response completed without error")
}
var timeout net.Error
if errors.As(err, &timeout) && timeout.Timeout() {
t.Fatalf("truncated response did not abort promptly: %v", wireClientError(err))
}
wireCheckWitness(t, x)
}
func wireBufferedConnect(t *testing.T, proxyURL *url.URL, creds Credentials, id int64, origin *testfixture.Origin, peer *testfixture.Peer) {
t.Helper()
const reply = "received data sent alongside CONNECT"
x := origin.Expect(t, peer.Source, testfixture.Exchange{
Method: http.MethodGet, Response: []byte(reply), Check: wireOriginHeaders,
})
originURL, err := url.Parse(origin.HTTPURL)
if err != nil {
t.Fatal(err)
}
authority := originURL.Host
conn, err := (&net.Dialer{Timeout: wireTimeout}).DialContext(t.Context(), "tcp", proxyURL.Host)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if err := conn.SetDeadline(time.Now().Add(wireTimeout)); err != nil {
t.Fatal(err)
}
basic := base64.StdEncoding.EncodeToString([]byte(wireUsername(id) + ":" + creds.Password(id)))
_, err = fmt.Fprintf(conn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\nProxy-Authorization: Basic %s\r\n\r\nGET %s HTTP/1.1\r\nHost: %s\r\nAuthorization: %s\r\nConnection: close\r\n\r\n",
authority, authority, basic, x.Path, authority, wireOriginAuth)
if err != nil {
t.Fatal(err)
}
reader := bufio.NewReader(conn)
connect, err := http.ReadResponse(reader, &http.Request{Method: http.MethodConnect})
if err != nil {
t.Fatalf("read CONNECT response: %v", err)
}
if connect.StatusCode != http.StatusOK {
t.Fatalf("CONNECT status = %d", connect.StatusCode)
}
response, err := http.ReadResponse(reader, &http.Request{Method: http.MethodGet})
if err != nil {
t.Fatalf("read response to buffered request: %v", err)
}
defer response.Body.Close()
wireCheckResponse(t, response, []byte(reply))
wireCheckWitness(t, x)
}
func wireClientAbort(t *testing.T, client *http.Client, origin *testfixture.Origin, peer *testfixture.Peer) {
t.Helper()
const prefix = "start of streaming reply"
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
closed := make(chan error, 1)
x := origin.Expect(t, peer.Source, testfixture.Exchange{
Method: http.MethodGet, Response: []byte(prefix), Check: wireOriginHeaders,
WaitForCancel: func(ctx context.Context) {
<-ctx.Done()
closed <- ctx.Err()
},
})
request := newWireRequest(t, ctx, origin.HTTPURL, x.Path, http.MethodGet, nil)
response, err := client.Do(request)
if err != nil {
t.Fatalf("start abort test stream: %v", wireClientError(err))
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
t.Fatalf("abort test stream status = %d", response.StatusCode)
}
var received [len(prefix)]byte
if _, err := io.ReadFull(response.Body, received[:]); err != nil || string(received[:]) != prefix {
t.Fatalf("stream did not deliver its prefix: %v", err)
}
wireCheckWitness(t, x)
cancel()
select {
case err := <-closed:
if !errors.Is(err, context.Canceled) {
t.Fatalf("origin stream was not canceled by the client's disconnect: %v", err)
}
case <-time.After(wireTimeout):
t.Fatal("origin stream remained open after client cancellation")
}
}
@@ -0,0 +1,254 @@
//go:build gateway_e2e && linux
package gateway
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"flag"
"io"
"log/slog"
"net"
"net/http"
"net/netip"
"net/url"
"os"
"os/exec"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
"git.eeee.moe/omar/zhguchiy_perchik/internal/dialer"
"git.eeee.moe/omar/zhguchiy_perchik/internal/gateway/testfixture"
)
const (
wireOriginName = "origin.gateway.test"
wireTimeout = 10 * time.Second
wireCAEnv = "GATEWAY_WIRE_E2E_CA"
wireOriginAuth = "Bearer fixture-origin-token"
)
// Run each top-level wire test in a fresh process so crypto/x509 loads the
// generated CA when the unmodified production dialers first use system roots.
func withWireCA(t *testing.T, run func(*testfixture.Authority)) {
t.Helper()
if file := os.Getenv(wireCAEnv); file != "" {
run(testfixture.LoadAuthority(t, file))
return
}
ca := testfixture.NewAuthority(t)
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
ctx := t.Context()
if deadline, ok := t.Deadline(); ok {
var cancel context.CancelFunc
ctx, cancel = context.WithDeadline(ctx, deadline)
defer cancel()
}
filter := "^" + regexp.QuoteMeta(t.Name()) + "$"
if runFlag := flag.Lookup("test.run"); runFlag != nil {
if _, subtests, ok := strings.Cut(runFlag.Value.String(), "/"); ok {
filter += "/" + subtests
}
}
args := []string{"-test.run=" + filter}
if testing.Verbose() {
args = append(args, "-test.v")
}
cmd := exec.CommandContext(ctx, executable, args...)
cmd.WaitDelay = wireTimeout
cmd.Env = append(os.Environ(), wireCAEnv+"="+ca.File, "SSL_CERT_FILE="+ca.File, "SSL_CERT_DIR="+t.TempDir())
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("isolated gateway wire test: %v\n%s", err, output)
}
if testing.Verbose() {
t.Logf("isolated gateway wire test:\n%s", output)
}
}
// newWireRoutePolicy installs only exact fixture routes. The same resolver and
// opener can be passed to a DB-backed ForwardProxy in the catalog acceptance test.
func newWireRoutePolicy(t *testing.T, origin *testfixture.Origin, peers ...*testfixture.Peer) (*RoutePolicy, *wireOpens) {
t.Helper()
httpOrigin, err := url.Parse(origin.HTTPURL)
if err != nil {
t.Fatal(err)
}
httpsOrigin, err := url.Parse(origin.HTTPSURL)
if err != nil {
t.Fatal(err)
}
cfg := Config{
AllowedDestinations: map[string]struct{}{httpOrigin.Host: {}, httpsOrigin.Host: {}},
ProbeURL: httpsOrigin,
}
opens := &wireOpens{allowed: make(map[string]struct{}, len(peers))}
allowedIPs := map[netip.Addr]struct{}{origin.HTTPAddr.Addr(): {}, origin.HTTPSAddr.Addr(): {}}
dns := map[string]netip.Addr{
httpOrigin.Hostname() + ".": origin.HTTPAddr.Addr(),
httpsOrigin.Hostname() + ".": origin.HTTPSAddr.Addr(),
}
for _, peer := range peers {
ip := peer.Addr.Addr()
cfg.UpstreamNetworks = append(cfg.UpstreamNetworks, netip.PrefixFrom(ip, ip.BitLen()))
allowedIPs[ip] = struct{}{}
dns[testfixture.PeerName+"."] = ip
opens.allowed[peer.Addr.String()] = struct{}{}
}
policy := NewRoutePolicy(cfg)
policy.allowIP = func(ip netip.Addr) bool {
_, ok := allowedIPs[ip]
return ip.IsLoopback() && ok
}
policy.localIPs = func() ([]netip.Addr, error) { return nil, nil }
policy.resolveIP = func(_ context.Context, host string) ([]netip.Addr, error) {
if ip, ok := dns[host]; ok {
return []netip.Addr{ip}, nil
}
return nil, errors.New("unexpected fixture DNS name")
}
policy.openTCP = opens.dial
return policy, opens
}
// The test opener records every attempted physical dial, including disallowed
// dials, without granting the gateway process external network access.
type wireOpens struct {
allowed map[string]struct{}
mu sync.Mutex
addrs []string
}
func (o *wireOpens) dial(ctx context.Context, network, address string) (net.Conn, error) {
o.mu.Lock()
o.addrs = append(o.addrs, address)
o.mu.Unlock()
if _, ok := o.allowed[address]; !ok || network != "tcp" {
return nil, errors.New("unexpected fixture socket target")
}
return (&net.Dialer{}).DialContext(ctx, network, address)
}
func (o *wireOpens) mark() int {
o.mu.Lock()
defer o.mu.Unlock()
return len(o.addrs)
}
func (o *wireOpens) requireSince(t *testing.T, mark int, want ...string) {
t.Helper()
o.mu.Lock()
got := slices.Clone(o.addrs[mark:])
o.mu.Unlock()
if !slices.Equal(got, want) {
t.Fatalf("gateway physical dial targets = %v, want %v", got, want)
}
}
// Phase 3 isolates forwarding from storage. The full runtime test can pass a
// real db.DB to NewForwardProxy instead, without changing the network fixtures.
type wireNodes map[int64]db.GatewayNode
func (nodes wireNodes) LookupGatewayNode(_ context.Context, id int64, _ time.Time) (*db.GatewayNode, error) {
node, ok := nodes[id]
if !ok {
return nil, nil
}
return &node, nil
}
func (wireNodes) LookupGatewayProbeNode(context.Context, int64, int64) (*db.GatewayNode, error) {
return nil, errors.New("unexpected probe lookup in wire test")
}
func wireForwarder(t *testing.T, origin *testfixture.Origin, peers ...*testfixture.Peer) (*url.URL, Credentials, *wireOpens) {
t.Helper()
policy, opens := newWireRoutePolicy(t, origin, peers...)
nodes := make(wireNodes, len(peers))
for i, peer := range peers {
id := int64(i) + 1
nodes[id] = db.GatewayNode{ProxyID: id, MembershipID: id, CanonicalURL: peer.URL}
}
creds, err := NewCredentials("96284417-017c-44d8-a494-c5af223fd478", [32]byte{1})
if err != nil {
t.Fatal(err)
}
log := slog.New(slog.NewTextHandler(io.Discard, nil))
proxy := NewForwardProxy(nodes, policy, dialer.NewDispatcher(log, policy.DialUpstream), nil)
return serveWireProxy(t, creds, proxy), creds, opens
}
func serveWireProxy(t *testing.T, creds Credentials, proxy ProxyLifecycle) *url.URL {
t.Helper()
listener, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := gatewayHTTPServer(t.Context(), creds.RequireProxyAuth(proxyFormHandler(proxy)))
done := make(chan error, 1)
go func() { done <- server.Serve(listener) }()
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), wireTimeout)
defer cancel()
if err := proxy.Shutdown(ctx); err != nil {
t.Errorf("forwarder shutdown: %v", err)
}
if err := server.Shutdown(ctx); err != nil {
_ = server.Close()
t.Errorf("proxy listener shutdown: %v", err)
}
select {
case err := <-done:
if !errors.Is(err, http.ErrServerClosed) {
t.Errorf("proxy listener stopped: %v", err)
}
case <-ctx.Done():
t.Error("proxy listener did not stop")
}
})
return &url.URL{Scheme: "http", Host: listener.Addr().String()}
}
func wireUsername(id int64) string {
return "node-" + strconv.FormatInt(id, 10)
}
func wireProxyURL(base *url.URL, creds Credentials, id int64) *url.URL {
authenticated := *base
authenticated.User = url.UserPassword(wireUsername(id), creds.Password(id))
return &authenticated
}
func newWireClient(t *testing.T, proxyURL *url.URL, roots *x509.CertPool) *http.Client {
t.Helper()
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
if network != "tcp" || address != proxyURL.Host {
return nil, errors.New("wire client attempted to bypass its proxy")
}
return (&net.Dialer{}).DialContext(ctx, network, address)
},
TLSClientConfig: &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12},
DisableKeepAlives: true,
}
t.Cleanup(transport.CloseIdleConnections)
return &http.Client{
Transport: transport,
Timeout: wireTimeout,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
+295
View File
@@ -0,0 +1,295 @@
package gateway
import (
"context"
"errors"
"slices"
"sync"
"sync/atomic"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
)
const (
monitorPollInterval = 5 * time.Second
monitorRetryDelay = time.Minute
monitorDBTimeout = 2 * time.Second
monitorWorkers = 8
// An authenticated probe can race a membership replacement. This is an
// internal result, never a runtime failure category or a health sample.
monitorProbeStale db.GatewayErrorCode = "stale"
)
type monitorCandidates interface {
GatewayCandidates(context.Context) (db.GatewayCandidateSnapshot, error)
}
type monitorLease interface {
BeginPass(context.Context, *int64, db.GatewayPassMode, time.Time, int) (*db.GatewayPass, error)
FinishPass(context.Context, *db.GatewayPass, time.Time, []db.GatewayProbeResult, db.GatewayErrorCode) (db.GatewayPassOutcome, error)
Degrade(context.Context, db.GatewayErrorCode) error
RescheduleFull(context.Context, time.Time, int) error
}
type monitorProber interface {
Control(context.Context) db.GatewayErrorCode
Probe(context.Context, db.GatewayCandidate) (db.GatewayProbeResult, db.GatewayErrorCode)
}
// Monitor schedules health probes; the runtime owns the lease and its heartbeat.
type Monitor struct {
store monitorCandidates
lease monitorLease
prober monitorProber
now func() time.Time
}
func NewMonitor(store monitorCandidates, lease monitorLease, prober monitorProber) *Monitor {
return &Monitor{store: store, lease: lease, prober: prober, now: time.Now}
}
// Run starts with a full pass and returns normally when its context is canceled.
// Only lease loss is fatal; other system failures are retried in place.
func (m *Monitor) Run(ctx context.Context) error {
ticker := time.NewTicker(monitorPollInterval)
defer ticker.Stop()
return m.run(ctx, ticker.C)
}
type monitorSchedule struct {
lastFullStarted time.Time
fullInterval int
retryAt time.Time
pendingMode db.GatewayPassMode
unfinished monitorUnfinishedPass
}
type monitorUnfinishedPass struct {
pass *db.GatewayPass
finishedAt time.Time
failure db.GatewayErrorCode
}
func (m *Monitor) run(ctx context.Context, ticks <-chan time.Time) error {
var schedule monitorSchedule
for ctx.Err() == nil {
reconcile, err := m.advance(ctx, &schedule)
if err != nil {
return err
}
if reconcile && ctx.Err() == nil {
// Recheck immediately once, then wait for the next poll if the
// snapshot is still churning instead of spinning on stale passes.
if _, err := m.advance(ctx, &schedule); err != nil {
return err
}
}
select {
case <-ctx.Done():
return nil
case _, ok := <-ticks:
if !ok {
return nil
}
}
}
return nil
}
func (m *Monitor) advance(ctx context.Context, s *monitorSchedule) (bool, error) {
if ctx.Err() != nil || m.now().Before(s.retryAt) {
return false, nil
}
if old := s.unfinished; old.pass != nil {
// A rolled-back finish leaves the lease's pass token active. Close
// it as degraded before allowing any new pass, never replay health.
_, err := m.finish(ctx, old.pass, old.finishedAt, nil, old.failure)
if errors.Is(err, db.ErrGatewayLeaseLost) {
return false, db.ErrGatewayLeaseLost
}
if err != nil {
s.retryAt = m.now().Add(monitorRetryDelay)
return false, nil
}
s.unfinished = monitorUnfinishedPass{}
}
callCtx, cancel := context.WithTimeout(ctx, monitorDBTimeout)
snapshot, err := m.store.GatewayCandidates(callCtx)
cancel()
if err != nil {
return false, m.degrade(ctx, s, err)
}
if ctx.Err() != nil {
return false, nil
}
interval := snapshot.IntervalMinutes
if !s.lastFullStarted.IsZero() && interval != s.fullInterval {
callCtx, cancel := context.WithTimeout(ctx, monitorDBTimeout)
err := m.lease.RescheduleFull(callCtx, s.lastFullStarted, interval)
cancel()
if err != nil {
return false, m.degrade(ctx, s, err)
}
s.fullInterval = interval
}
startedAt := m.now()
mode := s.pendingMode
candidates := snapshot.Candidates
nextFullAt := s.lastFullStarted.Add(time.Duration(interval) * time.Minute)
if s.lastFullStarted.IsZero() || !startedAt.Before(nextFullAt) || mode == db.GatewayPassFull {
mode = db.GatewayPassFull
} else {
candidates = slices.DeleteFunc(candidates, func(c db.GatewayCandidate) bool {
return c.TestedMembershipID != nil && *c.TestedMembershipID == c.MembershipID
})
if len(candidates) == 0 && mode == "" {
return false, nil
}
mode = db.GatewayPassEarly
}
if ctx.Err() != nil {
return false, nil
}
callCtx, cancel = context.WithTimeout(ctx, monitorDBTimeout)
pass, err := m.lease.BeginPass(callCtx, snapshot.SessionID, mode, startedAt, interval)
cancel()
if err != nil {
s.pendingMode = mode
return false, m.degrade(ctx, s, err)
}
if mode == db.GatewayPassFull {
s.lastFullStarted, s.fullInterval = startedAt, interval
}
results, failure := m.measure(ctx, candidates)
if ctx.Err() != nil {
failure = db.GatewayErrorInterrupted
}
finishedAt := m.now()
outcome, err := m.finish(ctx, pass, finishedAt, results, failure)
if errors.Is(err, db.ErrGatewayLeaseLost) {
return false, db.ErrGatewayLeaseLost
}
if err != nil && failure == "" {
failure = db.GatewayErrorDatabase
if ctx.Err() != nil {
failure = db.GatewayErrorInterrupted
}
_, err = m.finish(ctx, pass, finishedAt, nil, failure)
if errors.Is(err, db.ErrGatewayLeaseLost) {
return false, db.ErrGatewayLeaseLost
}
}
if failure != "" {
if err != nil {
s.unfinished = monitorUnfinishedPass{pass: pass, finishedAt: finishedAt, failure: failure}
}
s.pendingMode = mode
s.retryAt = m.now().Add(monitorRetryDelay)
return false, nil
}
s.pendingMode = ""
s.retryAt = time.Time{}
if !outcome.SessionCurrent {
// Reconcile even an empty replacement session, without moving the
// full-pass anchor just because the session pointer moved.
s.pendingMode = db.GatewayPassEarly
return true, nil
}
return len(results) != len(candidates) || outcome.Applied < int64(len(results)), nil
}
func (m *Monitor) degrade(ctx context.Context, s *monitorSchedule, err error) error {
if errors.Is(err, db.ErrGatewayLeaseLost) {
return db.ErrGatewayLeaseLost
}
if ctx.Err() != nil {
return nil
}
failure := db.GatewayErrorDatabase
if errors.Is(err, db.ErrGatewayConfig) {
failure = db.GatewayErrorConfig
}
callCtx, cancel := context.WithTimeout(ctx, monitorDBTimeout)
defer cancel()
if errors.Is(m.lease.Degrade(callCtx, failure), db.ErrGatewayLeaseLost) {
return db.ErrGatewayLeaseLost
}
if s.pendingMode == "" {
s.pendingMode = db.GatewayPassEarly
}
s.retryAt = m.now().Add(monitorRetryDelay)
return nil
}
func (m *Monitor) finish(ctx context.Context, pass *db.GatewayPass, at time.Time, results []db.GatewayProbeResult, failure db.GatewayErrorCode) (db.GatewayPassOutcome, error) {
if failure != "" {
// Permit bounded status-only cleanup on shutdown. A canceled pass
// must never use a detached context to write health samples.
ctx, results = context.WithoutCancel(ctx), nil
}
callCtx, cancel := context.WithTimeout(ctx, monitorDBTimeout)
defer cancel()
return m.lease.FinishPass(callCtx, pass, at, results, failure)
}
func (m *Monitor) measure(ctx context.Context, candidates []db.GatewayCandidate) ([]db.GatewayProbeResult, db.GatewayErrorCode) {
if ctx.Err() != nil {
return nil, db.GatewayErrorInterrupted
}
if len(candidates) == 0 {
return nil, ""
}
if failure := m.prober.Control(ctx); failure != "" {
return nil, failure
}
probes, stop := context.WithCancel(ctx)
defer stop()
results := make([]db.GatewayProbeResult, len(candidates))
var (
workers sync.WaitGroup
next atomic.Int64
once sync.Once
failure db.GatewayErrorCode
)
for range min(monitorWorkers, len(candidates)) {
workers.Go(func() {
for probes.Err() == nil {
i := next.Add(1) - 1
if i >= int64(len(candidates)) {
return
}
result, code := m.prober.Probe(probes, candidates[i])
switch code {
case "":
results[i] = result
case monitorProbeStale:
// No observation for this membership; reconcile after commit.
default:
once.Do(func() {
failure = code
stop()
})
return
}
}
})
}
workers.Wait()
if ctx.Err() != nil {
return nil, db.GatewayErrorInterrupted
}
if failure != "" {
return nil, failure
}
if failure := m.prober.Control(ctx); failure != "" {
return nil, failure
}
return slices.DeleteFunc(results, func(result db.GatewayProbeResult) bool { return result.ProxyID == 0 }), ""
}
+148
View File
@@ -0,0 +1,148 @@
package gateway
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"errors"
"net"
"net/http"
"net/netip"
"net/url"
"strconv"
"sync/atomic"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
)
type httpGatewayProber struct {
endpoint *url.URL
proxyURL url.URL
credentials Credentials
tickets *probeTickets
roots *x509.CertPool
control http.Transport
}
// roots is nil in production (system trust). A fixture may install its own CA;
// certificate chains and names are always verified against the same endpoint.
func newHTTPGatewayProber(endpoint *url.URL, proxyAddr string, credentials Credentials, tickets *probeTickets,
dialControl func(context.Context, string, string) (net.Conn, error), roots *x509.CertPool,
) (*httpGatewayProber, error) {
if endpoint == nil || tickets == nil || credentials.storePrefix == "" || dialControl == nil {
return nil, errors.New("incomplete gateway probe configuration")
}
validated, ok := parseGatewayProbeURL(endpoint.String())
if !ok || *validated != *endpoint || validated.Host != tickets.authority {
return nil, errors.New("invalid gateway probe endpoint")
}
proxy, err := netip.ParseAddrPort(proxyAddr)
if err != nil || proxy.Port() == 0 || proxy.Addr().Zone() != "" || proxy.Addr().Is4In6() || !proxy.Addr().IsLoopback() {
return nil, errors.New("gateway probe proxy must be a bound loopback address")
}
return &httpGatewayProber{
endpoint: validated,
proxyURL: url.URL{Scheme: "http", Host: proxy.String()},
credentials: credentials,
tickets: tickets,
roots: roots,
control: http.Transport{
DialContext: dialControl,
TLSClientConfig: &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12},
DisableKeepAlives: true,
DisableCompression: true,
MaxResponseHeaderBytes: 32 << 10,
},
}, nil
}
func (p *httpGatewayProber) Control(ctx context.Context) db.GatewayErrorCode {
attempt, cancel := context.WithTimeout(ctx, probeTicketTTL)
defer cancel()
ok := p.checkHTTPS(attempt, &p.control)
if ctx.Err() != nil {
return db.GatewayErrorInterrupted
}
if !ok {
return db.GatewayErrorControl
}
return ""
}
func (p *httpGatewayProber) Probe(ctx context.Context, candidate db.GatewayCandidate) (db.GatewayProbeResult, db.GatewayErrorCode) {
attempt, cancel := context.WithTimeout(ctx, probeTicketTTL)
defer cancel()
ticket, revoke, err := p.tickets.issue(attempt, candidate.ProxyID, candidate.MembershipID)
if err != nil {
if ctx.Err() != nil {
return db.GatewayProbeResult{}, db.GatewayErrorInterrupted
}
return db.GatewayProbeResult{}, db.GatewayErrorProbe
}
defer revoke()
login := nodeUsernamePrefix + strconv.FormatInt(candidate.ProxyID, 10) + ":" + p.credentials.Password(candidate.ProxyID)
var connectStatus atomic.Int32
transport := http.Transport{
Proxy: http.ProxyURL(&p.proxyURL),
TLSClientConfig: &tls.Config{RootCAs: p.roots, MinVersion: tls.VersionTLS12},
ProxyConnectHeader: http.Header{
"Proxy-Authorization": {"Basic " + base64.StdEncoding.EncodeToString([]byte(login))},
probeTicketHeader: {ticket},
},
OnProxyConnectResponse: func(_ context.Context, _ *url.URL, _ *http.Request, resp *http.Response) error {
connectStatus.Store(int32(resp.StatusCode))
return nil
},
DisableKeepAlives: true,
DisableCompression: true,
MaxResponseHeaderBytes: 32 << 10,
}
started := time.Now()
ok := p.checkHTTPS(attempt, &transport)
finished := time.Now()
if ctx.Err() != nil {
return db.GatewayProbeResult{}, db.GatewayErrorInterrupted
}
result := db.GatewayProbeResult{
ProxyID: candidate.ProxyID,
MembershipID: candidate.MembershipID,
CheckedAt: finished,
}
switch connectStatus.Load() {
case http.StatusOK:
if ok {
result.OK = true
result.LatencyMS = int32(finished.Sub(started).Milliseconds())
}
return result, ""
case http.StatusBadGateway, http.StatusGatewayTimeout:
// The local listener reached this node's setup and reported its failure.
return result, ""
case http.StatusConflict:
return db.GatewayProbeResult{}, monitorProbeStale
default:
// No CONNECT status, an auth rejection, DB failure, route policy
// failure, or exhausted local budget is not evidence about a node.
return db.GatewayProbeResult{}, db.GatewayErrorProbe
}
}
func (p *httpGatewayProber) checkHTTPS(ctx context.Context, transport *http.Transport) bool {
req := (&http.Request{
Method: http.MethodGet,
URL: p.endpoint,
Host: p.endpoint.Host,
Header: make(http.Header),
}).WithContext(ctx)
// RoundTrip does not follow redirects. Do not propagate transport errors,
// CONNECT status text or response bodies into runtime status or logs.
resp, err := transport.RoundTrip(req)
if err != nil {
return false
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusNoContent && resp.TLS != nil && len(resp.TLS.VerifiedChains) != 0 && ctx.Err() == nil
}
+365
View File
@@ -0,0 +1,365 @@
package gateway
import (
"context"
"crypto/x509"
"errors"
"io"
"log"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"net/url"
"strconv"
"sync/atomic"
"testing"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
"git.eeee.moe/omar/zhguchiy_perchik/internal/upstream"
)
const monitorHTTPPath = "/probe/health"
func monitorHTTPOrigin(t *testing.T, hostname string, handler http.HandlerFunc) (*url.URL, *x509.CertPool, netip.AddrPort) {
t.Helper()
origin := httptest.NewUnstartedServer(handler)
origin.Config.ErrorLog = log.New(io.Discard, "", 0) // intentional negative TLS probes
origin.StartTLS()
t.Cleanup(origin.Close)
addr := origin.Listener.Addr().(*net.TCPAddr).AddrPort()
endpoint, ok := parseGatewayProbeURL("https://" + net.JoinHostPort(hostname, strconv.Itoa(int(addr.Port()))) + monitorHTTPPath)
if !ok {
t.Fatal("invalid monitor HTTPS fixture URL")
}
roots := x509.NewCertPool()
roots.AddCert(origin.Certificate())
return endpoint, roots, addr
}
func monitorHTTPPolicy(t *testing.T, endpoint *url.URL, addr netip.AddrPort) *RoutePolicy {
t.Helper()
policy := NewRoutePolicy(Config{ProbeURL: endpoint, AllowedDestinations: map[string]struct{}{endpoint.Host: {}}})
policy.resolveIP = func(_ context.Context, name string) ([]netip.Addr, error) {
if name != endpoint.Hostname()+"." {
t.Error("monitor attempted to resolve a different hostname")
return nil, errors.New("unexpected fixture DNS name")
}
return []netip.Addr{addr.Addr()}, nil
}
policy.localIPs = func() ([]netip.Addr, error) { return nil, nil }
policy.allowIP = func(ip netip.Addr) bool { return ip.IsLoopback() && ip == addr.Addr() }
policy.openTCP = func(ctx context.Context, network, destination string) (net.Conn, error) {
if network != "tcp" || destination != addr.String() {
t.Error("monitor attempted to open a different TCP route")
return nil, errors.New("unexpected fixture socket")
}
return (&net.Dialer{}).DialContext(ctx, network, destination)
}
return policy
}
func monitorHTTPProber(t *testing.T, endpoint *url.URL, peerAddr string, credentials Credentials, tickets *probeTickets, policy *RoutePolicy, roots *x509.CertPool) *httpGatewayProber {
t.Helper()
p, err := newHTTPGatewayProber(endpoint, peerAddr, credentials, tickets, policy.DialControl, roots)
if err != nil {
t.Fatal(err)
}
return p
}
func monitorHTTPNode(t *testing.T, candidate db.GatewayCandidate, endpoint *url.URL, policy *RoutePolicy, dial forwardTestDial) (*ForwardProxy, *probeTickets) {
t.Helper()
tickets := newProbeTickets(endpoint.Host)
store := forwardTestStore{
ready: func(_ int64) (*db.GatewayNode, error) {
t.Error("monitor CONNECT fell back to ordinary readiness lookup")
return nil, nil
},
probe: func(id, membership int64) (*db.GatewayNode, error) {
if id != candidate.ProxyID || membership != candidate.MembershipID {
t.Error("CONNECT did not use the selected node credentials and ticket membership")
return nil, nil
}
return forwardTestNode(id, membership), nil
},
}
return NewForwardProxy(store, policy, dial, tickets), tickets
}
func TestHTTPGatewayProberRoundTrip(t *testing.T) {
var originRequests, connections, peerDials, directDials atomic.Int32
endpoint, roots, origin := monitorHTTPOrigin(t, "example.com", func(w http.ResponseWriter, r *http.Request) {
originRequests.Add(1)
local := r.Context().Value(http.LocalAddrContextKey).(*net.TCPAddr)
if r.Method != http.MethodGet || r.URL.Path != monitorHTTPPath || r.URL.RawQuery != "" ||
r.Host != net.JoinHostPort("example.com", strconv.Itoa(local.Port)) || r.TLS.ServerName != "example.com" {
t.Error("monitor used an unexpected HTTPS endpoint")
}
if r.Header.Get("Proxy-Authorization") != "" || r.Header.Get(probeTicketHeader) != "" || r.Header.Get("Authorization") != "" {
t.Error("monitor sent proxy credentials or a ticket to the origin")
}
w.WriteHeader(http.StatusNoContent)
})
policy := monitorHTTPPolicy(t, endpoint, origin)
open := policy.openTCP
policy.openTCP = func(ctx context.Context, network, addr string) (net.Conn, error) {
connections.Add(1)
return open(ctx, network, addr)
}
candidate := db.GatewayCandidate{ProxyID: 42, MembershipID: 511}
forward, tickets := monitorHTTPNode(t, candidate, endpoint, policy, func(ctx context.Context, up *upstream.Upstream, dest string) (net.Conn, error) {
if up.Host != "peer42.fixture" || dest != origin.String() {
t.Error("monitor used the wrong node or did not use the checked destination")
return nil, errors.New("unexpected fixture node or route")
}
peerDials.Add(1)
return policy.openTCP(ctx, "tcp", dest)
})
proxyAddr, credentials := serveForwardTest(t, forward)
prober, err := newHTTPGatewayProber(endpoint, proxyAddr, credentials, tickets, func(ctx context.Context, network, addr string) (net.Conn, error) {
if addr != endpoint.Host {
t.Error("direct control did not use the approved authority")
}
directDials.Add(1)
return policy.DialControl(ctx, network, addr)
}, roots)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), forwardTestDeadline)
defer cancel()
if code := prober.Control(ctx); code != "" {
t.Fatalf("control beforehand failed: %q", code)
}
for range 2 {
started := time.Now()
got, code := prober.Probe(ctx, candidate)
if code != "" || !got.OK || got.ProxyID != candidate.ProxyID || got.MembershipID != candidate.MembershipID {
t.Fatalf("probe got %+v, %q; want positive measurement of the exact candidate", got, code)
}
if got.CheckedAt.Before(started) || got.CheckedAt.After(time.Now()) || got.LatencyMS < 0 ||
time.Duration(got.LatencyMS)*time.Millisecond > got.CheckedAt.Sub(started) {
t.Fatalf("probe reported invalid completion or monotonic latency: %+v", got)
}
}
if code := prober.Control(ctx); code != "" {
t.Fatalf("control afterward failed: %q", code)
}
if got, direct, viaPeer, conns := originRequests.Load(), directDials.Load(), peerDials.Load(), connections.Load(); got != 4 || direct != 2 || viaPeer != 2 || conns != 4 {
t.Fatalf("expected two fresh direct routes and two fresh tunnels: requests=%d direct=%d peer=%d conns=%d", got, direct, viaPeer, conns)
}
}
func TestHTTPGatewayProberRejectsInvalidHTTPS(t *testing.T) {
for _, tc := range []struct {
name, host string
status int
unknownCA bool
}{
{name: "redirect", host: "example.com", status: http.StatusFound},
{name: "not-204", host: "example.com", status: http.StatusOK},
{name: "wrong-tls-name", host: "wrong.monitor.test", status: http.StatusNoContent},
{name: "unknown-tls-ca", host: "example.com", status: http.StatusNoContent, unknownCA: true},
} {
t.Run(tc.name, func(t *testing.T) {
var hits, redirects atomic.Int32
endpoint, roots, origin := monitorHTTPOrigin(t, tc.host, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != monitorHTTPPath {
redirects.Add(1)
w.WriteHeader(http.StatusNoContent)
return
}
hits.Add(1)
if tc.status == http.StatusFound {
w.Header().Set("Location", "/redirect")
}
w.WriteHeader(tc.status)
})
if tc.unknownCA {
roots = x509.NewCertPool()
}
policy := monitorHTTPPolicy(t, endpoint, origin)
candidate := db.GatewayCandidate{ProxyID: 7, MembershipID: 29}
forward, tickets := monitorHTTPNode(t, candidate, endpoint, policy, func(ctx context.Context, _ *upstream.Upstream, dest string) (net.Conn, error) {
return policy.openTCP(ctx, "tcp", dest)
})
addr, credentials := serveForwardTest(t, forward)
prober := monitorHTTPProber(t, endpoint, addr, credentials, tickets, policy, roots)
ctx, cancel := context.WithTimeout(t.Context(), forwardTestDeadline)
defer cancel()
if code := prober.Control(ctx); code != db.GatewayErrorControl {
t.Errorf("direct check returned code %q, want control", code)
}
got, code := prober.Probe(ctx, candidate)
if code != "" || got.OK || got.CheckedAt.IsZero() || got.LatencyMS != 0 {
t.Fatalf("after a successful CONNECT got %+v, %q; want a negative node measurement", got, code)
}
wantHits := int32(2)
if tc.unknownCA || tc.host != "example.com" {
wantHits = 0
}
if hits.Load() != wantHits || redirects.Load() != 0 {
t.Fatalf("HTTPS handler hits=%d, redirect hits=%d; want %d, 0", hits.Load(), redirects.Load(), wantHits)
}
})
}
}
func TestHTTPGatewayProberClassifiesConnectFailure(t *testing.T) {
for _, tc := range []struct {
name string
wantCode db.GatewayErrorCode
wantDial bool
}{
{name: "local-auth", wantCode: db.GatewayErrorProbe},
{name: "local-capacity", wantCode: db.GatewayErrorProbe},
{name: "db-error", wantCode: db.GatewayErrorProbe},
{name: "stale-membership", wantCode: monitorProbeStale},
{name: "route-resolution", wantCode: db.GatewayErrorProbe},
{name: "selected-node-reset", wantDial: true},
{name: "selected-node-timeout", wantDial: true},
} {
t.Run(tc.name, func(t *testing.T) {
endpoint, ok := parseGatewayProbeURL("https://control.monitor.test" + monitorHTTPPath)
if !ok {
t.Fatal("invalid fixed probe URL")
}
candidate := db.GatewayCandidate{ProxyID: 3, MembershipID: 44}
store := forwardTestStore{probe: func(id, membership int64) (*db.GatewayNode, error) {
switch tc.name {
case "db-error":
return nil, errors.New("fixture DB error")
case "stale-membership":
return nil, nil
default:
return forwardTestNode(id, membership), nil
}
}}
var dialed atomic.Bool
tickets := newProbeTickets(endpoint.Host)
forward := newForwardTestProxy(store, func(_ context.Context, _ *upstream.Upstream, _ string) (net.Conn, error) {
dialed.Store(true)
if tc.name == "selected-node-timeout" {
return nil, context.DeadlineExceeded
}
return nil, errors.New("selected fixture node unavailable")
}, tickets, "127.0.0.1:1")
if tc.name == "route-resolution" {
forward.resolveRequest = func(context.Context, *http.Request) (string, string, error) {
return "", "", context.DeadlineExceeded
}
}
if tc.name == "local-capacity" {
for range cap(forward.probes) {
forward.probes <- struct{}{}
}
}
addr, credentials := serveForwardTest(t, forward)
if tc.name == "local-auth" {
credentials.secret = [32]byte{2}
}
prober, err := newHTTPGatewayProber(endpoint, addr, credentials, tickets, func(context.Context, string, string) (net.Conn, error) {
t.Error("failed CONNECT attempted a direct request")
return nil, errors.New("unexpected direct request")
}, nil)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), forwardTestDeadline)
defer cancel()
got, code := prober.Probe(ctx, candidate)
if code != tc.wantCode || got.OK || dialed.Load() != tc.wantDial {
t.Fatalf("result=%+v code=%q dial=%t; want code=%q dial=%t", got, code, dialed.Load(), tc.wantCode, tc.wantDial)
}
if tc.wantCode == "" {
if got.CheckedAt.IsZero() || got.ProxyID != candidate.ProxyID || got.MembershipID != candidate.MembershipID {
t.Fatalf("confirmed node failure did not record the exact candidate: %+v", got)
}
} else if got != (db.GatewayProbeResult{}) {
t.Fatalf("shared failure emitted a measurement: %+v", got)
}
tickets.mu.Lock()
active := len(tickets.active)
tickets.mu.Unlock()
if active != 0 {
t.Fatal("failed probe retained an active ticket")
}
})
}
}
func TestHTTPGatewayProberMissingConnectStatus(t *testing.T) {
var seen atomic.Bool
listener := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen.Store(true)
if r.Method != http.MethodConnect {
t.Error("expected a loopback CONNECT")
}
conn, _, err := http.NewResponseController(w).Hijack()
if err != nil {
t.Error(err)
return
}
_ = conn.Close()
}))
t.Cleanup(listener.Close)
endpoint, ok := parseGatewayProbeURL("https://control.monitor.test" + monitorHTTPPath)
if !ok {
t.Fatal("invalid fixed probe URL")
}
credentials, err := NewCredentials("838e3104-6966-4644-b625-932c6e6f62a9", [32]byte{1})
if err != nil {
t.Fatal(err)
}
tickets := newProbeTickets(endpoint.Host)
prober, err := newHTTPGatewayProber(endpoint, listener.Listener.Addr().String(), credentials, tickets, func(context.Context, string, string) (net.Conn, error) {
t.Error("CONNECT failure attempted a direct route")
return nil, errors.New("unexpected direct route")
}, nil)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), forwardTestDeadline)
defer cancel()
got, code := prober.Probe(ctx, db.GatewayCandidate{ProxyID: 5, MembershipID: 53})
if !seen.Load() || code != db.GatewayErrorProbe || got != (db.GatewayProbeResult{}) {
t.Fatalf("abrupt loopback close emitted %+v, %q, seen=%t", got, code, seen.Load())
}
}
func TestHTTPGatewayProberAbortClosesTunnel(t *testing.T) {
started, originCanceled := make(chan struct{}), make(chan struct{})
endpoint, roots, origin := monitorHTTPOrigin(t, "example.com", func(_ http.ResponseWriter, r *http.Request) {
close(started)
<-r.Context().Done()
close(originCanceled)
})
policy := monitorHTTPPolicy(t, endpoint, origin)
candidate := db.GatewayCandidate{ProxyID: 8, MembershipID: 81}
forward, tickets := monitorHTTPNode(t, candidate, endpoint, policy, func(ctx context.Context, _ *upstream.Upstream, dest string) (net.Conn, error) {
return policy.openTCP(ctx, "tcp", dest)
})
addr, credentials := serveForwardTest(t, forward)
prober := monitorHTTPProber(t, endpoint, addr, credentials, tickets, policy, roots)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
type outcome struct {
result db.GatewayProbeResult
code db.GatewayErrorCode
}
finished := make(chan outcome, 1)
go func() {
result, code := prober.Probe(ctx, candidate)
finished <- outcome{result: result, code: code}
}()
forwardTestReceive(t, started)
cancel()
got := forwardTestReceive(t, finished)
if got.code != db.GatewayErrorInterrupted || got.result != (db.GatewayProbeResult{}) {
t.Fatalf("cancelled CONNECT probe produced %+v", got)
}
forwardTestReceive(t, originCanceled)
}
+553
View File
@@ -0,0 +1,553 @@
package gateway
import (
"context"
"errors"
"fmt"
"slices"
"testing"
"testing/synctest"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
)
type monitorTestStore struct {
snapshot db.GatewayCandidateSnapshot
readErr error
beginErr error
reads int
passes []monitorTestPass
active *db.GatewayPass
finishes []monitorTestFinish
degraded []db.GatewayErrorCode
reschedules []time.Time
health map[int64]db.GatewayProbeResult
beforeFinish func(monitorTestFinish) error
}
type monitorTestPass struct {
sessionID int64
mode db.GatewayPassMode
startedAt time.Time
interval int
}
type monitorTestFinish struct {
at time.Time
results []db.GatewayProbeResult
failure db.GatewayErrorCode
}
func (s *monitorTestStore) GatewayCandidates(ctx context.Context) (db.GatewayCandidateSnapshot, error) {
s.reads++
if err := ctx.Err(); err != nil {
return db.GatewayCandidateSnapshot{}, err
}
out := s.snapshot
out.Candidates = slices.Clone(out.Candidates)
for i, c := range out.Candidates {
if _, ok := s.health[c.ProxyID]; ok {
membership := s.health[c.ProxyID].MembershipID
out.Candidates[i].TestedMembershipID = &membership
}
}
return out, s.readErr
}
func (s *monitorTestStore) BeginPass(ctx context.Context, session *int64, mode db.GatewayPassMode, at time.Time, interval int) (*db.GatewayPass, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if s.active != nil {
return nil, errors.New("overlapping pass")
}
if s.beginErr != nil {
return nil, s.beginErr
}
s.passes = append(s.passes, monitorTestPass{monitorSessionID(session), mode, at, interval})
s.active = new(db.GatewayPass)
return s.active, nil
}
func (s *monitorTestStore) FinishPass(ctx context.Context, pass *db.GatewayPass, at time.Time, results []db.GatewayProbeResult, failure db.GatewayErrorCode) (db.GatewayPassOutcome, error) {
if err := ctx.Err(); err != nil {
return db.GatewayPassOutcome{}, err
}
if pass == nil || pass != s.active {
return db.GatewayPassOutcome{}, errors.New("finish without matching pass")
}
finish := monitorTestFinish{at, slices.Clone(results), failure}
s.finishes = append(s.finishes, finish)
if s.beforeFinish != nil {
if err := s.beforeFinish(finish); err != nil {
return db.GatewayPassOutcome{}, err
}
}
s.active = nil
if failure != "" {
return db.GatewayPassOutcome{}, nil
}
out := db.GatewayPassOutcome{SessionCurrent: s.passes[len(s.passes)-1].sessionID == monitorSessionID(s.snapshot.SessionID)}
if out.SessionCurrent {
for _, r := range results {
for _, c := range s.snapshot.Candidates {
if c.ProxyID == r.ProxyID && c.MembershipID == r.MembershipID {
s.health[r.ProxyID] = r
out.Applied++
break
}
}
}
}
return out, nil
}
func (s *monitorTestStore) Degrade(_ context.Context, failure db.GatewayErrorCode) error {
s.degraded = append(s.degraded, failure)
return nil
}
func (s *monitorTestStore) RescheduleFull(_ context.Context, start time.Time, interval int) error {
s.reschedules = append(s.reschedules, start.Add(time.Duration(interval)*time.Minute))
return nil
}
func monitorSessionID(id *int64) int64 {
if id == nil {
return 0
}
return *id
}
func monitorSnapshot(session int64, interval int, candidates ...db.GatewayCandidate) db.GatewayCandidateSnapshot {
out := db.GatewayCandidateSnapshot{IntervalMinutes: interval, Candidates: candidates}
if session != 0 {
out.SessionID = &session
}
return out
}
func monitorCandidate(id, membership int64) db.GatewayCandidate {
return db.GatewayCandidate{ProxyID: id, MembershipID: membership}
}
type monitorTestProber struct {
controls int
control func(int) db.GatewayErrorCode
probe func(context.Context, db.GatewayCandidate) (db.GatewayProbeResult, db.GatewayErrorCode)
}
func (p *monitorTestProber) Control(_ context.Context) db.GatewayErrorCode {
p.controls++
if p.control != nil {
return p.control(p.controls)
}
return ""
}
func (p *monitorTestProber) Probe(ctx context.Context, c db.GatewayCandidate) (db.GatewayProbeResult, db.GatewayErrorCode) {
if p.probe != nil {
return p.probe(ctx, c)
}
return monitorObservation(c, time.Now(), true), ""
}
func monitorObservation(c db.GatewayCandidate, at time.Time, ok bool) db.GatewayProbeResult {
return db.GatewayProbeResult{ProxyID: c.ProxyID, MembershipID: c.MembershipID, CheckedAt: at, OK: ok}
}
var monitorTestEpoch = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
func monitorFixture(snapshot db.GatewayCandidateSnapshot) (*Monitor, *monitorTestStore, *monitorTestProber, *time.Time) {
now := monitorTestEpoch
store := &monitorTestStore{snapshot: snapshot, health: make(map[int64]db.GatewayProbeResult)}
prober := new(monitorTestProber)
monitor := NewMonitor(store, store, prober)
monitor.now = func() time.Time { return now }
return monitor, store, prober, &now
}
func monitorAdvance(t *testing.T, m *Monitor, schedule *monitorSchedule) {
t.Helper()
if reconcile, err := m.advance(t.Context(), schedule); err != nil || reconcile {
t.Fatalf("advance = (%t, %v), want no reconciliation or error", reconcile, err)
}
}
func TestMonitorFullIntervalAndSameSessionEarlyPass(t *testing.T) {
m, store, prober, now := monitorFixture(monitorSnapshot(1, 20, monitorCandidate(1, 11), monitorCandidate(2, 12)))
var schedule monitorSchedule
prober.probe = func(_ context.Context, c db.GatewayCandidate) (db.GatewayProbeResult, db.GatewayErrorCode) {
return monitorObservation(c, *now, c.MembershipID != 21), ""
}
monitorAdvance(t, m, &schedule)
*now = now.Add(5 * time.Second)
store.snapshot = monitorSnapshot(1, 20, monitorCandidate(1, 21), monitorCandidate(2, 12))
monitorAdvance(t, m, &schedule)
if got := store.finishes[1].results; len(got) != 1 || got[0].MembershipID != 21 || got[0].OK {
t.Fatalf("early reinsert measurement = %+v", got)
}
*now = now.Add(5 * time.Second)
monitorAdvance(t, m, &schedule) // committed down membership is not an early candidate
*now = monitorTestEpoch.Add(20 * time.Minute)
monitorAdvance(t, m, &schedule)
wantPasses := []monitorTestPass{
{1, db.GatewayPassFull, monitorTestEpoch, 20},
{1, db.GatewayPassEarly, monitorTestEpoch.Add(5 * time.Second), 20},
{1, db.GatewayPassFull, monitorTestEpoch.Add(20 * time.Minute), 20},
}
if !slices.Equal(store.passes, wantPasses) || len(store.finishes[2].results) != 2 || prober.controls != 6 {
t.Fatalf("passes = %+v, finishes = %+v, controls = %d", store.passes, store.finishes, prober.controls)
}
}
func TestMonitorReschedulesFromFullStartAndCatchesUpOnlyOnce(t *testing.T) {
m, store, prober, now := monitorFixture(monitorSnapshot(0, 15))
var schedule monitorSchedule
monitorAdvance(t, m, &schedule)
*now = now.Add(10 * time.Minute)
store.snapshot = monitorSnapshot(2, 30) // valid empty current; no control traffic
monitorAdvance(t, m, &schedule)
*now = monitorTestEpoch.Add(20 * time.Minute)
monitorAdvance(t, m, &schedule)
*now = monitorTestEpoch.Add(25 * time.Minute)
store.snapshot.IntervalMinutes = 20
monitorAdvance(t, m, &schedule)
*now = monitorTestEpoch.Add(95 * time.Minute)
monitorAdvance(t, m, &schedule)
monitorAdvance(t, m, &schedule)
wantPasses := []monitorTestPass{
{0, db.GatewayPassFull, monitorTestEpoch, 15},
{2, db.GatewayPassFull, monitorTestEpoch.Add(25 * time.Minute), 20},
{2, db.GatewayPassFull, monitorTestEpoch.Add(95 * time.Minute), 20},
}
wantReschedules := []time.Time{monitorTestEpoch.Add(30 * time.Minute), monitorTestEpoch.Add(20 * time.Minute)}
if !slices.Equal(store.passes, wantPasses) || !slices.Equal(store.reschedules, wantReschedules) || prober.controls != 0 {
t.Fatalf("passes = %+v, reschedules = %v, controls = %d", store.passes, store.reschedules, prober.controls)
}
if err := m.run(t.Context(), nilClosedMonitorTicks()); err != nil {
t.Fatal(err)
}
if got := store.passes[len(store.passes)-1]; len(store.passes) != 4 || got.mode != db.GatewayPassFull || !got.startedAt.Equal(*now) {
t.Fatalf("restart did not begin a full pass: %+v", store.passes)
}
}
func nilClosedMonitorTicks() <-chan time.Time {
ticks := make(chan time.Time)
close(ticks)
return ticks
}
func TestMonitorReconcilesStaleMembershipsWithoutWaitingForTick(t *testing.T) {
for _, scenario := range []string{"session", "empty session", "commit membership", "probe membership"} {
t.Run(scenario, func(t *testing.T) {
m, store, prober, now := monitorFixture(monitorSnapshot(1, 20, monitorCandidate(1, 11), monitorCandidate(2, 12)))
next := monitorSnapshot(1, 20, monitorCandidate(1, 21), monitorCandidate(2, 12))
switch scenario {
case "session":
next = monitorSnapshot(2, 20, monitorCandidate(1, 21), monitorCandidate(2, 22))
case "empty session":
next = monitorSnapshot(2, 20)
case "probe membership":
prober.probe = func(_ context.Context, c db.GatewayCandidate) (db.GatewayProbeResult, db.GatewayErrorCode) {
if c.MembershipID == 11 {
return db.GatewayProbeResult{}, monitorProbeStale
}
return monitorObservation(c, *now, true), ""
}
}
store.beforeFinish = func(monitorTestFinish) error {
store.snapshot = next
return nil
}
if err := m.run(t.Context(), nilClosedMonitorTicks()); err != nil {
t.Fatal(err)
}
if len(store.passes) != 2 || store.passes[0].mode != db.GatewayPassFull || store.passes[1].mode != db.GatewayPassEarly ||
store.passes[1].sessionID != monitorSessionID(next.SessionID) || len(store.reschedules) != 0 {
t.Fatalf("stale reconciliation passes: %+v", store.passes)
}
for _, c := range next.Candidates {
if got := store.health[c.ProxyID]; got.MembershipID != c.MembershipID || !got.OK {
t.Fatalf("current membership %+v, health = %+v", c, got)
}
}
if len(next.Candidates) == 0 && len(store.health) != 0 {
t.Fatalf("stale session published measurements: %+v", store.health)
}
if scenario == "probe membership" && (len(store.finishes[0].results) != 1 || store.finishes[0].failure != "") {
t.Fatalf("stale probe leaked into first publication: %+v", store.finishes[0])
}
})
}
}
func TestMonitorSystemFailuresDoNotPublishAndBackOff(t *testing.T) {
for _, tc := range []struct {
name string
failControl int
failProbe db.GatewayErrorCode
want db.GatewayErrorCode
wantControls int
}{
{name: "pre-control", failControl: 3, want: db.GatewayErrorControl, wantControls: 3},
{name: "post-control", failControl: 4, want: db.GatewayErrorControl, wantControls: 4},
{name: "local proxy", failProbe: db.GatewayErrorProbe, want: db.GatewayErrorProbe, wantControls: 3},
{name: "database lookup", failProbe: db.GatewayErrorDatabase, want: db.GatewayErrorDatabase, wantControls: 3},
} {
t.Run(tc.name, func(t *testing.T) {
m, store, prober, now := monitorFixture(monitorSnapshot(1, 20, monitorCandidate(1, 11)))
var schedule monitorSchedule
monitorAdvance(t, m, &schedule)
previous := store.health[1]
var attempts int
prober.control = func(call int) db.GatewayErrorCode {
if call == tc.failControl {
return db.GatewayErrorControl
}
return ""
}
prober.probe = func(_ context.Context, c db.GatewayCandidate) (db.GatewayProbeResult, db.GatewayErrorCode) {
attempts++
return monitorObservation(c, *now, false), tc.failProbe
}
*now = monitorTestEpoch.Add(20 * time.Minute)
monitorAdvance(t, m, &schedule)
if got := store.finishes[1]; got.failure != tc.want || len(got.results) != 0 || store.health[1] != previous || prober.controls != tc.wantControls {
t.Fatalf("failed pass = %+v, controls = %d, health = %+v", got, prober.controls, store.health)
}
if tc.failControl == 3 && attempts != 0 {
t.Fatalf("pre-control failure still ran %d probes", attempts)
}
failedAt, reads := *now, store.reads
for offset := 5 * time.Second; offset < time.Minute; offset += 5 * time.Second {
*now = failedAt.Add(offset)
monitorAdvance(t, m, &schedule)
}
if store.reads != reads || len(store.passes) != 2 {
t.Fatal("system failure caused five-second retries")
}
*now = failedAt.Add(time.Minute)
prober.probe = func(_ context.Context, c db.GatewayCandidate) (db.GatewayProbeResult, db.GatewayErrorCode) {
return monitorObservation(c, *now, false), ""
}
monitorAdvance(t, m, &schedule)
if got := store.finishes[2]; got.failure != "" || len(got.results) != 1 || store.health[1].OK || store.passes[2].mode != db.GatewayPassFull {
t.Fatalf("confirmed zero-ready full pass not committed: %+v", got)
}
})
}
}
func TestMonitorEarlyFailureRetriesWithoutMovingFullDeadline(t *testing.T) {
m, store, prober, now := monitorFixture(monitorSnapshot(1, 20, monitorCandidate(1, 11)))
var schedule monitorSchedule
monitorAdvance(t, m, &schedule)
store.snapshot = monitorSnapshot(1, 20, monitorCandidate(1, 11), monitorCandidate(2, 12))
prober.control = func(call int) db.GatewayErrorCode {
if call == 3 {
return db.GatewayErrorControl
}
return ""
}
*now = now.Add(5 * time.Second)
monitorAdvance(t, m, &schedule)
if len(store.finishes) != 2 || store.finishes[1].failure != db.GatewayErrorControl || len(store.health) != 1 {
t.Fatalf("early batch failure = %+v, health = %+v", store.finishes, store.health)
}
*now = now.Add(time.Minute)
monitorAdvance(t, m, &schedule)
*now = monitorTestEpoch.Add(20 * time.Minute)
monitorAdvance(t, m, &schedule)
if len(store.passes) != 4 || store.passes[2].mode != db.GatewayPassEarly || store.passes[3].mode != db.GatewayPassFull ||
!store.passes[3].startedAt.Equal(*now) || len(store.finishes[2].results) != 1 || store.finishes[2].results[0].ProxyID != 2 {
t.Fatalf("early retry moved deadline or rechecked healthy membership: %+v, %+v", store.passes, store.finishes)
}
}
func TestMonitorBoundsImmediateReconciliationDuringChurn(t *testing.T) {
m, store, _, _ := monitorFixture(monitorSnapshot(1, 20, monitorCandidate(1, 11)))
store.beforeFinish = func(monitorTestFinish) error {
session := *store.snapshot.SessionID + 1
store.snapshot = monitorSnapshot(session, 20, monitorCandidate(1, 10+session))
return nil
}
if err := m.run(t.Context(), nilClosedMonitorTicks()); err != nil {
t.Fatal(err)
}
if store.reads != 2 || len(store.passes) != 2 || len(store.health) != 0 {
t.Fatalf("changing session produced %d reads, %d passes, health = %+v", store.reads, len(store.passes), store.health)
}
}
func TestMonitorSanitizesReadAndBeginFailures(t *testing.T) {
for _, tc := range []struct {
name string
read, begin error
want db.GatewayErrorCode
}{
{name: "invalid config", read: fmt.Errorf("bad setting: %w", db.ErrGatewayConfig), want: db.GatewayErrorConfig},
{name: "database read", read: errors.New("private database detail"), want: db.GatewayErrorDatabase},
{name: "begin write", begin: errors.New("private database detail"), want: db.GatewayErrorDatabase},
} {
t.Run(tc.name, func(t *testing.T) {
m, store, prober, now := monitorFixture(monitorSnapshot(1, 20, monitorCandidate(1, 11)))
store.readErr, store.beginErr = tc.read, tc.begin
var schedule monitorSchedule
monitorAdvance(t, m, &schedule)
if !slices.Equal(store.degraded, []db.GatewayErrorCode{tc.want}) || len(store.passes) != 0 || prober.controls != 0 {
t.Fatalf("degraded = %v, passes = %v, controls = %d", store.degraded, store.passes, prober.controls)
}
store.readErr, store.beginErr = nil, nil
*now = now.Add(time.Minute - time.Nanosecond)
monitorAdvance(t, m, &schedule)
if store.reads != 1 {
t.Fatalf("early retry read %d times", store.reads)
}
*now = now.Add(time.Nanosecond)
monitorAdvance(t, m, &schedule)
if len(store.passes) != 1 || store.passes[0].mode != db.GatewayPassFull || !store.health[1].OK {
t.Fatalf("recovery passes = %+v, health = %+v", store.passes, store.health)
}
})
}
}
func TestMonitorFinishRollbackClosesPassBeforeRetry(t *testing.T) {
m, store, _, now := monitorFixture(monitorSnapshot(1, 20, monitorCandidate(1, 11)))
var schedule monitorSchedule
store.beforeFinish = func(monitorTestFinish) error {
if len(store.finishes) <= 2 {
return errors.New("private database detail")
}
return nil
}
monitorAdvance(t, m, &schedule)
if len(store.health) != 0 || len(store.finishes) != 2 || store.finishes[1].failure != db.GatewayErrorDatabase || len(store.finishes[1].results) != 0 || store.active == nil {
t.Fatalf("rollback did not retain status-only cleanup: %+v", store.finishes)
}
*now = now.Add(5 * time.Second)
monitorAdvance(t, m, &schedule)
if len(store.finishes) != 2 || len(store.passes) != 1 {
t.Fatal("rolled back pass retried without backoff")
}
*now = monitorTestEpoch.Add(time.Minute)
monitorAdvance(t, m, &schedule)
if len(store.finishes) != 4 || store.finishes[2].failure != db.GatewayErrorDatabase || !store.finishes[2].at.Equal(monitorTestEpoch) ||
store.finishes[3].failure != "" || len(store.passes) != 2 || !store.health[1].OK || store.active != nil {
t.Fatalf("recovery order or state wrong: %+v, health = %+v", store.finishes, store.health)
}
}
func TestMonitorLeaseLossIsFatalAndSanitized(t *testing.T) {
m, store, _, _ := monitorFixture(monitorSnapshot(1, 20, monitorCandidate(1, 11)))
store.beforeFinish = func(monitorTestFinish) error {
return fmt.Errorf("private database detail: %w", db.ErrGatewayLeaseLost)
}
if err := m.run(t.Context(), nilClosedMonitorTicks()); err != db.ErrGatewayLeaseLost {
t.Fatalf("monitor returned %v, want only lease sentinel", err)
}
if len(store.finishes) != 1 || len(store.health) != 0 {
t.Fatalf("monitor retried or published after lease loss: %+v", store.finishes)
}
}
func TestMonitorRunSerializesLongPassAndUsesNewInterval(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
m, store, prober, now := monitorFixture(monitorSnapshot(1, 20, monitorCandidate(1, 11)))
release, ticks := make(chan struct{}), make(chan time.Time, 1)
prober.probe = func(ctx context.Context, c db.GatewayCandidate) (db.GatewayProbeResult, db.GatewayErrorCode) {
select {
case <-release:
return monitorObservation(c, *now, true), ""
case <-ctx.Done():
return db.GatewayProbeResult{}, db.GatewayErrorInterrupted
}
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
done := make(chan error, 1)
go func() { done <- m.run(ctx, ticks) }()
synctest.Wait()
if store.reads != 1 || len(store.finishes) != 0 {
t.Fatalf("first pass did not start immediately: %d reads, %+v finishes", store.reads, store.finishes)
}
*now = now.Add(16 * time.Minute)
store.snapshot.IntervalMinutes = 15
ticks <- monitorTestEpoch.Add(5 * time.Second) // coalesced old event; decision uses current time
synctest.Wait()
if store.reads != 1 || len(store.passes) != 1 {
t.Fatal("tick overlapped an active pass")
}
close(release)
synctest.Wait()
if len(store.passes) != 2 || store.passes[1] != (monitorTestPass{1, db.GatewayPassFull, *now, 15}) ||
!slices.Equal(store.reschedules, []time.Time{monitorTestEpoch.Add(15 * time.Minute)}) {
t.Fatalf("missed deadline not caught up with the current config: %+v, %v", store.passes, store.reschedules)
}
cancel()
if err := <-done; err != nil {
t.Fatal(err)
}
})
}
func TestMonitorBoundsFanoutAndJoinsWorkersOnCancellation(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
candidates := make([]db.GatewayCandidate, 32)
for i := range candidates {
candidates[i] = monitorCandidate(int64(i+1), int64(i+100))
}
m, store, prober, _ := monitorFixture(monitorSnapshot(1, 20, candidates...))
started, stopped := make(chan int64, len(candidates)), make(chan int64, len(candidates))
prober.probe = func(ctx context.Context, c db.GatewayCandidate) (db.GatewayProbeResult, db.GatewayErrorCode) {
started <- c.ProxyID
<-ctx.Done()
stopped <- c.ProxyID
return db.GatewayProbeResult{}, db.GatewayErrorInterrupted
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
done := make(chan error, 1)
go func() { done <- m.run(ctx, make(chan time.Time)) }()
synctest.Wait()
if len(started) != 8 || len(stopped) != 0 || prober.controls != 1 {
t.Fatalf("active fanout = %d, stopped = %d, controls = %d", len(started), len(stopped), prober.controls)
}
cancel()
if err := <-done; err != nil {
t.Fatal(err)
}
if len(started) != 8 || len(stopped) != 8 || len(store.health) != 0 || len(store.finishes) != 1 ||
store.finishes[0].failure != db.GatewayErrorInterrupted || len(store.finishes[0].results) != 0 {
t.Fatalf("shutdown started %d, stopped %d, finishes = %+v, health = %+v", len(started), len(stopped), store.finishes, store.health)
}
})
}
func TestMonitorPreservesProbeCompletionTimesAndLatencies(t *testing.T) {
m, store, prober, now := monitorFixture(monitorSnapshot(1, 20, monitorCandidate(1, 11), monitorCandidate(2, 12)))
prober.probe = func(_ context.Context, c db.GatewayCandidate) (db.GatewayProbeResult, db.GatewayErrorCode) {
r := monitorObservation(c, monitorTestEpoch.Add(time.Duration(c.ProxyID)*time.Second), true)
r.LatencyMS = int32(c.ProxyID * 100)
return r, ""
}
prober.control = func(call int) db.GatewayErrorCode {
if call == 2 {
*now = now.Add(8 * time.Second)
}
return ""
}
var schedule monitorSchedule
monitorAdvance(t, m, &schedule)
if len(store.finishes) != 1 || !store.finishes[0].at.Equal(*now) || len(store.health) != 2 {
t.Fatalf("finish event or stored results missing: %+v, %+v", store.finishes, store.health)
}
for id, got := range store.health {
if got.CheckedAt.Equal(*now) || !got.CheckedAt.Equal(monitorTestEpoch.Add(time.Duration(id)*time.Second)) || got.LatencyMS != int32(100*id) {
t.Fatalf("node %d timing replaced by batch time: %+v", id, got)
}
}
}
+315
View File
@@ -0,0 +1,315 @@
package gateway
import (
"context"
"errors"
"maps"
"net"
"net/http"
"net/netip"
"slices"
"strconv"
"strings"
"git.eeee.moe/omar/zhguchiy_perchik/internal/netpolicy"
)
var (
ErrInvalidDestination = errors.New("invalid gateway request destination")
ErrDestinationDenied = errors.New("gateway destination not permitted")
ErrUpstreamDenied = errors.New("gateway upstream not permitted")
errControlDenied = errors.New("gateway control destination not permitted")
errRouteDial = errors.New("gateway TCP connection failed")
)
// RoutePolicy checks application destinations and upstream sockets independently.
// Construct it from validated Config and do not change it while serving requests.
type RoutePolicy struct {
destinations map[string]struct{}
upstreams []netip.Prefix
probe string
selfName string
selfIP netip.Addr
resolveIP func(context.Context, string) ([]netip.Addr, error)
openTCP func(context.Context, string, string) (net.Conn, error)
localIPs func() ([]netip.Addr, error)
allowIP func(netip.Addr) bool
}
// NewRoutePolicy creates the production route policy without opening sockets.
func NewRoutePolicy(cfg Config) *RoutePolicy {
// Use the Go resolver with both families and reject partial results on
// temporary failures. Its A and AAAA decoding preserves the address family.
resolver := &net.Resolver{PreferGo: true, StrictErrors: true}
var dialer net.Dialer
p := &RoutePolicy{
destinations: maps.Clone(cfg.AllowedDestinations),
upstreams: slices.Clone(cfg.UpstreamNetworks),
openTCP: dialer.DialContext,
localIPs: routeInterfaceIPs,
allowIP: netpolicy.IsPublicIP,
resolveIP: func(ctx context.Context, name string) ([]netip.Addr, error) {
return resolver.LookupNetIP(ctx, "ip", name)
},
}
if cfg.ProbeURL != nil {
p.probe = cfg.ProbeURL.Host
}
if ip, err := netip.ParseAddr(cfg.PublicProxyHost); err == nil {
p.selfIP = ip
} else {
p.selfName, _ = normalizeGatewayDNSName(cfg.PublicProxyHost)
}
return p
}
// ResolveRequest returns the normalized authority and a checked numeric IP:port.
// The caller forwards the original Request.Host for ordinary HTTP requests.
func (p *RoutePolicy) ResolveRequest(ctx context.Context, r *http.Request) (authority, destination string, err error) {
var defaultPort uint16 = 80
u := r.URL
if u == nil || u.Host == "" || u.User != nil || u.Opaque != "" || u.OmitHost ||
u.Fragment != "" || u.RawFragment != "" || strings.Contains(r.RequestURI, "#") {
return "", "", ErrInvalidDestination
}
if r.Method == http.MethodConnect {
defaultPort = 0 // CONNECT always needs an explicit port.
if r.ProtoMajor != 1 || r.ProtoMinor != 1 || u.Scheme != "" || u.Path != "" ||
u.RawPath != "" || u.RawQuery != "" || u.ForceQuery ||
(r.RequestURI != "" && r.RequestURI != u.Host) || r.ContentLength != 0 || len(r.TransferEncoding) != 0 {
return "", "", ErrInvalidDestination
}
} else if r.ProtoMajor != 1 || u.Scheme != "http" {
return "", "", ErrInvalidDestination
}
target, ok := parseRouteAuthority(u.Host, defaultPort)
if !ok {
return "", "", ErrInvalidDestination
}
host, ok := parseRouteAuthority(r.Host, defaultPort)
if !ok || host != target || !routeHeadersValid(r.Header, target, defaultPort) {
return "", "", ErrInvalidDestination
}
if target.ip.IsValid() {
return "", "", ErrDestinationDenied
}
authority = target.String()
if _, ok := p.destinations[authority]; !ok {
return "", "", ErrDestinationDenied
}
pinned, err := p.pin(ctx, target, false, ErrDestinationDenied)
if err != nil {
return "", "", err
}
return authority, pinned, nil
}
func routeHeadersValid(header http.Header, target routeAuthority, defaultPort uint16) bool {
// net/http derives Request.Host from the target for absolute/authority
// form. If a caller supplies a separate Host, never forward a conflicting one.
hostSeen := false
for key, values := range header {
switch {
case strings.EqualFold(key, "Host"):
if hostSeen || len(values) != 1 {
return false
}
hostSeen = true
host, ok := parseRouteAuthority(values[0], defaultPort)
if !ok || host != target {
return false
}
case strings.EqualFold(key, "Upgrade"):
return false
case strings.EqualFold(key, "Connection"):
for _, value := range values {
for name := range strings.SplitSeq(value, ",") {
name = strings.Trim(name, " \t")
if strings.EqualFold(name, "upgrade") || strings.EqualFold(name, "host") {
return false
}
}
}
}
}
return true
}
// DialUpstream opens TCP only to a checked address within the operator's
// enrollment. The protocol dialer keeps the separate logical host for TLS, etc.
func (p *RoutePolicy) DialUpstream(ctx context.Context, network, address string) (net.Conn, error) {
if network != "tcp" {
return nil, ErrUpstreamDenied
}
target, ok := parseRouteAuthority(address, 0)
if !ok {
return nil, ErrUpstreamDenied
}
pinned, err := p.pin(ctx, target, true, ErrUpstreamDenied)
if err != nil {
return nil, err
}
return p.dialPinned(ctx, pinned)
}
// DialControl opens a direct TCP connection only to the configured probe
// authority. TLS still authenticates the probe's logical name in its client.
func (p *RoutePolicy) DialControl(ctx context.Context, network, address string) (net.Conn, error) {
target, ok := parseRouteAuthority(address, 0)
if network != "tcp" || !ok || target.ip.IsValid() {
return nil, errControlDenied
}
authority := target.String()
if authority != p.probe {
return nil, errControlDenied
}
if _, ok := p.destinations[authority]; !ok {
return nil, errControlDenied
}
pinned, err := p.pin(ctx, target, false, errControlDenied)
if err != nil {
return nil, err
}
return p.dialPinned(ctx, pinned)
}
type routeAuthority struct {
name string
ip netip.Addr
port uint16
}
func (a routeAuthority) String() string {
if a.ip.IsValid() {
return netip.AddrPortFrom(a.ip, a.port).String()
}
return net.JoinHostPort(a.name, strconv.Itoa(int(a.port)))
}
func parseRouteAuthority(raw string, defaultPort uint16) (routeAuthority, bool) {
host := raw
port := defaultPort
bracketed := strings.HasPrefix(raw, "[")
if strings.ContainsAny(raw, ":[]") {
var portText string
var err error
host, portText, err = net.SplitHostPort(raw)
if err == nil {
var ok bool
port, ok = parseGatewayPort(portText)
if !ok {
return routeAuthority{}, false
}
} else if bracketed && strings.HasSuffix(raw, "]") && defaultPort != 0 {
host = raw[1 : len(raw)-1]
} else {
return routeAuthority{}, false
}
}
if port == 0 {
return routeAuthority{}, false
}
if ip, err := netip.ParseAddr(host); err == nil {
if bracketed != ip.Is6() || ip.Zone() != "" || ip.Is4In6() {
return routeAuthority{}, false
}
return routeAuthority{ip: ip, port: port}, true
}
name, ok := normalizeGatewayDNSName(host)
if !ok || bracketed {
return routeAuthority{}, false
}
return routeAuthority{name: name, port: port}, true
}
func (p *RoutePolicy) pin(ctx context.Context, target routeAuthority, upstream bool, denied error) (string, error) {
if err := ctx.Err(); err != nil {
return "", err
}
if target.name != "" && target.name == p.selfName {
return "", denied
}
if upstream && len(p.upstreams) == 0 {
return "", denied
}
ips := []netip.Addr{target.ip}
if !target.ip.IsValid() {
var err error
ips, err = p.resolveIP(ctx, target.name+".") // never expand the DNS search path
if err != nil {
return "", safeRouteError(err, denied)
}
if len(ips) == 0 {
return "", denied
}
}
local, err := p.localIPs()
if err != nil {
return "", denied
}
// Deny the whole authority on any unsafe answer, not just the selected IP.
for _, ip := range ips {
if !ip.IsValid() || ip.Is4In6() || ip.Zone() != "" || !p.allowIP(ip) ||
ip == p.selfIP || slices.Contains(local, ip) || (upstream && !p.enrolled(ip)) {
return "", denied
}
}
if err := ctx.Err(); err != nil {
return "", err
}
return netip.AddrPortFrom(ips[0], target.port).String(), nil
}
func (p *RoutePolicy) enrolled(ip netip.Addr) bool {
for _, prefix := range p.upstreams {
if prefix.Contains(ip) {
return true
}
}
return false
}
func (p *RoutePolicy) dialPinned(ctx context.Context, address string) (net.Conn, error) {
conn, err := p.openTCP(ctx, "tcp", address)
if err != nil {
return nil, safeRouteError(err, errRouteDial)
}
return conn, nil
}
func safeRouteError(err, fallback error) error {
if errors.Is(err, context.Canceled) {
return context.Canceled
}
var timeout net.Error
if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &timeout) && timeout.Timeout()) {
return context.DeadlineExceeded
}
return fallback
}
func routeInterfaceIPs() ([]netip.Addr, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
ips := make([]netip.Addr, 0, len(addrs))
for _, addr := range addrs {
var raw net.IP
switch a := addr.(type) {
case *net.IPNet:
raw = a.IP
case *net.IPAddr:
raw = a.IP
}
ip, ok := netip.AddrFromSlice(raw)
if !ok {
return nil, errors.New("gateway local interface address unavailable")
}
// The interface API may represent a local IPv4 address in 16 bytes.
ips = append(ips, ip.Unmap())
}
return ips, nil
}
+387
View File
@@ -0,0 +1,387 @@
package gateway
import (
"bufio"
"context"
"errors"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"net/url"
"strings"
"testing"
)
func routeTestConfig() Config {
return Config{
AllowedDestinations: map[string]struct{}{
"app.operator.test:80": {},
"probe.operator.test:443": {},
"gateway.operator.test:80": {},
},
UpstreamNetworks: []netip.Prefix{
netip.MustParsePrefix("8.8.8.0/24"),
netip.MustParsePrefix("2606:4700:4700::/64"),
},
ProbeURL: &url.URL{Scheme: "https", Host: "probe.operator.test:443", Path: "/ok"},
PublicProxyHost: "gateway.operator.test",
}
}
func newRouteTestPolicy(t *testing.T, cfg Config) *RoutePolicy {
t.Helper()
policy := NewRoutePolicy(cfg)
policy.localIPs = func() ([]netip.Addr, error) { return nil, nil }
policy.resolveIP = func(_ context.Context, name string) ([]netip.Addr, error) {
t.Fatalf("unexpected DNS lookup for %q", name)
return nil, nil
}
policy.openTCP = func(_ context.Context, _, address string) (net.Conn, error) {
t.Fatalf("unexpected open to %q", address)
return nil, nil
}
return policy
}
func readRouteTestRequest(t *testing.T, wire string) *http.Request {
t.Helper()
r, err := http.ReadRequest(bufio.NewReader(strings.NewReader(wire)))
if err != nil {
t.Fatal(err)
}
return r
}
func TestRouteRequestPinsExactDestination(t *testing.T) {
cases := []struct {
name, wire, lookup, authority, host, pinned string
ips []netip.Addr
}{
{
name: "absolute form HTTP preserves host",
wire: "GET http://APP.Operator.test./a%23b?q=a HTTP/1.1\r\nHost: APP.Operator.test.\r\n\r\n",
lookup: "app.operator.test.",
authority: "app.operator.test:80",
host: "APP.Operator.test.",
pinned: "1.1.1.1:80",
ips: []netip.Addr{netip.MustParseAddr("1.1.1.1"), netip.MustParseAddr("2606:4700:4700::1111")},
},
{
name: "authority form CONNECT retains checked IPv6",
wire: "CONNECT PROBE.operator.test:00443 HTTP/1.1\r\nHost: PROBE.operator.test:00443\r\nContent-Length: 0\r\n\r\n",
lookup: "probe.operator.test.",
authority: "probe.operator.test:443",
host: "PROBE.operator.test:00443",
pinned: "[2606:4700:4700::1111]:443",
ips: []netip.Addr{netip.MustParseAddr("2606:4700:4700::1111"), netip.MustParseAddr("1.1.1.1")},
},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
policy := newRouteTestPolicy(t, routeTestConfig())
lookups := 0
policy.resolveIP = func(_ context.Context, name string) ([]netip.Addr, error) {
lookups++
if name != tt.lookup {
t.Fatalf("lookup = %q, want %q", name, tt.lookup)
}
return tt.ips, nil
}
r := readRouteTestRequest(t, tt.wire)
authority, pinned, err := policy.ResolveRequest(t.Context(), r)
if err != nil || authority != tt.authority || pinned != tt.pinned || r.Host != tt.host || lookups != 1 {
t.Fatalf("resolved (%q, %q, %v), Host=%q, lookups=%d", authority, pinned, err, r.Host, lookups)
}
})
}
}
func TestRouteRequestRejectsInvalidOrUnapprovedBeforeDNS(t *testing.T) {
cases := []struct {
name string
alter func(*http.Request)
denied bool
}{
{name: "origin form", alter: func(r *http.Request) { r.URL = &url.URL{Path: "/v1/proxies"} }},
{name: "direct HTTPS", alter: func(r *http.Request) { r.URL.Scheme = "https" }},
{name: "userinfo", alter: func(r *http.Request) { r.URL.User = url.UserPassword("test", "test") }},
{name: "opaque", alter: func(r *http.Request) { r.URL.Opaque = "//app.operator.test/path" }},
{name: "fragment", alter: func(r *http.Request) { r.RequestURI += "#fragment" }},
{name: "conflicting Host", alter: func(r *http.Request) { r.Host = "probe.operator.test:443" }},
{name: "conflicting separate Host", alter: func(r *http.Request) { r.Header.Set("Host", "other.operator.test") }},
{name: "ambiguous Host", alter: func(r *http.Request) { r.Header["Host"] = []string{r.Host, r.Host} }},
{name: "host nominated by connection", alter: func(r *http.Request) { r.Header.Set("Connection", "Host") }},
{name: "empty Upgrade header", alter: func(r *http.Request) { r.Header.Set("Upgrade", "") }},
{name: "upgrade on second connection line", alter: func(r *http.Request) {
r.Header["Connection"] = []string{"keep-alive", "x-extra,\tUpGrade"}
}},
{name: "alternate port", alter: setRouteTestHost("app.operator.test:81"), denied: true},
{name: "unapproved suffix", alter: setRouteTestHost("app.operator.test.other.test"), denied: true},
{name: "unapproved subdomain", alter: setRouteTestHost("other.app.operator.test"), denied: true},
{name: "advertised gateway name", alter: setRouteTestHost("Gateway.Operator.test."), denied: true},
{name: "literal IPv4", alter: setRouteTestHost("1.1.1.1:80"), denied: true},
{name: "literal IPv6", alter: setRouteTestHost("[2606:4700:4700::1111]"), denied: true},
{name: "IPv6 without brackets", alter: setRouteTestHost("2606:4700:4700::1111:80")},
{name: "IPv6 scope", alter: setRouteTestHost("[fe80::1%eth0]:80")},
{name: "bracketed DNS", alter: setRouteTestHost("[app.operator.test]:80")},
{name: "mapped address", alter: setRouteTestHost("[::ffff:1.1.1.1]:80")},
{name: "escaped authority", alter: setRouteTestHost("app%2eoperator.test:80")},
{name: "empty port", alter: setRouteTestHost("app.operator.test:")},
{name: "overflowing port", alter: setRouteTestHost("app.operator.test:65536")},
{name: "port zero", alter: setRouteTestHost("app.operator.test:0")},
{name: "multiple trailing dots", alter: setRouteTestHost("app.operator.test..")},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
policy := newRouteTestPolicy(t, routeTestConfig())
r := httptest.NewRequest(http.MethodGet, "http://app.operator.test/path", nil)
tt.alter(r)
want := ErrInvalidDestination
if tt.denied {
want = ErrDestinationDenied
}
authority, pinned, err := policy.ResolveRequest(t.Context(), r)
if err != want || authority != "" || pinned != "" {
t.Fatalf("resolved (%q, %q, %v), want %v", authority, pinned, err, want)
}
})
}
}
func setRouteTestHost(host string) func(*http.Request) {
return func(r *http.Request) { r.URL.Host, r.Host = host, host }
}
func TestRouteCONNECTRequiresUnframedHTTP11Authority(t *testing.T) {
cases := map[string]func(*http.Request){
"absent port": func(r *http.Request) {
r.URL.Host, r.Host, r.RequestURI = "probe.operator.test", "probe.operator.test", "probe.operator.test"
},
"mismatched URI": func(r *http.Request) { r.RequestURI = "another.operator.test:443" },
"absolute URI": func(r *http.Request) { r.URL.Scheme = "http" },
"with path": func(r *http.Request) { r.URL.Path = "/extra" },
"with query": func(r *http.Request) { r.URL.ForceQuery = true },
"old HTTP": func(r *http.Request) { r.ProtoMinor = 0 },
"HTTP/2": func(r *http.Request) { r.ProtoMajor = 2 },
"fixed body": func(r *http.Request) { r.ContentLength = 1 },
"chunked body": func(r *http.Request) { r.TransferEncoding = []string{"chunked"} },
}
for name, alter := range cases {
t.Run(name, func(t *testing.T) {
policy := newRouteTestPolicy(t, routeTestConfig())
r := readRouteTestRequest(t, "CONNECT probe.operator.test:443 HTTP/1.1\r\nHost: probe.operator.test:443\r\n\r\n")
alter(r)
_, _, err := policy.ResolveRequest(t.Context(), r)
if err != ErrInvalidDestination {
t.Fatalf("err = %v, want invalid destination", err)
}
})
}
}
func TestRouteRequestRejectsAnyUnsafeAnswer(t *testing.T) {
cases := []struct{ name, answer string }{
{"loopback", "127.0.0.1"},
{"private", "10.1.2.3"},
{"infrastructure", "100.64.0.1"},
{"metadata", "169.254.169.254"},
{"multicast", "224.1.2.3"},
{"special", "198.18.1.2"},
{"IPv6 private", "fd00::1"},
{"IPv6 link-local", "fe80::1"},
{"IPv6 documentation", "2001:db8::1"},
{"mapped public IPv4", "::ffff:8.8.8.8"},
{"zoned public IPv6", "2606:4700:4700::1111%eth0"},
{"gateway interface", "8.8.8.9"},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
policy := newRouteTestPolicy(t, routeTestConfig())
policy.resolveIP = func(context.Context, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("1.1.1.1"), netip.MustParseAddr(tt.answer)}, nil
}
policy.localIPs = func() ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("8.8.8.9")}, nil
}
_, ip, err := policy.ResolveRequest(t.Context(), httptest.NewRequest(http.MethodGet, "http://app.operator.test/", nil))
if err != ErrDestinationDenied || ip != "" {
t.Fatalf("resolved (%q, %v), want denial with no pinned IP", ip, err)
}
})
}
}
func TestRouteUpstreamOpensOnlyEnrolledNumericAddress(t *testing.T) {
cases := []struct {
name, network, target, lookup, pinned string
answers []string
}{
{name: "enrolled IPv4 literal", network: "tcp", target: "8.8.8.7:8443", pinned: "8.8.8.7:8443"},
{name: "enrolled IPv6 literal", network: "tcp", target: "[2606:4700:4700::1001]:443", pinned: "[2606:4700:4700::1001]:443"},
{name: "all enrolled DNS", network: "tcp", target: "Peer.Operator.test:443", lookup: "peer.operator.test.",
pinned: "[2606:4700:4700::1001]:443", answers: []string{"2606:4700:4700::1001", "8.8.8.7"}},
{name: "unenrolled IPv4", network: "tcp", target: "1.1.1.1:443"},
{name: "unenrolled IPv6", network: "tcp", target: "[2001:4860:4860::8888]:443"},
{name: "mixed enrollment", network: "tcp", target: "peer.operator.test:443", lookup: "peer.operator.test.", answers: []string{"8.8.8.7", "1.1.1.1"}},
{name: "mixed private", network: "tcp", target: "peer.operator.test:443", lookup: "peer.operator.test.", answers: []string{"8.8.8.7", "10.0.0.1"}},
{name: "mixed own IP", network: "tcp", target: "peer.operator.test:443", lookup: "peer.operator.test.", answers: []string{"8.8.8.7", "8.8.8.9"}},
{name: "own IP literal", network: "tcp", target: "8.8.8.9:443"},
{name: "advertised name", network: "tcp", target: "Gateway.Operator.test.:8081"},
{name: "empty DNS answer", network: "tcp", target: "peer.operator.test:443", lookup: "peer.operator.test."},
{name: "userinfo", network: "tcp", target: "user@peer.operator.test:443"},
{name: "mapped public IP", network: "tcp", target: "[::ffff:8.8.8.7]:443"},
{name: "unsupported network", network: "udp", target: "8.8.8.7:443"},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
policy := newRouteTestPolicy(t, routeTestConfig())
policy.localIPs = func() ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("8.8.8.9")}, nil
}
lookups, opens := 0, 0
policy.resolveIP = func(_ context.Context, name string) ([]netip.Addr, error) {
lookups++
if tt.lookup == "" || name != tt.lookup {
t.Fatalf("unexpected lookup %q, want %q", name, tt.lookup)
}
ips := make([]netip.Addr, 0, len(tt.answers))
for _, ip := range tt.answers {
ips = append(ips, netip.MustParseAddr(ip))
}
return ips, nil
}
policy.openTCP = func(_ context.Context, network, address string) (net.Conn, error) {
opens++
if tt.pinned == "" || network != "tcp" || address != tt.pinned {
t.Fatalf("unexpected open %s %s, want tcp %s", network, address, tt.pinned)
}
client, peer := net.Pipe()
t.Cleanup(func() { _ = peer.Close() })
return client, nil
}
conn, err := policy.DialUpstream(t.Context(), tt.network, tt.target)
if conn != nil {
defer conn.Close()
}
if (tt.lookup == "" && lookups != 0) || (tt.lookup != "" && lookups != 1) {
t.Fatalf("lookups = %d", lookups)
}
if tt.pinned == "" {
if err != ErrUpstreamDenied || conn != nil || opens != 0 {
t.Fatalf("upstream was not denied before opening: conn=%v, err=%v, opens=%d", conn, err, opens)
}
} else if err != nil || conn == nil || opens != 1 {
t.Fatalf("expected one checked upstream connection, got conn=%v, err=%v, opens=%d", conn, err, opens)
}
})
}
}
func TestRouteControlCannotBecomeGeneralDialer(t *testing.T) {
policy := newRouteTestPolicy(t, routeTestConfig())
for _, address := range []string{"probe.operator.test:80", "probe.operator.test", "app.operator.test:80", "1.1.1.1:443", "user@probe.operator.test:443"} {
if conn, err := policy.DialControl(t.Context(), "tcp", address); err != errControlDenied || conn != nil {
t.Fatalf("control %q returned (%v, %v)", address, conn, err)
}
}
if conn, err := policy.DialControl(t.Context(), "udp", "probe.operator.test:443"); err != errControlDenied || conn != nil {
t.Fatalf("UDP control returned (%v, %v)", conn, err)
}
// A local test can substitute the resolver and opener without changing
// the exact probe authority or the rules for an ordinary gateway request.
policy.allowIP = func(ip netip.Addr) bool { return ip == netip.MustParseAddr("127.0.0.1") }
policy.resolveIP = func(_ context.Context, name string) ([]netip.Addr, error) {
if name != "probe.operator.test." {
t.Fatalf("control looked up %q", name)
}
return []netip.Addr{netip.MustParseAddr("127.0.0.1"), netip.MustParseAddr("::ffff:127.0.0.1")}, nil
}
if conn, err := policy.DialControl(t.Context(), "tcp", "probe.operator.test:443"); err != errControlDenied || conn != nil {
t.Fatalf("mixed control DNS returned (%v, %v)", conn, err)
}
policy.resolveIP = func(_ context.Context, name string) ([]netip.Addr, error) {
if name != "probe.operator.test." {
t.Fatalf("control looked up %q", name)
}
return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil
}
policy.openTCP = func(_ context.Context, network, address string) (net.Conn, error) {
if network != "tcp" || address != "127.0.0.1:443" {
t.Fatalf("control opened %s %s", network, address)
}
client, peer := net.Pipe()
t.Cleanup(func() { _ = peer.Close() })
return client, nil
}
conn, err := policy.DialControl(t.Context(), "tcp", "PROBE.Operator.test.:443")
if conn != nil {
defer conn.Close()
}
if err != nil || conn == nil {
t.Fatalf("pinned control returned (%v, %v)", conn, err)
}
}
func TestRouteFailsClosedWithoutLeakingNetworkErrors(t *testing.T) {
policy := newRouteTestPolicy(t, routeTestConfig())
r := httptest.NewRequest(http.MethodGet, "http://app.operator.test/", nil)
ctx, cancel := context.WithCancel(t.Context())
cancel()
if _, _, err := policy.ResolveRequest(ctx, r); err != context.Canceled {
t.Fatalf("canceled lookup: %v", err)
}
privateError := errors.New("private DNS or socket details")
policy.resolveIP = func(context.Context, string) ([]netip.Addr, error) { return nil, privateError }
if _, _, err := policy.ResolveRequest(t.Context(), r); err != ErrDestinationDenied {
t.Fatalf("failed lookup: %v", err)
}
policy.resolveIP = func(context.Context, string) ([]netip.Addr, error) { return nil, context.DeadlineExceeded }
if _, _, err := policy.ResolveRequest(t.Context(), r); err != context.DeadlineExceeded {
t.Fatalf("timed out lookup: %v", err)
}
policy.localIPs = func() ([]netip.Addr, error) { return nil, privateError }
if _, err := policy.DialUpstream(t.Context(), "tcp", "8.8.8.7:443"); err != ErrUpstreamDenied {
t.Fatalf("failed interface enumeration: %v", err)
}
policy.localIPs = func() ([]netip.Addr, error) { return nil, nil }
policy.openTCP = func(context.Context, string, string) (net.Conn, error) { return nil, privateError }
if _, err := policy.DialUpstream(t.Context(), "tcp", "8.8.8.7:443"); err != errRouteDial {
t.Fatalf("failed socket: %v", err)
}
policy.openTCP = func(context.Context, string, string) (net.Conn, error) { return nil, &net.DNSError{IsTimeout: true} }
if _, err := policy.DialUpstream(t.Context(), "tcp", "8.8.8.7:443"); err != context.DeadlineExceeded {
t.Fatalf("timed out socket: %v", err)
}
}
func TestRouteAdvertisedIPIsDeniedWithoutInterfaceMatch(t *testing.T) {
cfg := routeTestConfig()
cfg.PublicProxyHost = "8.8.8.9"
policy := newRouteTestPolicy(t, cfg)
if _, err := policy.DialUpstream(t.Context(), "tcp", "8.8.8.9:443"); err != ErrUpstreamDenied {
t.Fatalf("dial to advertised IP returned %v", err)
}
}
func FuzzRouteAuthority(f *testing.F) {
for _, seed := range []string{
"APP.operator.test.", "app.operator.test:00080", "[2606:4700:4700::1111]:443", "[::ffff:8.8.8.8]:443",
"user@host:80", "host:0", "host:65536", "[fe80::1%eth0]:80", "host:80/?x=y", "host\r\n:80", "127.0.0.01",
} {
f.Add(seed)
}
f.Fuzz(func(t *testing.T, raw string) {
a, ok := parseRouteAuthority(raw, 80)
if !ok {
return
}
if a.port == 0 || (a.ip.IsValid() && (a.ip.Is4In6() || a.ip.Zone() != "" || a.name != "")) {
t.Fatalf("invalid authority parsed: %q", raw)
}
if roundTrip, ok := parseRouteAuthority(a.String(), 0); !ok || roundTrip != a {
t.Fatalf("authority %q does not round trip as %q", raw, a.String())
}
})
}
+136
View File
@@ -0,0 +1,136 @@
package gateway
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"net/http"
"net/netip"
"sync"
"time"
)
const (
probeTicketHeader = "X-Gateway-Probe"
probeTicketTTL = 8 * time.Second
probeTicketBytes = 16
)
var probeTicketEncoding = base64.RawURLEncoding.Strict()
type probeTicket struct {
proxyID, membershipID int64
expires time.Time
done <-chan struct{}
}
type probeTickets struct {
authority string
now func() time.Time
mu sync.Mutex
active map[[probeTicketBytes]byte]*probeTicket
}
// authority is the validated ProbeURL.Host, with an explicit port.
func newProbeTickets(authority string) *probeTickets {
return &probeTickets{
authority: authority,
now: time.Now,
active: make(map[[probeTicketBytes]byte]*probeTicket),
}
}
// issue authorizes one CONNECT for an in-flight monitor job. The caller must
// defer revoke so a request that never reaches the listener leaves no ticket.
func (p *probeTickets) issue(ctx context.Context, proxyID, membershipID int64) (token string, revoke func(), err error) {
if p == nil || p.authority == "" || proxyID <= 0 || membershipID <= 0 {
return "", nil, errors.New("invalid gateway probe ticket request")
}
if err := ctx.Err(); err != nil {
return "", nil, err
}
var key [probeTicketBytes]byte
if _, err := rand.Read(key[:]); err != nil {
return "", nil, errors.New("gateway probe ticket randomness unavailable")
}
expires := p.now().Add(probeTicketTTL)
lifetime, cancel := context.WithDeadline(ctx, expires)
entry := &probeTicket{proxyID: proxyID, membershipID: membershipID, expires: expires, done: lifetime.Done()}
p.mu.Lock()
if err := lifetime.Err(); err != nil {
p.mu.Unlock()
cancel()
return "", nil, err
}
if _, exists := p.active[key]; exists {
p.mu.Unlock()
cancel()
return "", nil, errors.New("duplicate gateway probe ticket")
}
p.active[key] = entry
p.mu.Unlock()
remove := func() {
p.mu.Lock()
if p.active[key] == entry {
delete(p.active, key)
}
p.mu.Unlock()
}
stop := context.AfterFunc(lifetime, remove)
return probeTicketEncoding.EncodeToString(key[:]), func() {
stop()
cancel()
remove()
}, nil
}
// consume runs only after runtime authentication. An absent marker permits
// ordinary readiness lookup; an invalid marker must not fall back to it.
// A successful marker permits an exact current-membership lookup, not a
// bypass of destination or upstream policy.
func (p *probeTickets) consume(r *http.Request, authenticatedProxyID int64) (membershipID int64, present bool) {
values, present := r.Header[probeTicketHeader]
if !present {
return 0, false
}
delete(r.Header, probeTicketHeader)
if p == nil || p.authority == "" || authenticatedProxyID <= 0 || len(values) != 1 ||
r.Method != http.MethodConnect || r.RequestURI != p.authority || r.Host != p.authority ||
r.URL == nil || r.URL.Host != p.authority || r.URL.Scheme != "" {
return 0, true
}
// RemoteAddr comes from the accepted socket; no forwarding header is trusted.
peer, err := netip.ParseAddrPort(r.RemoteAddr)
if err != nil || !peer.Addr().Unmap().IsLoopback() || len(values[0]) != probeTicketEncoding.EncodedLen(probeTicketBytes) {
return 0, true
}
var key [probeTicketBytes]byte
if n, err := probeTicketEncoding.Decode(key[:], []byte(values[0])); err != nil || n != len(key) {
return 0, true
}
p.mu.Lock()
defer p.mu.Unlock()
entry := p.active[key]
if entry == nil {
return 0, true
}
if !p.now().Before(entry.expires) {
delete(p.active, key)
return 0, true
}
select {
case <-entry.done:
delete(p.active, key)
return 0, true
default:
}
if entry.proxyID != authenticatedProxyID || r.Context().Err() != nil {
return 0, true
}
delete(p.active, key)
return entry.membershipID, true
}
+235
View File
@@ -0,0 +1,235 @@
package gateway
import (
"bufio"
"context"
"encoding/base64"
"errors"
"net"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
)
const probeTicketTestAuthority = "probe.example:443"
func issueTestProbeTicket(t *testing.T, tickets *probeTickets, ctx context.Context, node, membership int64) (string, func()) {
t.Helper()
token, revoke, err := tickets.issue(ctx, node, membership)
if err != nil {
t.Fatalf("issue probe ticket: %v", err)
}
t.Cleanup(revoke)
return token, revoke
}
func testProbeTicketRequest(token string) *http.Request {
r := httptest.NewRequest(http.MethodConnect, probeTicketTestAuthority, nil)
r.RemoteAddr = "127.0.0.1:9876"
r.Header.Set(probeTicketHeader, token)
return r
}
func assertProbeTicketResult(t *testing.T, tickets *probeTickets, r *http.Request, id, wantMembership int64, wantPresent bool) {
t.Helper()
membership, present := tickets.consume(r, id)
if membership != wantMembership || present != wantPresent {
t.Fatalf("probe decision = (%d, %t), want (%d, %t)", membership, present, wantMembership, wantPresent)
}
if _, present := r.Header[probeTicketHeader]; present {
t.Fatal("probe marker remains on request")
}
}
func TestProbeTicketRequestBinding(t *testing.T) {
for _, test := range []struct {
name string
id int64
edit func(*http.Request)
}{
{name: "different node", id: 42},
{name: "no authenticated node", id: 0},
{name: "different DNS name", id: 41, edit: func(r *http.Request) {
r.Host = "other.example:443"
r.URL.Host, r.RequestURI = r.Host, r.Host
}},
{name: "different port", id: 41, edit: func(r *http.Request) {
r.Host = "probe.example:8443"
r.URL.Host, r.RequestURI = r.Host, r.Host
}},
{name: "not exact authority", id: 41, edit: func(r *http.Request) {
r.Host = "Probe.Example:443"
r.URL.Host, r.RequestURI = r.Host, r.Host
}},
{name: "absolute CONNECT", id: 41, edit: func(r *http.Request) {
r.RequestURI = "https://" + r.Host
}},
{name: "different Host", id: 41, edit: func(r *http.Request) {
r.Host = "other.example:443"
}},
{name: "HTTP method", id: 41, edit: func(r *http.Request) {
r.Method = http.MethodGet
}},
{name: "remote IPv4 with spoofed forwarding headers", id: 41, edit: func(r *http.Request) {
r.RemoteAddr = "192.0.2.34:9876"
r.Header.Set("X-Forwarded-For", "127.0.0.1")
r.Header.Set("Forwarded", "for=127.0.0.1")
}},
{name: "remote IPv6", id: 41, edit: func(r *http.Request) {
r.RemoteAddr = "[2001:db8::34]:9876"
}},
{name: "not a numeric socket address", id: 41, edit: func(r *http.Request) {
r.RemoteAddr = "localhost:9876"
}},
{name: "duplicate marker", id: 41, edit: func(r *http.Request) {
r.Header.Add(probeTicketHeader, r.Header.Get(probeTicketHeader))
}},
{name: "empty marker", id: 41, edit: func(r *http.Request) {
r.Header.Set(probeTicketHeader, "")
}},
{name: "padded marker", id: 41, edit: func(r *http.Request) {
r.Header.Set(probeTicketHeader, r.Header.Get(probeTicketHeader)+"==")
}},
} {
t.Run(test.name, func(t *testing.T) {
tickets := newProbeTickets(probeTicketTestAuthority)
token, _ := issueTestProbeTicket(t, tickets, context.Background(), 41, 87)
bad := testProbeTicketRequest(token)
if test.edit != nil {
test.edit(bad)
}
assertProbeTicketResult(t, tickets, bad, test.id, 0, true)
assertProbeTicketResult(t, tickets, testProbeTicketRequest(token), 41, 87, true)
assertProbeTicketResult(t, tickets, testProbeTicketRequest(token), 41, 0, true)
})
}
}
func TestProbeTicketAbsentOrDisabled(t *testing.T) {
tickets := newProbeTickets(probeTicketTestAuthority)
r := testProbeTicketRequest("")
r.Header.Del(probeTicketHeader)
assertProbeTicketResult(t, tickets, r, 41, 0, false)
var disabled *probeTickets
assertProbeTicketResult(t, disabled, r, 41, 0, false)
assertProbeTicketResult(t, disabled, testProbeTicketRequest(""), 41, 0, true)
}
func TestProbeTicketExpiresAtEightSeconds(t *testing.T) {
tickets := newProbeTickets(probeTicketTestAuthority)
now := time.Now()
tickets.now = func() time.Time { return now }
before, _ := issueTestProbeTicket(t, tickets, context.Background(), 41, 87)
boundary, _ := issueTestProbeTicket(t, tickets, context.Background(), 41, 88)
now = now.Add(8*time.Second - time.Nanosecond)
assertProbeTicketResult(t, tickets, testProbeTicketRequest(before), 41, 87, true)
now = now.Add(time.Nanosecond)
assertProbeTicketResult(t, tickets, testProbeTicketRequest(boundary), 41, 0, true)
}
func TestProbeTicketCancellation(t *testing.T) {
tickets := newProbeTickets(probeTicketTestAuthority)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
token, _ := issueTestProbeTicket(t, tickets, ctx, 41, 87)
cancel()
assertProbeTicketResult(t, tickets, testProbeTicketRequest(token), 41, 0, true)
if _, _, err := tickets.issue(ctx, 41, 87); !errors.Is(err, context.Canceled) {
t.Fatalf("issue with canceled context: got %v, want context.Canceled", err)
}
unclaimed, revoke := issueTestProbeTicket(t, tickets, context.Background(), 41, 88)
revoke()
revoke()
assertProbeTicketResult(t, tickets, testProbeTicketRequest(unclaimed), 41, 0, true)
live, _ := issueTestProbeTicket(t, tickets, context.Background(), 41, 89)
assertProbeTicketResult(t, tickets, testProbeTicketRequest(live).WithContext(ctx), 41, 0, true)
assertProbeTicketResult(t, tickets, testProbeTicketRequest(live), 41, 89, true)
}
func TestProbeTicketSingleConcurrentConsumer(t *testing.T) {
tickets := newProbeTickets(probeTicketTestAuthority)
token, _ := issueTestProbeTicket(t, tickets, context.Background(), 41, 87)
const clients = 12
start := make(chan struct{})
results := make(chan int64, clients)
for range clients {
r := testProbeTicketRequest(token)
r.RemoteAddr = "[::1]:9876"
go func() {
<-start
membership, _ := tickets.consume(r, 41)
results <- membership
}()
}
close(start)
accepted := 0
for range clients {
if membership := <-results; membership == 87 {
accepted++
} else if membership != 0 {
t.Errorf("unexpected membership %d", membership)
}
}
if accepted != 1 {
t.Fatalf("accepted %d consumers, want one", accepted)
}
}
func TestProbeTicketRequiresProxyAuthenticationOnSocket(t *testing.T) {
tickets := newProbeTickets(probeTicketTestAuthority)
credentials, err := NewCredentials("89d27ff5-04c2-4d10-a7d4-f13272374e66", [32]byte{1})
if err != nil {
t.Fatal(err)
}
server := httptest.NewServer(credentials.RequireProxyAuth(func(w http.ResponseWriter, r *http.Request, node int64) {
membership, present := tickets.consume(r, node)
if !present || membership != 87 {
w.WriteHeader(http.StatusForbidden)
return
}
if r.Header.Get(probeTicketHeader) != "" || r.Header.Get("Proxy-Authorization") != "" {
t.Error("internal authorization headers were not stripped")
}
w.WriteHeader(http.StatusNoContent)
}))
t.Cleanup(server.Close)
token, _ := issueTestProbeTicket(t, tickets, context.Background(), 41, 87)
request := func(node int64, password string, want int) {
t.Helper()
conn, err := net.DialTimeout("tcp", server.Listener.Addr().String(), time.Second)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if err := conn.SetDeadline(time.Now().Add(time.Second)); err != nil {
t.Fatal(err)
}
r := testProbeTicketRequest(token)
if password != "" {
basic := "node-" + strconv.FormatInt(node, 10) + ":" + password
r.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(basic)))
}
if err := r.Write(conn); err != nil {
t.Fatal(err)
}
resp, err := http.ReadResponse(bufio.NewReader(conn), r)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != want {
t.Fatalf("CONNECT status = %d, want %d", resp.StatusCode, want)
}
}
request(41, "", http.StatusProxyAuthRequired)
request(41, credentials.Password(42), http.StatusProxyAuthRequired)
request(42, credentials.Password(42), http.StatusForbidden)
request(41, credentials.Password(41), http.StatusNoContent)
request(41, credentials.Password(41), http.StatusForbidden)
}
+140
View File
@@ -0,0 +1,140 @@
package gateway
import (
"context"
"errors"
"io"
"net"
"net/http"
"sync/atomic"
"time"
)
func (p *ForwardProxy) connect(w http.ResponseWriter, upstream net.Conn) {
client, buf, err := http.NewResponseController(w).Hijack()
if err != nil {
_ = upstream.Close()
forwardError(w, http.StatusBadGateway)
return
}
// The HTTP reader may cancel the original request on a client FIN,
// even after hijack. Relay handles this as a half-close, not shutdown.
ctx := p.lifetime
if err := p.establishConnect(ctx, client); err != nil {
_ = client.Close()
_ = upstream.Close()
return
}
relayConnect(ctx, client, buf.Reader, upstream, p.timing.idle, p.timing.halfCloseGrace)
}
func (p *ForwardProxy) establishConnect(ctx context.Context, client net.Conn) error {
stop := context.AfterFunc(ctx, func() { _ = client.Close() })
defer stop()
if err := client.SetWriteDeadline(time.Now().Add(p.timing.setup)); err != nil {
return err
}
// No HTTP response has been buffered. Write the header synchronously to
// the socket, but preserve the reader that may already hold tunnel bytes.
const established = "HTTP/1.1 200 Connection Established\r\n\r\n"
if _, err := (tunnelWriter{dst: client}).Write([]byte(established)); err != nil {
return err
}
return client.SetWriteDeadline(time.Time{})
}
type tunnelWriter struct {
dst io.Writer
start time.Time
progress *atomic.Int64
}
func (w tunnelWriter) Write(b []byte) (int, error) {
var written int
for written < len(b) {
n, err := w.dst.Write(b[written:])
written += n
if n > 0 && w.progress != nil {
at := int64(time.Since(w.start))
for last := w.progress.Load(); at > last; last = w.progress.Load() {
if w.progress.CompareAndSwap(last, at) {
break
}
}
}
if err != nil {
return written, err
}
if n == 0 {
return written, io.ErrShortWrite
}
}
return written, nil
}
type tunnelCopyResult struct {
err error
writeClosed bool
}
func copyTunnel(dst net.Conn, src io.Reader, writer tunnelWriter, done chan<- tunnelCopyResult) {
_, err := io.Copy(writer, src)
if err != nil {
done <- tunnelCopyResult{err: err}
return
}
// A wrapper embedding net.Conn does not imply its framing, or even its
// underlying socket, has a meaningful half-close operation.
if half, ok := dst.(interface{ CloseWrite() error }); ok {
err := half.CloseWrite()
if !errors.Is(err, errors.ErrUnsupported) {
done <- tunnelCopyResult{err: err, writeClosed: err == nil}
return
}
}
done <- tunnelCopyResult{}
}
func relayConnect(ctx context.Context, client net.Conn, clientReader io.Reader, upstream net.Conn, idle, halfCloseGrace time.Duration) {
start := time.Now()
var progress atomic.Int64
done := make(chan tunnelCopyResult, 2)
go copyTunnel(upstream, clientReader, tunnelWriter{upstream, start, &progress}, done)
go copyTunnel(client, upstream, tunnelWriter{client, start, &progress}, done)
timer := time.NewTimer(idle)
defer timer.Stop()
var grace *time.Timer
var graceExpired <-chan time.Time
remaining := 2
relay:
for remaining != 0 {
select {
case <-ctx.Done():
break relay
case result := <-done:
remaining--
if result.err != nil {
break relay
}
if !result.writeClosed && remaining != 0 {
grace = time.NewTimer(halfCloseGrace)
defer grace.Stop()
graceExpired = grace.C
}
case <-graceExpired:
break relay
case <-timer.C:
sinceProgress := time.Since(start) - time.Duration(progress.Load())
if sinceProgress >= idle {
break relay
}
timer.Reset(idle - sinceProgress)
}
}
_ = client.Close()
_ = upstream.Close()
for ; remaining != 0; remaining-- {
<-done
}
}
+336
View File
@@ -0,0 +1,336 @@
package gateway
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"sync/atomic"
"testing"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
"git.eeee.moe/omar/zhguchiy_perchik/internal/upstream"
)
type forwardTestShortTCP struct{ *net.TCPConn }
func (c forwardTestShortTCP) Write(b []byte) (int, error) {
return c.TCPConn.Write(b[:min(len(b), 17)])
}
func TestForwardConnectEarlyBytesPartialWritesAndHalfClose(t *testing.T) {
listener, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
early := "early\x01\x00tunnel data"
payload := bytes.Repeat([]byte("many binary frames\x00\xff"), 4096)
want := append([]byte(early), payload...)
originDone := make(chan error, 1)
go func() {
originDone <- func() error {
c, err := listener.Accept()
if err != nil {
return err
}
defer c.Close()
if err := c.SetDeadline(time.Now().Add(forwardTestDeadline)); err != nil {
return err
}
// Reply only after the proxy has propagated the client's FIN.
got, err := io.ReadAll(c)
if err != nil || !bytes.Equal(got, want) {
return fmt.Errorf("origin read %d/%d bytes: %v", len(got), len(want), err)
}
_, err = c.Write(got)
return err
}()
}()
p := newForwardTestProxy(forwardTestStore{ready: forwardTestReady}, func(ctx context.Context, _ *upstream.Upstream, dest string) (net.Conn, error) {
c, err := new(net.Dialer).DialContext(ctx, "tcp", dest)
if err != nil {
return nil, err
}
return forwardTestShortTCP{c.(*net.TCPConn)}, nil
}, nil, listener.Addr().String())
addr, credentials := serveForwardTest(t, p)
c, r := forwardTestTCP(t, addr)
forwardTestConnect(t, c, r, forwardTestBasic(credentials, 1), "", early, 200)
if _, err := c.Write(payload); err != nil {
t.Fatal(err)
}
if err := c.CloseWrite(); err != nil {
t.Fatal(err)
}
got, err := io.ReadAll(r)
if err != nil || !bytes.Equal(got, want) {
t.Fatalf("client read %d/%d bytes: %v", len(got), len(want), err)
}
if err := forwardTestReceive(t, originDone); err != nil {
t.Fatal(err)
}
}
func TestForwardConnectWithoutHalfCloseGivesReverseFlowGrace(t *testing.T) {
relay, peer := net.Pipe() // net.Conn without CloseWrite.
defer peer.Close()
_ = peer.SetDeadline(time.Now().Add(forwardTestDeadline))
p := newForwardTestProxy(forwardTestStore{ready: forwardTestReady}, func(context.Context, *upstream.Upstream, string) (net.Conn, error) {
return relay, nil
}, nil, "192.0.2.77:443")
p.timing.halfCloseGrace = 300 * time.Millisecond
addr, credentials := serveForwardTest(t, p)
c, r := forwardTestTCP(t, addr)
forwardTestConnect(t, c, r, forwardTestBasic(credentials, 1), "", "", 200)
if err := c.CloseWrite(); err != nil {
t.Fatal(err)
}
if _, err := io.WriteString(peer, "reply"); err != nil {
t.Fatalf("reverse flow closed before grace period: %v", err)
}
got, err := io.ReadAll(r)
if err != nil || string(got) != "reply" {
t.Fatalf("reverse flow: %q, %v", got, err)
}
var b [1]byte
if _, err := peer.Read(b[:]); err != io.EOF {
t.Fatalf("upstream socket not closed at end of grace: %v", err)
}
}
func TestForwardConnectIdleTracksBidirectionalProgress(t *testing.T) {
relay, peer := net.Pipe()
defer peer.Close()
_ = peer.SetDeadline(time.Now().Add(forwardTestDeadline))
p := newForwardTestProxy(forwardTestStore{ready: forwardTestReady}, func(context.Context, *upstream.Upstream, string) (net.Conn, error) {
return relay, nil
}, nil, "192.0.2.77:443")
p.timing.setup = 300 * time.Millisecond
p.timing.idle = 350 * time.Millisecond
addr, credentials := serveForwardTest(t, p)
c, r := forwardTestTCP(t, addr)
forwardTestConnect(t, c, r, forwardTestBasic(credentials, 1), "", "", 200)
ticker := time.NewTicker(55 * time.Millisecond)
defer ticker.Stop()
var b [1]byte
for n := byte(0); n < 14; n++ {
<-ticker.C
if n < 7 {
if _, err := peer.Write([]byte{n}); err != nil {
t.Fatal(err)
}
got, err := r.ReadByte()
if err != nil || got != n {
t.Fatalf("reverse byte %d: %d %v", n, got, err)
}
} else {
if _, err := c.Write([]byte{n}); err != nil {
t.Fatal(err)
}
if _, err := peer.Read(b[:]); err != nil || b[0] != n {
t.Fatalf("forward byte %d: %d %v", n, b[0], err)
}
}
}
if _, err := r.ReadByte(); err != io.EOF {
t.Fatalf("idle client connection was not closed: %v", err)
}
if _, err := peer.Read(b[:]); err != io.EOF {
t.Fatalf("idle upstream connection was not closed: %v", err)
}
}
func TestForwardConnectSetupTimeoutAndDisconnectCancelDial(t *testing.T) {
for _, tc := range []struct {
name string
want error
}{{"timeout", context.DeadlineExceeded}, {"disconnect", context.Canceled}} {
t.Run(tc.name, func(t *testing.T) {
dialEntered := make(chan struct{})
dialExited := make(chan error, 1)
p := newForwardTestProxy(forwardTestStore{ready: forwardTestReady}, func(ctx context.Context, _ *upstream.Upstream, _ string) (net.Conn, error) {
close(dialEntered)
<-ctx.Done()
dialExited <- ctx.Err()
return nil, ctx.Err()
}, nil, "192.0.2.77:443")
if tc.want == context.DeadlineExceeded {
p.timing.setup = 300 * time.Millisecond
}
addr, credentials := serveForwardTest(t, p)
c, r := forwardTestTCP(t, addr)
if tc.want == context.DeadlineExceeded {
forwardTestConnect(t, c, r, forwardTestBasic(credentials, 1), "", "", 504)
} else {
if _, err := fmt.Fprintf(c, "CONNECT %[1]s HTTP/1.1\r\nHost: %[1]s\r\n%[2]s\r\n", forwardTestAuthority, forwardTestBasic(credentials, 1)); err != nil {
t.Fatal(err)
}
forwardTestReceive(t, dialEntered)
_ = c.Close()
}
if err := forwardTestReceive(t, dialExited); err != tc.want {
t.Fatalf("dial context = %v, want %v", err, tc.want)
}
})
}
}
func TestForwardSeparateProbeBudgetAndShutdownClosesHijacks(t *testing.T) {
var ordinary, probe atomic.Int32
store := forwardTestStore{
ready: func(id int64) (*db.GatewayNode, error) {
ordinary.Add(1)
if id != 1 {
return nil, nil
}
return forwardTestReady(id)
},
probe: func(id, membership int64) (*db.GatewayNode, error) {
probe.Add(1)
if membership == 21 {
return nil, errors.New("fixture DB unavailable")
}
if membership == 20 {
return forwardTestNode(id, 23), nil
}
if id != 2 || membership != 23 {
return nil, nil
}
return forwardTestNode(id, membership), nil
},
}
tickets := newProbeTickets(forwardTestAuthority)
peers := make(chan net.Conn, 2)
p := newForwardTestProxy(store, func(_ context.Context, u *upstream.Upstream, _ string) (net.Conn, error) {
if u.Host != "peer1.fixture" && u.Host != "peer2.fixture" {
return nil, errors.New("proxy selected an unrequested peer")
}
relay, remote := net.Pipe()
peers <- remote
return relay, nil
}, tickets, "192.0.2.77:443")
if cap(p.users) != 256 || cap(p.probes) != 8 {
t.Fatal("unexpected production connection limits")
}
p.users, p.probes = make(chan struct{}, 1), make(chan struct{}, 1)
addr, credentials := serveForwardTest(t, p)
auth1, auth2 := forwardTestBasic(credentials, 1), forwardTestBasic(credentials, 2)
issue := func(membership int64) string {
t.Helper()
ticket, revoke, err := tickets.issue(context.Background(), 2, membership)
if err != nil {
t.Fatal(err)
}
t.Cleanup(revoke)
return ticket
}
request := func(auth, ticket string, status int) *http.Response {
t.Helper()
c, r := forwardTestTCP(t, addr)
defer c.Close()
return forwardTestConnect(t, c, r, auth, ticket, "", status)
}
request(auth2, "", 503) // pending: ordinary access cannot open the node.
request(auth2, issue(22), http.StatusConflict) // exact membership no longer exists.
request(auth2, issue(20), http.StatusConflict) // returned membership differs from the ticket.
request(auth2, issue(21), http.StatusServiceUnavailable)
a, ar := forwardTestTCP(t, addr)
forwardTestConnect(t, a, ar, auth1, "", "", 200)
pa := forwardTestReceive(t, peers)
defer pa.Close()
if h := request(auth1, "", 503).Header.Get("Retry-After"); h == "" {
t.Fatal("full ordinary budget did not advertise Retry-After")
}
ticket := issue(23)
request("", ticket, 407) // authentication must run before ticket consumption.
b, br := forwardTestTCP(t, addr)
forwardTestConnect(t, b, br, auth2, ticket, "", 200)
pb := forwardTestReceive(t, peers)
defer pb.Close()
request(auth2, ticket, 403) // replay never reaches the lookup.
if h := request(auth2, issue(23), 503).Header.Get("Retry-After"); h == "" {
t.Fatal("full probe budget did not advertise Retry-After")
}
if ordinary.Load() != 2 || probe.Load() != 4 {
t.Fatalf("unexpected ready/exact lookups: %d %d", ordinary.Load(), probe.Load())
}
ctx, cancel := context.WithTimeout(context.Background(), forwardTestDeadline)
defer cancel()
if err := p.Shutdown(ctx); err != nil {
t.Fatal(err)
}
for _, r := range []io.Reader{ar, br, pa, pb} {
var b [1]byte
if c, ok := r.(net.Conn); ok {
_ = c.SetReadDeadline(time.Now().Add(forwardTestDeadline))
}
if n, err := r.Read(b[:]); n != 0 || !errors.Is(err, io.EOF) {
t.Fatalf("socket still open or got a synthetic error response: %d, %v", n, err)
}
}
request(auth1, "", 503)
}
func TestForwardProbeTimeoutClassification(t *testing.T) {
for _, tc := range []struct {
name string
probe bool
routeFail bool
status int
}{
{"ordinary route timeout", false, true, http.StatusGatewayTimeout},
{"probe route timeout", true, true, http.StatusServiceUnavailable},
{"probe upstream timeout", true, false, http.StatusGatewayTimeout},
} {
t.Run(tc.name, func(t *testing.T) {
results := make(chan time.Duration, 1)
store := forwardTestStore{
ready: forwardTestReady,
probe: func(id, membership int64) (*db.GatewayNode, error) {
return forwardTestNode(id, membership), nil
},
}
tickets := newProbeTickets(forwardTestAuthority)
p := newForwardTestProxy(store, func(ctx context.Context, _ *upstream.Upstream, _ string) (net.Conn, error) {
deadline, _ := ctx.Deadline()
results <- time.Until(deadline)
return nil, context.DeadlineExceeded
}, tickets, "192.0.2.77:443")
if tc.routeFail {
p.resolveRequest = func(context.Context, *http.Request) (string, string, error) {
return "", "", context.DeadlineExceeded
}
}
addr, credentials := serveForwardTest(t, p)
c, r := forwardTestTCP(t, addr)
var ticket string
if tc.probe {
var revoke func()
var err error
ticket, revoke, err = tickets.issue(t.Context(), 1, 23)
if err != nil {
t.Fatal(err)
}
defer revoke()
}
forwardTestConnect(t, c, r, forwardTestBasic(credentials, 1), ticket, "", tc.status)
if tc.routeFail {
select {
case <-results:
t.Fatal("route failure reached the selected upstream")
default:
}
} else if remaining := forwardTestReceive(t, results); remaining <= 0 || remaining > probeTicketTTL-time.Second {
t.Fatalf("probe upstream deadline lacks monitor headroom: %v", remaining)
}
})
}
}
+416
View File
@@ -0,0 +1,416 @@
package gateway
import (
"context"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/netip"
"strconv"
"sync"
"sync/atomic"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
)
const (
defaultProxyAddr = ":8081"
defaultAPIAddr = ":8082"
)
// RuntimeOptions configures local listeners and builds their real components.
// The zero addresses use the container defaults. Build is called once, after
// binding both listeners and acquiring the database lease, before serving traffic.
// Its context scopes construction only; Monitor receives its own run context.
type RuntimeOptions struct {
ProxyAddr string
APIAddr string
Build func(context.Context, RuntimeEndpoints) (RuntimeComponents, error)
}
// RuntimeEndpoints are derived from bound sockets and the initialized database,
// not from incoming requests. Only the runtime may release the lease.
type RuntimeEndpoints struct {
ProxyAddr string
APIAddr string
ProbeProxyAddr string
Credentials Credentials
Lease *db.GatewayLease
}
// RuntimeComponents must all be provided by the caller. Catalog serves only
// authenticated GET /v1/proxies and reads the live DB for each request. Monitor
// must run until cancellation or a fatal error without owning lease or heartbeat.
type RuntimeComponents struct {
Catalog http.Handler
Proxy ProxyLifecycle
Monitor func(context.Context) error
}
// ProxyLifecycle receives one authenticated request per call and checks the
// selected node's availability. Shutdown must stop accepting tunnels, close all
// hijacked sockets, and wait for their handlers; net/http no longer owns them.
type ProxyLifecycle interface {
ServeProxy(http.ResponseWriter, *http.Request, int64)
Shutdown(context.Context) error
}
type runtimeTiming struct {
startup, retry, dbCall, heartbeat, shutdown time.Duration
}
// Run owns both listeners, the database lease, the monitor, and their shutdown.
// Call it with validated launch configuration and an opened DB (which the caller
// closes after Run returns). A signal-driven cancellation is a normal exit.
func Run(ctx context.Context, store *db.DB, cfg Config, opts RuntimeOptions) error {
if store == nil {
return errors.New("gateway database is required")
}
return runGateway(ctx, store, cfg, opts, runtimeTiming{
startup: 30 * time.Second,
retry: time.Second,
dbCall: 2 * time.Second,
heartbeat: 10 * time.Second,
shutdown: 10 * time.Second,
}, new(net.ListenConfig).Listen)
}
type runtimeActive struct {
lease *db.GatewayLease
catalog http.Handler
proxy http.Handler
heartbeat atomic.Bool
}
type gatewayRuntime struct {
ctx context.Context
store *db.DB
timing runtimeTiming
active atomic.Pointer[runtimeActive]
}
func runGateway(parent context.Context, store *db.DB, cfg Config, opts RuntimeOptions, timing runtimeTiming, listen func(context.Context, string, string) (net.Listener, error)) (result error) {
if opts.Build == nil {
return errors.New("gateway component factory is required")
}
if parent.Err() != nil {
return nil
}
if opts.ProxyAddr == "" {
opts.ProxyAddr = defaultProxyAddr
}
if opts.APIAddr == "" {
opts.APIAddr = defaultAPIAddr
}
proxyListener, err := listen(parent, "tcp", opts.ProxyAddr)
if err != nil {
if parent.Err() != nil {
return nil
}
return errors.New("could not bind gateway proxy listener")
}
defer proxyListener.Close()
apiListener, err := listen(parent, "tcp", opts.APIAddr)
if err != nil {
if parent.Err() != nil {
return nil
}
return errors.New("could not bind gateway API listener")
}
defer apiListener.Close()
probeProxyAddr, err := runtimeLoopbackAddr(proxyListener.Addr())
if err != nil {
return err
}
ctx, stop := context.WithCancelCause(parent)
runtime := &gatewayRuntime{ctx: ctx, store: store, timing: timing}
apiServer := gatewayHTTPServer(ctx, runtime.apiHandler(cfg.APIToken))
proxyServer := gatewayHTTPServer(ctx, http.HandlerFunc(runtime.serveProxy))
var workers sync.WaitGroup
var components RuntimeComponents
var lease *db.GatewayLease
defer func() {
stop(nil)
runtime.active.Store(nil)
result = errors.Join(result, shutdownGateway(timing.shutdown, apiServer, proxyServer, components.Proxy))
workers.Wait()
if lease != nil {
result = errors.Join(result, closeRuntimeLease(lease, timing.dbCall))
}
}()
for _, entry := range []struct {
name string
server *http.Server
listener net.Listener
}{
{"API", apiServer, apiListener},
{"proxy", proxyServer, proxyListener},
} {
workers.Go(func() {
if err := entry.server.Serve(entry.listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
stop(fmt.Errorf("gateway %s listener stopped", entry.name))
}
})
}
startCtx, cancelStart := context.WithTimeout(ctx, timing.startup)
defer cancelStart()
var storeUUID string
lease, storeUUID, err = runtime.awaitStore(startCtx)
if err != nil {
if ctx.Err() != nil {
return runtimeExit(parent, ctx)
}
return err
}
workers.Go(func() {
select {
case <-lease.Lost():
stop(db.ErrGatewayLeaseLost)
case <-ctx.Done():
}
})
credentials, err := NewCredentials(storeUUID, cfg.NodeSecret)
if err != nil {
return errors.New("invalid gateway store identity")
}
components, err = opts.Build(startCtx, RuntimeEndpoints{
ProxyAddr: proxyListener.Addr().String(),
APIAddr: apiListener.Addr().String(),
ProbeProxyAddr: probeProxyAddr,
Credentials: credentials,
Lease: lease,
})
if ctx.Err() != nil {
return runtimeExit(parent, ctx)
}
if err != nil {
return errors.New("could not initialize gateway components")
}
if startCtx.Err() != nil {
return errors.New("gateway component startup deadline expired")
}
if components.Catalog == nil || components.Proxy == nil || components.Monitor == nil {
return errors.New("gateway catalog, proxy, and monitor are required")
}
// Construction may take time; check the dedicated connection again before
// publishing the handlers it protects.
checkCtx, cancelCheck := context.WithTimeout(startCtx, timing.dbCall)
err = lease.Check(checkCtx)
cancelCheck()
if ctx.Err() != nil {
return runtimeExit(parent, ctx)
}
if errors.Is(err, db.ErrGatewayLeaseLost) {
return db.ErrGatewayLeaseLost
}
if err != nil {
return errors.New("could not verify gateway database lease")
}
cancelStart()
active := &runtimeActive{
lease: lease,
catalog: components.Catalog,
proxy: credentials.RequireProxyAuth(proxyFormHandler(components.Proxy)),
}
active.heartbeat.Store(true)
runtime.active.Store(active)
workers.Go(func() { runtime.heartbeat(active, stop) })
workers.Go(func() {
err := components.Monitor(ctx)
if ctx.Err() != nil {
return
}
if errors.Is(err, db.ErrGatewayLeaseLost) {
stop(db.ErrGatewayLeaseLost)
return
}
stop(errors.New("gateway monitor stopped"))
})
<-ctx.Done()
return runtimeExit(parent, ctx)
}
func runtimeExit(parent, ctx context.Context) error {
cause := context.Cause(ctx)
if errors.Is(cause, context.Canceled) || (parent.Err() != nil && errors.Is(cause, context.Cause(parent))) {
return nil
}
return cause
}
func runtimeLoopbackAddr(addr net.Addr) (string, error) {
tcp, ok := addr.(*net.TCPAddr)
if !ok {
return "", errors.New("gateway proxy listener must use TCP")
}
ip := tcp.AddrPort().Addr().Unmap()
if ip.IsUnspecified() {
if ip.Is4() {
ip = netip.AddrFrom4([4]byte{127, 0, 0, 1})
} else {
ip = netip.IPv6Loopback()
}
}
if !ip.IsLoopback() {
return "", errors.New("gateway proxy listener must be reachable on loopback")
}
return net.JoinHostPort(ip.String(), strconv.Itoa(tcp.Port)), nil
}
func (rt *gatewayRuntime) awaitStore(ctx context.Context) (*db.GatewayLease, string, error) {
timer := time.NewTimer(rt.timing.retry)
timer.Stop()
defer timer.Stop()
var last error
for ctx.Err() == nil {
attempt, cancel := context.WithTimeout(ctx, rt.timing.dbCall)
lease, uuid, err := rt.initStore(attempt)
cancel()
if err == nil {
return lease, uuid, nil
}
// A canceled final attempt must not erase a known contention result.
if ctx.Err() != nil && !errors.Is(err, db.ErrGatewayLeaseHeld) {
break
}
last = err
timer.Reset(rt.timing.retry)
select {
case <-ctx.Done():
case <-timer.C:
}
}
if errors.Is(last, db.ErrGatewayLeaseHeld) {
return nil, "", db.ErrGatewayLeaseHeld
}
return nil, "", errors.New("gateway database startup deadline expired")
}
func (rt *gatewayRuntime) initStore(ctx context.Context) (*db.GatewayLease, string, error) {
if _, err := rt.store.GatewayStatus(ctx, time.Time{}); err != nil {
return nil, "", err
}
uuid, err := rt.store.GatewayStoreUUID(ctx)
if err != nil {
return nil, "", err
}
lease, err := rt.store.AcquireGatewayLease(ctx)
if err != nil {
return nil, "", err
}
if err := lease.Heartbeat(ctx, time.Now()); err != nil {
_ = closeRuntimeLease(lease, rt.timing.dbCall)
return nil, "", err
}
return lease, uuid, nil
}
func (rt *gatewayRuntime) heartbeat(active *runtimeActive, stop context.CancelCauseFunc) {
ticker := time.NewTicker(rt.timing.heartbeat)
defer ticker.Stop()
for {
select {
case <-rt.ctx.Done():
return
case <-ticker.C:
ctx, cancel := context.WithTimeout(rt.ctx, rt.timing.dbCall)
err := active.lease.Heartbeat(ctx, time.Now())
cancel()
active.heartbeat.Store(err == nil)
if errors.Is(err, db.ErrGatewayLeaseLost) {
stop(db.ErrGatewayLeaseLost)
return
}
}
}
}
func (rt *gatewayRuntime) serving() *runtimeActive {
active := rt.active.Load()
if active == nil || rt.ctx.Err() != nil || !active.heartbeat.Load() {
return nil
}
select {
case <-active.lease.Lost():
return nil
default:
return active
}
}
func (rt *gatewayRuntime) serveProxy(w http.ResponseWriter, r *http.Request) {
active := rt.serving()
if active == nil {
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
return
}
active.proxy.ServeHTTP(w, r)
}
func proxyFormHandler(proxy ProxyLifecycle) func(http.ResponseWriter, *http.Request, int64) {
return func(w http.ResponseWriter, r *http.Request, id int64) {
u := r.URL
if r.Method == http.MethodConnect {
if u.Host == "" || u.Scheme != "" || r.RequestURI != u.Host {
http.Error(w, "CONNECT requires authority form", http.StatusBadRequest)
return
}
} else if u.Scheme != "http" || u.Host == "" {
http.Error(w, "proxy requires absolute HTTP form", http.StatusBadRequest)
return
}
proxy.ServeProxy(w, r, id)
}
}
func gatewayHTTPServer(ctx context.Context, handler http.Handler) *http.Server {
return &http.Server{
Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 2 * time.Minute,
MaxHeaderBytes: 32 << 10,
DisableGeneralOptionsHandler: true,
BaseContext: func(net.Listener) context.Context { return ctx },
// net/http may print a panic value containing untrusted request data.
ErrorLog: log.New(io.Discard, "", 0),
}
}
func shutdownGateway(timeout time.Duration, api, proxy *http.Server, lifecycle ProxyLifecycle) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
results := make(chan error, 2)
for _, server := range []*http.Server{api, proxy} {
go func() {
if err := server.Shutdown(ctx); err != nil {
_ = server.Close()
results <- errors.New("gateway HTTP shutdown deadline expired")
return
}
results <- nil
}()
}
var err error
if lifecycle != nil {
if shutdownErr := lifecycle.Shutdown(ctx); shutdownErr != nil {
err = errors.New("gateway tunnel shutdown failed")
}
}
return errors.Join(err, <-results, <-results)
}
func closeRuntimeLease(lease *db.GatewayLease, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if err := lease.Close(ctx); err != nil {
return errors.New("could not close gateway database lease")
}
return nil
}
+500
View File
@@ -0,0 +1,500 @@
package gateway
import (
"bufio"
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
"github.com/jackc/pgx/v5"
)
func TestGatewayRuntimeSecondBindFailure(t *testing.T) {
occupied, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer occupied.Close()
var firstAddr string
var bindings int
opts := RuntimeOptions{
ProxyAddr: "127.0.0.1:0",
APIAddr: occupied.Addr().String(),
Build: func(context.Context, RuntimeEndpoints) (RuntimeComponents, error) {
t.Fatal("built components despite failure to bind both listeners")
return RuntimeComponents{}, nil
},
}
err = runGateway(t.Context(), nil, Config{}, opts, runtimeTiming{}, func(ctx context.Context, network, addr string) (net.Listener, error) {
listener, err := new(net.ListenConfig).Listen(ctx, network, addr)
bindings++
if bindings == 1 && err == nil {
firstAddr = listener.Addr().String()
}
return listener, err
})
if err == nil || err.Error() != "could not bind gateway API listener" || firstAddr == "" || bindings != 2 {
t.Fatalf("did not reach second bind and fail cleanly: %v, bindings=%d", err, bindings)
}
assertRuntimeListenerClosed(t, firstAddr)
}
func TestGatewayRuntimePostgres(t *testing.T) {
cluster := newRuntimeTestDatabase(t)
cfg := Config{APIToken: base64.RawURLEncoding.EncodeToString([]byte(strings.Repeat("a", 32))), NodeSecret: [32]byte{1}}
timing := runtimeTiming{startup: 4 * time.Second, retry: 15 * time.Millisecond, dbCall: time.Second, heartbeat: 25 * time.Millisecond, shutdown: time.Second}
t.Run("schema readiness and canceled retry", func(t *testing.T) {
store := cluster.store(t)
components := newRuntimeTestComponents()
first := startRuntimeTest(t, store, cfg, timing, components.build)
assertRuntimeStarting(t, first, cfg)
first.cancel()
if err := first.wait(t); err != nil {
t.Fatalf("cancel during schema wait: %v", err)
}
assertRuntimeListenerClosed(t, first.api)
assertRuntimeListenerClosed(t, first.proxy)
select {
case <-components.endpoints:
t.Fatal("components were built before schema was applied")
default:
}
expiryTiming := timing
expiryTiming.startup = 300 * time.Millisecond
expired := startRuntimeTest(t, store, cfg, expiryTiming, components.build)
if err := expired.wait(t); err == nil || err.Error() != "gateway database startup deadline expired" {
t.Fatalf("start without schema did not hit its deadline: %v", err)
}
assertRuntimeListenerClosed(t, expired.api)
assertRuntimeListenerClosed(t, expired.proxy)
second := startRuntimeTest(t, store, cfg, timing, components.build)
assertRuntimeStarting(t, second, cfg)
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
defer cancel()
if err := store.ApplySchema(ctx); err != nil {
t.Fatal(err)
}
waitRuntimeEvent(t, components.started)
assertRuntimeAPI(t, second.api, cfg)
// Drop a required projection from the request's search path, leaving the
// lease and heartbeat intact. A live process is not proof of readiness.
if _, err := store.Pool().Exec(ctx, `ALTER VIEW gateway_candidates RENAME TO gateway_candidates_unavailable`); err != nil {
t.Fatal(err)
}
assertRuntimeHTTP(t, second.api, http.MethodGet, "/healthz", "", http.StatusOK)
assertRuntimeHTTP(t, second.api, http.MethodGet, "/readyz", "", http.StatusServiceUnavailable)
assertRuntimeHTTP(t, second.api, http.MethodGet, "/v1/status", runtimeBearer(cfg), http.StatusServiceUnavailable)
second.cancel()
if err := second.wait(t); err != nil {
t.Fatalf("shutdown after schema failure: %v", err)
}
})
t.Run("contention, authorization, heartbeat and shutdown", func(t *testing.T) {
store := cluster.store(t)
applyRuntimeSchema(t, store)
components := newRuntimeTestComponents()
first := startRuntimeTest(t, store, cfg, timing, components.build)
waitRuntimeEvent(t, components.started)
endpoint := <-components.endpoints
if endpoint.Lease == nil || endpoint.APIAddr != first.api || endpoint.ProxyAddr != first.proxy || endpoint.ProbeProxyAddr != first.proxy {
t.Fatal("factory did not receive the active lease and bound listener addresses")
}
assertRuntimeAPI(t, first.api, cfg)
assertRuntimePortAuth(t, first, cfg, endpoint.Credentials)
assertRuntimeHeartbeat(t, store)
contender := newRuntimeTestComponents()
contentionTiming := timing
contentionTiming.startup = time.Second
second := startRuntimeTest(t, store, cfg, contentionTiming, contender.build)
assertRuntimeStarting(t, second, cfg)
assertRuntimeHTTP(t, second.proxy, http.MethodGet, "http://origin.test/", runtimeProxyAuth(endpoint.Credentials, 42), http.StatusServiceUnavailable)
if err := second.wait(t); !errors.Is(err, db.ErrGatewayLeaseHeld) {
t.Fatalf("contending runtime exit = %v, want lease held", err)
}
select {
case <-contender.endpoints:
t.Fatal("contender built active components")
default:
}
assertRuntimeListenerClosed(t, second.api)
assertRuntimeListenerClosed(t, second.proxy)
assertRuntimeHTTP(t, first.api, http.MethodGet, "/readyz", "", http.StatusOK)
conn, reader := dialRuntimeWire(t, first.proxy)
defer conn.Close()
response := exchangeRuntimeWire(t, conn, reader, http.MethodConnect, "origin.test:443", runtimeProxyAuth(endpoint.Credentials, 42))
if response.StatusCode != http.StatusOK {
response.Body.Close()
t.Fatalf("tunnel setup status = %d", response.StatusCode)
}
first.cancel()
if err := first.wait(t); err != nil {
t.Fatalf("graceful shutdown: %v", err)
}
if _, err := reader.ReadByte(); !errors.Is(err, io.EOF) {
t.Fatalf("hijacked socket not closed on shutdown: %v", err)
}
waitRuntimeEvent(t, components.proxy.tunnelDone)
waitRuntimeEvent(t, components.stopped)
assertRuntimeListenerClosed(t, first.api)
assertRuntimeListenerClosed(t, first.proxy)
assertRuntimeLeaseAvailable(t, store)
})
for _, viaReady := range []bool{false, true} {
name := "heartbeat detects idle lease loss"
if viaReady {
name = "readiness verifies the actual lease"
}
t.Run(name, func(t *testing.T) {
store := cluster.store(t)
applyRuntimeSchema(t, store)
components := newRuntimeTestComponents()
lossTiming := timing
if viaReady {
lossTiming.heartbeat = time.Hour // readiness must check before the next tick
}
instance := startRuntimeTest(t, store, cfg, lossTiming, components.build)
waitRuntimeEvent(t, components.started)
assertRuntimeHTTP(t, instance.api, http.MethodGet, "/readyz", "", http.StatusOK)
terminateRuntimeLease(t, store)
if viaReady {
assertRuntimeHTTP(t, instance.api, http.MethodGet, "/readyz", "", http.StatusServiceUnavailable)
}
if err := instance.wait(t); !errors.Is(err, db.ErrGatewayLeaseLost) {
t.Fatalf("runtime exit = %v, want lease lost", err)
}
waitRuntimeEvent(t, components.stopped)
waitRuntimeEvent(t, components.proxy.closed)
assertRuntimeListenerClosed(t, instance.api)
assertRuntimeListenerClosed(t, instance.proxy)
assertRuntimeLeaseAvailable(t, store)
})
}
}
type runtimeTestDatabase string
func newRuntimeTestDatabase(t *testing.T) runtimeTestDatabase {
t.Helper()
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("set TEST_DATABASE_URL to a PostgreSQL test database")
}
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
admin, err := pgx.Connect(ctx, dsn)
if err != nil {
t.Fatal("could not connect to PostgreSQL test database")
}
t.Cleanup(func() { _ = admin.Close(context.Background()) })
// The product lock is database-wide, so a separate database also isolates
// this suite from simultaneous internal/db acceptance tests.
name := "gateway_runtime_" + strings.ToLower(rand.Text())
quoted := pgx.Identifier{name}.Sanitize()
if _, err := admin.Exec(ctx, "CREATE DATABASE "+quoted); err != nil {
t.Fatalf("create isolated runtime test database (requires CREATEDB): %v", err)
}
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := admin.Exec(ctx, "DROP DATABASE "+quoted); err != nil {
t.Errorf("drop isolated runtime test database: %v", err)
}
})
if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {
uri, err := url.Parse(dsn)
if err != nil {
t.Fatal("invalid test database URI")
}
uri.Path, uri.RawPath = "/"+name, ""
params := uri.Query()
params.Del("dbname")
params.Del("database")
uri.RawQuery = params.Encode()
return runtimeTestDatabase(uri.String())
}
return runtimeTestDatabase(dsn + " dbname=" + name)
}
func (dsn runtimeTestDatabase) store(t *testing.T) *db.DB {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
defer cancel()
unscoped, err := db.New(ctx, string(dsn))
if err != nil {
t.Fatal("could not open the isolated runtime test database")
}
defer unscoped.Close()
schema := "runtime_" + strings.ToLower(rand.Text())
if _, err := unscoped.Pool().Exec(ctx, "CREATE SCHEMA "+pgx.Identifier{schema}.Sanitize()); err != nil {
t.Fatalf("create runtime test schema: %v", err)
}
scoped := string(dsn) + " search_path=" + schema
if strings.HasPrefix(string(dsn), "postgres://") || strings.HasPrefix(string(dsn), "postgresql://") {
uri, err := url.Parse(string(dsn))
if err != nil {
t.Fatal("invalid isolated database URI")
}
params := uri.Query()
params.Set("search_path", schema)
uri.RawQuery = params.Encode()
scoped = uri.String()
}
store, err := db.New(ctx, scoped)
if err != nil {
t.Fatal("could not open the isolated runtime test schema")
}
t.Cleanup(store.Close)
return store
}
func applyRuntimeSchema(t *testing.T, store *db.DB) {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
defer cancel()
if err := store.ApplySchema(ctx); err != nil {
t.Fatal(err)
}
}
func assertRuntimeHeartbeat(t *testing.T, store *db.DB) {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
read := func() time.Time {
var at time.Time
if err := store.Pool().QueryRow(ctx, `SELECT heartbeat_at FROM gateway_runtime WHERE id = 1`).Scan(&at); err != nil {
t.Fatalf("read gateway heartbeat: %v", err)
}
return at
}
initial := read()
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
t.Fatal("heartbeat did not advance while the monitor was blocked")
case <-ticker.C:
if read().After(initial) {
return
}
}
}
}
func terminateRuntimeLease(t *testing.T, store *db.DB) {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
defer cancel()
var pid int32
if err := store.Pool().QueryRow(ctx, `SELECT pid FROM pg_catalog.pg_locks
WHERE locktype = 'advisory' AND mode = 'ExclusiveLock' AND granted
AND classid = 0 AND objid = 72640821 AND objsubid = 1
AND database = (SELECT oid FROM pg_catalog.pg_database WHERE datname = current_database())`).Scan(&pid); err != nil {
t.Fatalf("find dedicated test lease backend: %v", err)
}
var terminated bool
if err := store.Pool().QueryRow(ctx, `SELECT pg_terminate_backend($1, 1000)`, pid).Scan(&terminated); err != nil || !terminated {
t.Fatalf("terminate dedicated test lease backend: %v, %v", terminated, err)
}
}
func assertRuntimeLeaseAvailable(t *testing.T, store *db.DB) {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
lease, err := store.AcquireGatewayLease(ctx)
if err != nil {
t.Fatalf("runtime did not release lease: %v", err)
}
if err := lease.Close(ctx); err != nil {
t.Fatalf("close replacement lease: %v", err)
}
}
type runtimeTestInstance struct {
api, proxy string
cancel context.CancelFunc
done chan struct{}
err error // published by closing done
}
func startRuntimeTest(t *testing.T, store *db.DB, cfg Config, timing runtimeTiming, build func(context.Context, RuntimeEndpoints) (RuntimeComponents, error)) *runtimeTestInstance {
t.Helper()
ctx, cancel := context.WithCancel(t.Context())
instance := &runtimeTestInstance{cancel: cancel, done: make(chan struct{})}
t.Cleanup(func() {
cancel()
waitRuntimeEvent(t, instance.done)
})
addresses := make(chan string, 2)
go func() {
defer close(instance.done)
opts := RuntimeOptions{ProxyAddr: "127.0.0.1:0", APIAddr: "127.0.0.1:0", Build: build}
instance.err = runGateway(ctx, store, cfg, opts, timing, func(ctx context.Context, network, addr string) (net.Listener, error) {
listener, err := new(net.ListenConfig).Listen(ctx, network, addr)
if err == nil {
addresses <- listener.Addr().String()
}
return listener, err
})
}()
readAddress := func() string {
select {
case address := <-addresses:
return address
case <-instance.done:
t.Fatalf("runtime exited before binding both listeners: %v", instance.err)
case <-time.After(3 * time.Second):
t.Fatal("timed out waiting for listener bind")
}
return ""
}
instance.proxy, instance.api = readAddress(), readAddress()
return instance
}
func (instance *runtimeTestInstance) wait(t *testing.T) error {
t.Helper()
waitRuntimeEvent(t, instance.done)
return instance.err
}
func waitRuntimeEvent(t *testing.T, event <-chan struct{}) {
t.Helper()
select {
case <-event:
case <-time.After(4 * time.Second):
t.Fatal("timed out waiting for runtime lifecycle event")
}
}
func assertRuntimeListenerClosed(t *testing.T, addr string) {
t.Helper()
conn, err := net.DialTimeout("tcp", addr, 250*time.Millisecond)
if err == nil {
_ = conn.Close()
t.Fatalf("listener remains reachable at %s", addr)
}
}
type runtimeTestComponents struct {
endpoints chan RuntimeEndpoints
started, stopped chan struct{}
proxy *runtimeTestProxy
}
func newRuntimeTestComponents() *runtimeTestComponents {
return &runtimeTestComponents{
endpoints: make(chan RuntimeEndpoints, 1),
started: make(chan struct{}),
stopped: make(chan struct{}),
proxy: &runtimeTestProxy{closed: make(chan struct{}), tunnelDone: make(chan struct{})},
}
}
func (components *runtimeTestComponents) build(_ context.Context, endpoints RuntimeEndpoints) (RuntimeComponents, error) {
components.endpoints <- endpoints
return RuntimeComponents{
Catalog: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }),
Proxy: components.proxy,
Monitor: func(ctx context.Context) error {
close(components.started)
defer close(components.stopped)
<-ctx.Done()
return ctx.Err()
},
}, nil
}
// The proxy double records authenticated routing and leaves a real hijacked
// socket open until the runtime calls the component's shutdown hook.
type runtimeTestProxy struct {
closed, tunnelDone chan struct{}
tunnel atomic.Bool
}
func (p *runtimeTestProxy) ServeProxy(w http.ResponseWriter, r *http.Request, id int64) {
if len(r.Header.Values("Proxy-Authorization")) != 0 {
w.WriteHeader(http.StatusInternalServerError)
return
}
if r.Method != http.MethodConnect {
_, _ = io.WriteString(w, strconv.FormatInt(id, 10))
return
}
conn, rw, err := http.NewResponseController(w).Hijack()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
p.tunnel.Store(true)
defer close(p.tunnelDone)
defer conn.Close()
if _, err := rw.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil || rw.Flush() != nil {
return
}
<-p.closed
}
func (p *runtimeTestProxy) Shutdown(ctx context.Context) error {
close(p.closed)
if p.tunnel.Load() {
select {
case <-p.tunnelDone:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
func runtimeProxyAuth(creds Credentials, id int64) string {
return "Proxy-Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte("node-"+strconv.FormatInt(id, 10)+":"+creds.Password(id))) + "\r\n"
}
func dialRuntimeWire(t *testing.T, addr string) (net.Conn, *bufio.Reader) {
t.Helper()
conn, err := net.DialTimeout("tcp", addr, time.Second)
if err != nil {
t.Fatalf("dial runtime test listener: %v", err)
}
if err := conn.SetDeadline(time.Now().Add(3 * time.Second)); err != nil {
_ = conn.Close()
t.Fatal(err)
}
return conn, bufio.NewReader(conn)
}
func exchangeRuntimeWire(t *testing.T, conn net.Conn, reader *bufio.Reader, method, target, headers string) *http.Response {
t.Helper()
if _, err := fmt.Fprintf(conn, "%s %s HTTP/1.1\r\nHost: origin.test\r\n%s\r\n", method, target, headers); err != nil {
t.Fatalf("write runtime test request: %v", err)
}
response, err := http.ReadResponse(reader, &http.Request{Method: method})
if err != nil {
t.Fatalf("read runtime test response: %v", err)
}
return response
}
+41
View File
@@ -0,0 +1,41 @@
package gateway
import (
"crypto/x509"
"errors"
"log/slog"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
"git.eeee.moe/omar/zhguchiy_perchik/internal/dialer"
)
// NewRuntimeComponents wires the gateway from validated launch configuration
// and the listener addresses, credentials, and lease established by Run.
func NewRuntimeComponents(store *db.DB, cfg Config, endpoints RuntimeEndpoints) (RuntimeComponents, error) {
return newRuntimeComponents(store, cfg, endpoints, NewRoutePolicy(cfg), nil)
}
// The socket policy and extra trust roots can only be supplied from inside the
// package, so the loopback E2E harness exercises the production wiring without
// adding a startup option that weakens the production policy or TLS validation.
func newRuntimeComponents(store *db.DB, cfg Config, endpoints RuntimeEndpoints, policy *RoutePolicy, roots *x509.CertPool) (RuntimeComponents, error) {
if store == nil || endpoints.Lease == nil || cfg.ProbeURL == nil || policy == nil {
return RuntimeComponents{}, errors.New("incomplete gateway component configuration")
}
probeURL := *cfg.ProbeURL
tickets := newProbeTickets(probeURL.Host)
prober, err := newHTTPGatewayProber(&probeURL, endpoints.ProbeProxyAddr, endpoints.Credentials, tickets, policy.DialControl, roots)
if err != nil {
return RuntimeComponents{}, err
}
// Shared dialers can log upstream and destination details. Do not route
// any of that output to the gateway's logs, even at debug level.
dispatcher := dialer.NewDispatcher(slog.New(slog.DiscardHandler), policy.DialUpstream)
monitor := NewMonitor(store, endpoints.Lease, prober)
return RuntimeComponents{
Catalog: NewCatalog(store, cfg, endpoints.Credentials),
Proxy: NewForwardProxy(store, policy, dispatcher, tickets),
Monitor: monitor.Run,
}, nil
}
+96
View File
@@ -0,0 +1,96 @@
package gateway
import (
"context"
"encoding/json"
"net/http"
"strings"
"time"
)
func (rt *gatewayRuntime) apiHandler(token string) http.Handler {
status := RequireBearerAuth(token, http.HandlerFunc(rt.serveStatus))
catalog := RequireBearerAuth(token, http.HandlerFunc(rt.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 != "" {
http.Error(w, "API requires origin form", http.StatusBadRequest)
return
}
switch r.URL.EscapedPath() {
case "/healthz":
if gatewayGET(w, r) {
w.WriteHeader(http.StatusOK)
}
case "/readyz":
if gatewayGET(w, r) {
rt.serveReady(w, r)
}
case "/v1/status":
status.ServeHTTP(w, r)
case "/v1/proxies":
catalog.ServeHTTP(w, r)
default:
http.NotFound(w, r)
}
})
}
func gatewayGET(w http.ResponseWriter, r *http.Request) bool {
if r.Method == http.MethodGet {
return true
}
w.Header().Set("Allow", http.MethodGet)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return false
}
func (rt *gatewayRuntime) serveReady(w http.ResponseWriter, r *http.Request) {
active := rt.serving()
if active == nil {
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
return
}
ctx, cancel := context.WithTimeout(r.Context(), rt.timing.dbCall)
defer cancel()
if err := active.lease.Check(ctx); err != nil {
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
return
}
if _, err := rt.store.GatewayStatus(ctx, time.Time{}); err != nil || rt.serving() == nil {
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
}
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
}
ctx, cancel := context.WithTimeout(r.Context(), rt.timing.dbCall)
defer cancel()
status, err := rt.store.GatewayStatus(ctx, time.Time{})
if err != nil || rt.serving() == nil {
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
return
}
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)
return
}
active.catalog.ServeHTTP(w, r)
}
+111
View File
@@ -0,0 +1,111 @@
package gateway
import (
"bytes"
"encoding/json"
"io"
"net/http"
"testing"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
)
func runtimeBearer(cfg Config) string {
return "Authorization: Bearer " + cfg.APIToken + "\r\n"
}
func assertRuntimeStarting(t *testing.T, run *runtimeTestInstance, cfg Config) {
t.Helper()
assertRuntimeHTTP(t, run.api, http.MethodGet, "/healthz", "", http.StatusOK)
assertRuntimeHTTP(t, run.api, http.MethodGet, "/readyz", "", http.StatusServiceUnavailable)
assertRuntimeHTTP(t, run.api, http.MethodGet, "/v1/status", "", http.StatusUnauthorized)
assertRuntimeHTTP(t, run.api, http.MethodGet, "/v1/status", runtimeBearer(cfg), http.StatusServiceUnavailable)
assertRuntimeHTTP(t, run.api, http.MethodGet, "/v1/proxies", runtimeBearer(cfg), http.StatusServiceUnavailable)
assertRuntimeHTTP(t, run.proxy, http.MethodGet, "http://origin.test/", "", http.StatusServiceUnavailable)
}
func assertRuntimeAPI(t *testing.T, api string, cfg Config) {
t.Helper()
assertRuntimeHTTP(t, api, http.MethodGet, "/readyz", "", http.StatusOK)
header, body := assertRuntimeHTTP(t, api, http.MethodGet, "/v1/status", runtimeBearer(cfg), http.StatusOK)
if header.Get("Content-Type") != "application/json" || header.Get("Cache-Control") != "no-store" || header.Get("Access-Control-Allow-Origin") != "" {
t.Fatal("status returned incorrect content, cache or CORS headers")
}
var status db.GatewayStatus
if err := json.Unmarshal(body, &status); err != nil {
t.Fatal("status response is not valid JSON")
}
if status.State != "idle" || status.SessionID != nil || status.ReadyCount != 0 || status.CandidateCount != 0 || status.IntervalMinutes == nil || *status.IntervalMinutes != 20 {
t.Fatal("status did not report a live, empty snapshot with the default interval")
}
if bytes.Contains(body, []byte(cfg.APIToken)) || bytes.Contains(body, []byte("store_uuid")) {
t.Fatal("status leaked credentials or internal store identity")
}
assertRuntimeHTTP(t, api, http.MethodGet, "/v1/proxies", runtimeBearer(cfg), http.StatusNoContent)
for _, target := range []string{"/v1/status", "/v1/proxies", "/readyz", "/healthz"} {
header, _ := assertRuntimeHTTP(t, api, http.MethodPost, target, runtimeBearer(cfg), http.StatusMethodNotAllowed)
if header.Get("Allow") != http.MethodGet {
t.Fatalf("missing Allow header on %s", target)
}
}
}
func assertRuntimePortAuth(t *testing.T, run *runtimeTestInstance, cfg Config, creds Credentials) {
t.Helper()
basic := runtimeProxyAuth(creds, 42)
assertRuntimeHTTP(t, run.api, http.MethodGet, "/v1/status", basic, http.StatusUnauthorized)
header, _ := assertRuntimeHTTP(t, run.api, http.MethodGet, "/v1/proxies", "Authorization: Bearer invalid\r\n", http.StatusUnauthorized)
if header.Get("WWW-Authenticate") != "Bearer" || header.Get("Cache-Control") != "no-store" {
t.Fatal("API did not challenge for bearer credentials without caching the result")
}
assertRuntimeHTTP(t, run.api, http.MethodConnect, "origin.test:443", runtimeBearer(cfg), http.StatusBadRequest)
assertRuntimeHTTP(t, run.api, http.MethodGet, "http://origin.test/v1/status", runtimeBearer(cfg), http.StatusBadRequest)
assertRuntimeHTTP(t, run.proxy, http.MethodGet, "/v1/proxies", basic, http.StatusBadRequest)
assertRuntimeHTTP(t, run.proxy, http.MethodGet, "http://origin.test/", runtimeBearer(cfg), http.StatusProxyAuthRequired)
assertRuntimeHTTP(t, run.proxy, http.MethodGet, "http://origin.test/", "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n", http.StatusProxyAuthRequired)
conn, reader := dialRuntimeWire(t, run.proxy)
defer conn.Close()
for _, tc := range []struct {
auth, id string
status int
}{
{basic, "42", http.StatusOK},
{"", "", http.StatusProxyAuthRequired},
{runtimeProxyAuth(creds, 7), "7", http.StatusOK},
} {
response := exchangeRuntimeWire(t, conn, reader, http.MethodGet, "http://origin.test/", tc.auth)
body := readRuntimeWireBody(t, response)
if response.StatusCode != tc.status {
t.Fatalf("request on reused socket = %d, want %d", response.StatusCode, tc.status)
}
if tc.status == http.StatusOK && string(body) != tc.id {
t.Fatal("dispatcher inherited the wrong authenticated ID on the reused socket")
}
if tc.status == http.StatusProxyAuthRequired && response.Header.Get("Proxy-Authenticate") != `Basic realm="http-gateway"` {
t.Fatal("proxy did not challenge for Basic credentials")
}
}
}
func assertRuntimeHTTP(t *testing.T, addr, method, target, headers string, status int) (http.Header, []byte) {
t.Helper()
conn, reader := dialRuntimeWire(t, addr)
defer conn.Close()
response := exchangeRuntimeWire(t, conn, reader, method, target, headers)
body := readRuntimeWireBody(t, response)
if response.StatusCode != status {
t.Fatalf("%s %s = %d, want %d", method, target, response.StatusCode, status)
}
return response.Header, body
}
func readRuntimeWireBody(t *testing.T, response *http.Response) []byte {
t.Helper()
defer response.Body.Close()
body, err := io.ReadAll(io.LimitReader(response.Body, 4096))
if err != nil {
t.Fatalf("read runtime HTTP body: %v", err)
}
return body
}
+411
View File
@@ -0,0 +1,411 @@
//go:build gateway_e2e && linux
// Package testfixture provides loopback-only fixtures for gateway acceptance tests.
package testfixture
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/hex"
"encoding/pem"
"errors"
"io"
"log"
"math/big"
"net"
"net/http"
"net/netip"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
var loopback = netip.AddrFrom4([4]byte{127, 0, 0, 1})
type Authority struct {
Roots *x509.CertPool
File string // PEM trust anchor for a test subprocess's SSL_CERT_FILE.
cert *x509.Certificate
key *ecdsa.PrivateKey
}
type Certificate struct {
CertFile string
KeyFile string
TLS tls.Certificate
}
func NewAuthority(t *testing.T) *Authority {
t.Helper()
key := newCertificateKey(t)
ca := certificateTemplate(t)
ca.Subject = pkix.Name{CommonName: "Gateway test CA"}
ca.IsCA = true
ca.BasicConstraintsValid = true
ca.KeyUsage = x509.KeyUsageCertSign
der, err := x509.CreateCertificate(rand.Reader, ca, ca, &key.PublicKey, key)
if err != nil {
t.Fatalf("create fixture CA: %v", err)
}
cert, err := x509.ParseCertificate(der)
if err != nil {
t.Fatalf("parse fixture CA: %v", err)
}
file := filepath.Join(t.TempDir(), "ca.pem")
writePEM(t, file, "CERTIFICATE", der)
keyDER, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
t.Fatalf("marshal fixture CA key: %v", err)
}
writePEM(t, authorityKeyFile(file), "PRIVATE KEY", keyDER)
return newAuthority(file, cert, key)
}
// LoadAuthority reopens the trust anchor and its sibling key from a test's temporary directory.
func LoadAuthority(t *testing.T, file string) *Authority {
t.Helper()
cert, err := x509.ParseCertificate(readPEM(t, file, "CERTIFICATE"))
if err != nil || !cert.IsCA {
t.Fatal("invalid fixture CA certificate")
}
privateKey, err := x509.ParsePKCS8PrivateKey(readPEM(t, authorityKeyFile(file), "PRIVATE KEY"))
key, ok := privateKey.(*ecdsa.PrivateKey)
if err != nil || !ok || !key.PublicKey.Equal(cert.PublicKey) {
t.Fatal("invalid fixture CA key")
}
return newAuthority(file, cert, key)
}
func authorityKeyFile(file string) string { return filepath.Join(filepath.Dir(file), "ca-key.pem") }
func newAuthority(file string, cert *x509.Certificate, key *ecdsa.PrivateKey) *Authority {
roots := x509.NewCertPool()
roots.AddCert(cert)
return &Authority{Roots: roots, File: file, cert: cert, key: key}
}
func (a *Authority) Issue(t *testing.T, names ...string) Certificate {
t.Helper()
if len(names) == 0 {
t.Fatal("fixture certificate needs a name")
}
key := newCertificateKey(t)
leaf := certificateTemplate(t)
leaf.KeyUsage = x509.KeyUsageDigitalSignature
leaf.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
for _, name := range names {
if ip := net.ParseIP(name); ip != nil {
leaf.IPAddresses = append(leaf.IPAddresses, ip)
} else {
leaf.DNSNames = append(leaf.DNSNames, name)
}
}
der, err := x509.CreateCertificate(rand.Reader, leaf, a.cert, &key.PublicKey, a.key)
if err != nil {
t.Fatalf("create fixture certificate: %v", err)
}
keyDER, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
t.Fatalf("marshal fixture certificate key: %v", err)
}
dir := t.TempDir()
certFile, keyFile := filepath.Join(dir, "cert.pem"), filepath.Join(dir, "key.pem")
writePEM(t, certFile, "CERTIFICATE", der)
writePEM(t, keyFile, "PRIVATE KEY", keyDER)
return Certificate{CertFile: certFile, KeyFile: keyFile, TLS: tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}}
}
func newCertificateKey(t *testing.T) *ecdsa.PrivateKey {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("generate fixture certificate key: %v", err)
}
return key
}
func certificateTemplate(t *testing.T) *x509.Certificate {
t.Helper()
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
t.Fatalf("generate fixture certificate serial: %v", err)
}
now := time.Now()
return &x509.Certificate{SerialNumber: serial.Add(serial, big.NewInt(1)), NotBefore: now.Add(-time.Hour), NotAfter: now.Add(time.Hour)}
}
func writePEM(t *testing.T, file, kind string, der []byte) {
t.Helper()
if err := os.WriteFile(file, pem.EncodeToMemory(&pem.Block{Type: kind, Bytes: der}), 0o600); err != nil {
t.Fatalf("write fixture %s: %v", kind, err)
}
}
func readPEM(t *testing.T, file, kind string) []byte {
t.Helper()
data, err := os.ReadFile(file)
if err != nil {
t.Fatalf("read fixture %s: %v", kind, err)
}
block, _ := pem.Decode(data)
if block == nil || block.Type != kind {
t.Fatalf("invalid fixture %s PEM", kind)
}
return block.Bytes
}
// The URL authorities use the supplied DNS name or IP, but the sockets always bind to loopback.
type Origin struct {
HTTPURL string
HTTPSURL string
HTTPAddr netip.AddrPort
HTTPSAddr netip.AddrPort
mu sync.Mutex
paths map[string]*Expectation
control *Control
connections atomic.Int64
}
func NewOrigin(t *testing.T, ca *Authority, hostname string) *Origin {
t.Helper()
cert := ca.Issue(t, hostname)
origin := &Origin{paths: make(map[string]*Expectation)}
origin.HTTPAddr = serveOrigin(t, origin, nil)
origin.HTTPSAddr = serveOrigin(t, origin, &tls.Config{Certificates: []tls.Certificate{cert.TLS}, MinVersion: tls.VersionTLS12})
origin.HTTPURL = "http://" + net.JoinHostPort(hostname, strconv.Itoa(int(origin.HTTPAddr.Port())))
origin.HTTPSURL = "https://" + net.JoinHostPort(hostname, strconv.Itoa(int(origin.HTTPSAddr.Port())))
return origin
}
// Connections counts TCP connections accepted by either listener, even if no request arrived.
func (o *Origin) Connections() int { return int(o.connections.Load()) }
func bindLoopback(t *testing.T) (net.Listener, netip.AddrPort) {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
var config net.ListenConfig
listener, err := config.Listen(ctx, "tcp4", netip.AddrPortFrom(loopback, 0).String())
if err != nil {
t.Fatalf("bind fixture listener: %v", err)
}
addr := listener.Addr().(*net.TCPAddr).AddrPort()
return listener, netip.AddrPortFrom(addr.Addr().Unmap(), addr.Port())
}
func serveOrigin(t *testing.T, origin *Origin, tlsConfig *tls.Config) netip.AddrPort {
t.Helper()
listener, addr := bindLoopback(t)
server := &http.Server{
Handler: origin,
TLSConfig: tlsConfig,
ErrorLog: log.New(io.Discard, "", 0),
ReadHeaderTimeout: 3 * time.Second,
ReadTimeout: 8 * time.Second,
WriteTimeout: 8 * time.Second,
IdleTimeout: 2 * time.Second,
ConnState: func(_ net.Conn, state http.ConnState) {
if state == http.StateNew {
origin.connections.Add(1)
}
},
}
done := make(chan error, 1)
go func() {
defer listener.Close()
if tlsConfig == nil {
done <- server.Serve(listener)
} else {
done <- server.ServeTLS(listener, "", "")
}
}()
t.Cleanup(func() {
_ = server.Close()
select {
case err := <-done:
if !errors.Is(err, http.ErrServerClosed) {
t.Errorf("fixture origin stopped unexpectedly: %v", err)
}
case <-time.After(3 * time.Second):
t.Error("fixture origin did not stop")
}
})
return addr
}
type Exchange struct {
Method string
Body []byte
Response []byte
ResponseHeader http.Header
Status int // Defaults to HTTP 200.
Truncate bool // Declare one additional byte and close after Response.
Check func(*http.Request) bool // Optional header/authority check; must not read the body.
WaitForCancel func(context.Context) // Optional hook after flushing; must honor the context.
}
type Expectation struct {
Path string // Use only once on one of the two fixture listeners.
source netip.Addr
exchange Exchange
requestSize int64
requestChecksum [sha256.Size]byte
responseChecksum string
hits atomic.Int32
verified atomic.Bool
}
func (e *Expectation) Hits() int { return int(e.hits.Load()) }
func (e *Expectation) Verified() bool { return e.verified.Load() }
func (o *Origin) Expect(t *testing.T, source netip.Addr, x Exchange) *Expectation {
t.Helper()
if !source.Is4() || !source.IsLoopback() {
t.Fatal("fixture origin requires a loopback source")
}
if x.Method == "" {
x.Method = http.MethodGet
}
if x.Status == 0 {
x.Status = http.StatusOK
}
checksum := sha256.Sum256(x.Response)
e := &Expectation{
Path: "/exchange/" + rand.Text(),
source: source,
requestSize: int64(len(x.Body)),
requestChecksum: sha256.Sum256(x.Body),
responseChecksum: hex.EncodeToString(checksum[:]),
}
x.Body = nil
x.Response = bytes.Clone(x.Response)
x.ResponseHeader = x.ResponseHeader.Clone()
e.exchange = x
o.mu.Lock()
defer o.mu.Unlock()
if _, exists := o.paths[e.Path]; exists {
t.Fatal("fixture origin marker collision")
}
o.paths[e.Path] = e
return e
}
// Control witnesses a TLS 204 probe from the gateway itself or an enrolled peer.
type Control struct {
Path string
host string
hits map[netip.Addr]*atomic.Int64
}
func (o *Origin) EnableControl(t *testing.T, peers ...netip.Addr) *Control {
t.Helper()
control := &Control{
Path: "/control/" + rand.Text(),
host: strings.TrimPrefix(o.HTTPSURL, "https://"),
hits: make(map[netip.Addr]*atomic.Int64, len(peers)+1),
}
control.hits[loopback] = new(atomic.Int64)
for _, source := range peers {
if !source.Is4() || !source.IsLoopback() || control.hits[source] != nil {
t.Fatal("fixture control requires distinct non-direct loopback peers")
}
control.hits[source] = new(atomic.Int64)
}
o.mu.Lock()
defer o.mu.Unlock()
if o.control != nil {
t.Fatal("fixture control already enabled")
}
o.control = control
return control
}
func (c *Control) Hits(source netip.Addr) int64 {
if count := c.hits[source]; count != nil {
return count.Load()
}
return 0
}
func (c *Control) serve(w http.ResponseWriter, r *http.Request) {
remote, err := netip.ParseAddrPort(r.RemoteAddr)
count := c.hits[remote.Addr().Unmap()]
if err != nil || count == nil || r.TLS == nil || r.Method != http.MethodGet ||
r.Host != c.host || r.URL.RawQuery != "" || len(r.Header.Values("Authorization")) != 0 ||
len(r.Header.Values("Proxy-Authorization")) != 0 || len(r.Header.Values("X-Gateway-Probe")) != 0 {
w.WriteHeader(http.StatusForbidden)
return
}
count.Add(1)
w.WriteHeader(http.StatusNoContent)
}
func (o *Origin) ServeHTTP(w http.ResponseWriter, r *http.Request) {
o.mu.Lock()
e := o.paths[r.URL.Path]
control := o.control
o.mu.Unlock()
if control != nil && r.URL.Path == control.Path {
control.serve(w, r)
return
}
if e == nil {
http.NotFound(w, r)
return
}
if e.hits.Add(1) != 1 {
w.WriteHeader(http.StatusConflict)
return
}
remote, err := netip.ParseAddrPort(r.RemoteAddr)
if err != nil || remote.Addr().Unmap() != e.source || r.Method != e.exchange.Method {
w.WriteHeader(http.StatusForbidden)
return
}
if e.exchange.Check != nil && !e.exchange.Check(r) {
w.WriteHeader(http.StatusBadRequest)
return
}
hash := sha256.New()
size, err := io.Copy(hash, io.LimitReader(r.Body, e.requestSize+1))
if err != nil || size != e.requestSize || !bytes.Equal(hash.Sum(nil), e.requestChecksum[:]) {
w.WriteHeader(http.StatusBadRequest)
return
}
e.verified.Store(true)
for name, values := range e.exchange.ResponseHeader {
w.Header()[name] = values
}
w.Header().Set("X-Fixture-Response-SHA256", e.responseChecksum)
if e.exchange.Truncate {
w.Header().Set("Content-Length", strconv.Itoa(len(e.exchange.Response)+1))
w.Header().Add("Connection", "close")
}
w.WriteHeader(e.exchange.Status)
if len(e.exchange.Response) > 0 {
_, _ = w.Write(e.exchange.Response)
}
if e.exchange.WaitForCancel != nil {
if err := http.NewResponseController(w).Flush(); err != nil {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
defer cancel()
e.exchange.WaitForCancel(ctx)
}
}
+376
View File
@@ -0,0 +1,376 @@
//go:build gateway_e2e && linux
package testfixture
import (
"context"
"crypto/ecdh"
"crypto/rand"
"crypto/tls"
"debug/buildinfo"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"maps"
"net"
"net/netip"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/gofrs/uuid"
)
const (
XrayVersion = "25.3.6"
XrayRevision = "2cba2c4d59e48a04aa5d09b8e4c2b2d26f8608a4"
PeerName = "peer.gateway.test"
wsHost = "ws.gateway.test"
wsPath = "/gateway-fixture"
grpcService = "GunService" // The gateway's VMess URL reader uses the dialer's default service name.
aeadCipher = "aes-128-gcm"
visionFlow = "xtls-rprx-vision"
peerStart = 5 * time.Second
peerStop = 3 * time.Second
)
type Case struct {
Name string
Protocol string
Network string
security string
}
func Cases() []Case {
return []Case{
{Name: "ss-aead", Protocol: "ss", Network: "tcp"},
{Name: "vless-tcp-tls", Protocol: "vless", Network: "tcp", security: "tls"},
{Name: "vless-ws-tls", Protocol: "vless", Network: "ws", security: "tls"},
{Name: "vless-grpc-tls", Protocol: "vless", Network: "grpc", security: "tls"},
{Name: "vless-reality-vision", Protocol: "vless", Network: "tcp", security: "reality"},
{Name: "trojan-tcp-tls", Protocol: "trojan", Network: "tcp", security: "tls"},
{Name: "trojan-ws-tls", Protocol: "trojan", Network: "ws", security: "tls"},
{Name: "trojan-grpc-tls", Protocol: "trojan", Network: "grpc", security: "tls"},
{Name: "vmess-tcp-aead", Protocol: "vmess", Network: "tcp"},
{Name: "vmess-ws-tls", Protocol: "vmess", Network: "ws", security: "tls"},
{Name: "vmess-grpc-tls", Protocol: "vmess", Network: "grpc", security: "tls"},
}
}
type Peer struct {
URL string // Credential-bearing test URL; never log it.
Addr netip.AddrPort
Source netip.Addr
bin, dir string
process *os.Process
done chan struct{}
waitErr error // Published by closing done.
stop sync.Once
}
var sourceCounter atomic.Uint32
// NewSource gives a peer a distinct Linux loopback source, different from a direct origin dial.
func NewSource() netip.Addr {
id := sourceCounter.Add(1)
if id > 0x7fffff {
panic("fixture source addresses exhausted")
}
return netip.AddrFrom4([4]byte{127, 128 | byte(id>>16), byte(id >> 8), byte(id)})
}
func StartPeer(t *testing.T, xrayBin string, origin *Origin, ca *Authority, c Case) *Peer {
t.Helper()
var credential string
if c.Protocol == "vless" || c.Protocol == "vmess" {
id, err := uuid.NewV4()
if err != nil {
t.Fatal("generate Xray fixture UUID")
}
credential = id.String()
} else {
credential = rand.Text()
}
xrayProtocol := c.Protocol
settings := make(map[string]any)
stream := map[string]any{"network": c.Network}
query := url.Values{"type": {c.Network}}
if c.security != "" {
stream["security"] = c.security
query.Set("security", c.security)
query.Set("sni", PeerName)
}
var tlsSettings map[string]any
if c.security == "tls" {
cert := ca.Issue(t, PeerName)
tlsSettings = map[string]any{
"minVersion": "1.2",
"rejectUnknownSni": true,
"certificates": []map[string]any{{
"certificateFile": cert.CertFile,
"keyFile": cert.KeyFile,
"oneTimeLoading": true,
}},
}
stream["tlsSettings"] = tlsSettings
}
if c.Network != "tcp" && tlsSettings == nil {
t.Fatal("WebSocket and gRPC fixture cases require TLS")
}
switch c.Network {
case "tcp":
case "ws":
stream["wsSettings"] = map[string]any{"path": wsPath, "host": wsHost}
query.Set("path", wsPath)
query.Set("host", wsHost)
tlsSettings["alpn"] = []string{"http/1.1"}
case "grpc":
stream["grpcSettings"] = map[string]any{"serviceName": grpcService}
query.Set("serviceName", grpcService)
tlsSettings["alpn"] = []string{"h2"}
default:
t.Fatal("unsupported Xray fixture network")
}
switch c.Protocol {
case "ss":
xrayProtocol = "shadowsocks"
settings["method"], settings["password"], settings["network"] = aeadCipher, credential, "tcp"
case "vless":
client := map[string]string{"id": credential}
settings["decryption"] = "none"
settings["clients"] = []map[string]string{client}
query.Set("encryption", "none")
if c.security == "reality" {
client["flow"] = visionFlow
query.Set("flow", visionFlow)
stream["realitySettings"] = realitySettings(t, ca, query)
}
case "trojan":
settings["clients"] = []map[string]string{{"password": credential}}
case "vmess":
settings["clients"] = []map[string]string{{"id": credential, "security": aeadCipher}}
default:
t.Fatal("unsupported Xray fixture protocol")
}
peer := StartXray(t, xrayBin, origin, NewSource(), map[string]any{
"protocol": xrayProtocol, "settings": settings, "streamSettings": stream,
})
if c.Protocol == "vmess" {
payload, err := json.Marshal(map[string]any{
"v": "2", "add": PeerName, "port": peer.Addr.Port(), "id": credential, "aid": 0,
"net": c.Network, "scy": aeadCipher, "tls": c.security, "sni": PeerName,
"host": query.Get("host"), "path": query.Get("path"),
})
if err != nil {
t.Fatal("encode VMess fixture URL")
}
peer.URL = "vmess://" + base64.RawStdEncoding.EncodeToString(payload)
} else {
u := url.URL{Scheme: c.Protocol, Host: net.JoinHostPort(PeerName, strconv.Itoa(int(peer.Addr.Port())))}
if c.Protocol == "ss" {
u.User = url.User(base64.RawURLEncoding.EncodeToString([]byte(aeadCipher + ":" + credential)))
} else {
u.User = url.User(credential)
u.RawQuery = query.Encode()
}
peer.URL = u.String()
}
return peer
}
func realitySettings(t *testing.T, ca *Authority, query url.Values) map[string]any {
t.Helper()
// This separate, loopback-only cover is never an allowed application destination.
cert := ca.Issue(t, PeerName)
cover := serveOrigin(t, &Origin{}, &tls.Config{
Certificates: []tls.Certificate{cert.TLS},
MinVersion: tls.VersionTLS13,
CurvePreferences: []tls.CurveID{tls.X25519},
NextProtos: []string{"h2", "http/1.1"},
})
key, err := ecdh.X25519().GenerateKey(rand.Reader)
if err != nil {
t.Fatal("generate REALITY fixture key")
}
var id [8]byte
rand.Read(id[:])
shortID := hex.EncodeToString(id[:])
query.Set("fp", "firefox")
query.Set("pbk", base64.RawURLEncoding.EncodeToString(key.PublicKey().Bytes()))
query.Set("sid", shortID)
return map[string]any{
"target": cover.String(),
"serverNames": []string{PeerName},
"privateKey": base64.RawURLEncoding.EncodeToString(key.Bytes()),
"shortIds": []string{shortID},
}
}
// StartXray launches a trusted test inbound. Application traffic can only reach
// the two numeric TCP authorities belonging to this origin; default egress is blackholed.
func StartXray(t *testing.T, bin string, origin *Origin, source netip.Addr, inbound map[string]any) *Peer {
t.Helper()
if !source.Is4() || !source.IsLoopback() || source == loopback {
t.Fatal("Xray fixture needs a distinct IPv4 loopback source")
}
if origin.HTTPAddr.Addr() != loopback || origin.HTTPSAddr.Addr() != loopback ||
origin.HTTPAddr.Port() == 0 || origin.HTTPSAddr.Port() == 0 {
t.Fatal("Xray fixture needs loopback HTTP and HTTPS origins")
}
bin = requireXray(t, bin)
addr := reservePeerAddr(t)
inbound = maps.Clone(inbound)
inbound["listen"], inbound["port"], inbound["tag"] = addr.Addr().String(), addr.Port(), "test-in"
config, err := json.Marshal(map[string]any{
"log": map[string]string{"access": "none", "error": "none", "loglevel": "none"},
"inbounds": []map[string]any{inbound},
"outbounds": []map[string]any{
{"protocol": "blackhole", "tag": "deny"},
{"protocol": "freedom", "tag": "origin", "sendThrough": source.String()},
},
"routing": map[string]any{
"domainStrategy": "AsIs",
"rules": []map[string]any{{
"type": "field",
"inboundTag": []string{"test-in"},
"network": "tcp",
"ip": []string{"127.0.0.1/32"},
"port": strconv.Itoa(int(origin.HTTPAddr.Port())) + "," + strconv.Itoa(int(origin.HTTPSAddr.Port())),
"outboundTag": "origin",
}},
},
})
if err != nil {
t.Fatal("encode Xray fixture config")
}
dir := t.TempDir()
if err = os.WriteFile(filepath.Join(dir, "peer.json"), config, 0o600); err != nil {
t.Fatalf("write Xray fixture config: %v", err)
}
return launchPeer(t, bin, dir, addr, source)
}
func launchPeer(t *testing.T, bin, dir string, addr netip.AddrPort, source netip.Addr) *Peer {
t.Helper()
cmd := exec.Command(bin, "run", "-c", "peer.json")
cmd.Dir = dir
cmd.Env = []string{"GOMAXPROCS=2"}
// Leave stdout and stderr on the null device: startup errors can contain config fragments.
if err := cmd.Start(); err != nil {
t.Fatalf("start Xray fixture: %v", err)
}
p := &Peer{Addr: addr, Source: source, bin: bin, dir: dir, process: cmd.Process, done: make(chan struct{})}
go func() {
p.waitErr = cmd.Wait()
close(p.done)
}()
t.Cleanup(func() { p.Stop(t) })
p.waitReady(t)
return p
}
// Restart starts a fresh process with the same inbound address, credentials,
// and pinned origin route. Stop has already waited for the old process to exit.
func (p *Peer) Restart(t *testing.T) *Peer {
t.Helper()
p.Stop(t)
next := launchPeer(t, p.bin, p.dir, p.Addr, p.Source)
next.URL = p.URL
return next
}
func requireXray(t *testing.T, bin string) string {
t.Helper()
if bin == "" {
t.Fatal("XRAY_BIN must point to the pinned Xray-core test binary")
}
path, err := exec.LookPath(bin)
if err != nil {
t.Fatal("XRAY_BIN is not executable")
}
path, err = filepath.Abs(path)
if err != nil {
t.Fatal("could not resolve XRAY_BIN")
}
// The test launcher pins the checkout. Enforce that revision when the binary exposes it.
if info, err := buildinfo.ReadFile(path); err == nil {
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" && setting.Value != XrayRevision {
t.Fatalf("XRAY_BIN must be built from Xray-core revision %s", XrayRevision)
}
}
}
ctx, cancel := context.WithTimeout(t.Context(), peerStart)
defer cancel()
cmd := exec.CommandContext(ctx, path, "version")
cmd.Env = []string{"GOMAXPROCS=2"}
cmd.WaitDelay = peerStop
out, err := cmd.Output()
if err != nil || !strings.HasPrefix(string(out), "Xray "+XrayVersion+" ") {
t.Fatalf("XRAY_BIN must report Xray %s", XrayVersion)
}
return path
}
func reservePeerAddr(t *testing.T) netip.AddrPort {
t.Helper()
l, addr := bindLoopback(t)
if err := l.Close(); err != nil {
t.Fatalf("release Xray fixture port: %v", err)
}
return addr
}
func (p *Peer) waitReady(t *testing.T) {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), peerStart)
defer cancel()
ticker := time.NewTicker(20 * time.Millisecond)
defer ticker.Stop()
dial := net.Dialer{Timeout: 100 * time.Millisecond}
addr := p.Addr.String()
for {
conn, err := dial.DialContext(ctx, "tcp4", addr)
if err == nil {
_ = conn.Close()
return
}
select {
case <-p.done:
t.Fatalf("Xray fixture exited before listening: %v", p.waitErr)
case <-ctx.Done():
t.Fatal("Xray fixture did not listen within startup deadline")
case <-ticker.C:
}
}
}
func (p *Peer) Stop(t *testing.T) {
t.Helper()
p.stop.Do(func() {
err := p.process.Kill()
if err != nil && !errors.Is(err, os.ErrProcessDone) {
t.Errorf("terminate Xray fixture: %v", err)
}
select {
case <-p.done:
if errors.Is(err, os.ErrProcessDone) {
t.Errorf("Xray fixture exited before stop: %v", p.waitErr)
}
case <-time.After(peerStop):
t.Error("Xray fixture did not exit within shutdown deadline")
}
})
}
+76
View File
@@ -0,0 +1,76 @@
// Package netpolicy classifies addresses before a network connection is opened.
package netpolicy
import "net/netip"
var ipv6GlobalUnicast = netip.MustParsePrefix("2000::/3")
// These IANA special-purpose blocks are not filtered by IsGlobalUnicast and
// IsPrivate. For IPv6, restrict to the current global unicast allocation first.
var specialIPPrefixes = [...]netip.Prefix{
netip.MustParsePrefix("0.0.0.0/8"),
netip.MustParsePrefix("100.64.0.0/10"),
netip.MustParsePrefix("192.0.0.0/24"),
netip.MustParsePrefix("192.0.2.0/24"),
netip.MustParsePrefix("192.31.196.0/24"),
netip.MustParsePrefix("192.52.193.0/24"),
netip.MustParsePrefix("192.88.99.0/24"),
netip.MustParsePrefix("192.175.48.0/24"),
netip.MustParsePrefix("198.18.0.0/15"),
netip.MustParsePrefix("198.51.100.0/24"),
netip.MustParsePrefix("203.0.113.0/24"),
netip.MustParsePrefix("240.0.0.0/4"),
netip.MustParsePrefix("2001::/23"),
netip.MustParsePrefix("2001:db8::/32"),
netip.MustParsePrefix("2002::/16"),
netip.MustParsePrefix("2620:4f:8000::/48"),
netip.MustParsePrefix("3fff::/20"),
}
// IPv4 ranges covered by IsGlobalUnicast and IsPrivate, but not by the
// special-purpose list above. A prefix can enclose them without starting there.
var nonPublicIPv4Prefixes = [...]netip.Prefix{
netip.MustParsePrefix("10.0.0.0/8"),
netip.MustParsePrefix("127.0.0.0/8"),
netip.MustParsePrefix("169.254.0.0/16"),
netip.MustParsePrefix("172.16.0.0/12"),
netip.MustParsePrefix("192.168.0.0/16"),
netip.MustParsePrefix("224.0.0.0/4"),
}
// IsPublicIP reports whether ip is a native, publicly routable address.
// Callers that intentionally accept IPv4-mapped addresses must unmap first.
func IsPublicIP(ip netip.Addr) bool {
if ip.Zone() != "" || !ip.IsGlobalUnicast() || ip.IsPrivate() || (ip.Is6() && !ipv6GlobalUnicast.Contains(ip)) {
return false
}
for _, prefix := range specialIPPrefixes {
if prefix.Contains(ip) {
return false
}
}
return true
}
// IsPublicPrefix reports whether a canonical prefix consists only of public IPs.
func IsPublicPrefix(prefix netip.Prefix) bool {
if prefix != prefix.Masked() || !IsPublicIP(prefix.Addr()) {
return false
}
if prefix.Addr().Is6() && prefix.Bits() < ipv6GlobalUnicast.Bits() {
return false
}
for _, excluded := range specialIPPrefixes {
if prefix.Overlaps(excluded) {
return false
}
}
if prefix.Addr().Is4() {
for _, excluded := range nonPublicIPv4Prefixes {
if prefix.Overlaps(excluded) {
return false
}
}
}
return true
}
+92
View File
@@ -0,0 +1,92 @@
package netpolicy
import (
"net/netip"
"testing"
)
func TestIsPublicIP(t *testing.T) {
for _, tc := range []struct {
address string
public bool
}{
{"1.1.1.1", true},
{"8.8.8.8", true},
{"2606:4700::1111", true},
{"", false},
{"0.0.0.0", false},
{"0.1.2.3", false},
{"10.0.0.1", false},
{"100.64.0.1", false},
{"127.0.0.1", false},
{"169.254.169.254", false},
{"172.31.1.1", false},
{"192.0.0.9", false},
{"192.0.2.1", false},
{"192.168.1.1", false},
{"198.18.0.1", false},
{"198.51.100.1", false},
{"203.0.113.1", false},
{"224.0.0.1", false},
{"240.0.0.1", false},
{"255.255.255.255", false},
{"::", false},
{"::1", false},
{"::ffff:127.0.0.1", false},
{"::ffff:8.8.8.8", false},
{"64:ff9b::808:808", false},
{"100::1", false},
{"2001::1", false},
{"2001:db8::1", false},
{"2002:808:808::1", false},
{"2606:4700::1111%eth0", false},
{"3fff::1", false},
{"fd00::1", false},
{"fe80::1", false},
{"ff00::1", false},
} {
t.Run(tc.address, func(t *testing.T) {
var addr netip.Addr
if tc.address != "" {
addr = netip.MustParseAddr(tc.address)
}
if got := IsPublicIP(addr); got != tc.public {
t.Errorf("IsPublicIP(%v) = %t, want %t", addr, got, tc.public)
}
})
}
}
func TestIsPublicPrefixRejectsNonPublicAddressesAnywhereInRange(t *testing.T) {
for _, tc := range []struct {
cidr string
public bool
}{
{"1.1.1.0/24", true},
{"1.1.1.1/32", true},
{"2606:4700::/64", true},
{"2606:4700::1/128", true},
{"", false},
{"1.1.1.1/24", false},
{"1.1.1.0/23", false},
{"10.0.0.0/8", false},
{"8.0.0.0/6", false}, // starts public, contains 10.0.0.0/8
{"192.0.0.0/23", false},
{"192.175.0.0/16", false}, // starts public, overlaps 192.175.48.0/24
{"2606:4700::1/64", false},
{"2000::/2", false},
{"3f00::/8", false}, // starts public, overlaps IPv6 documentation space
{"::ffff:8.8.8.8/128", false},
{"fc00::/7", false},
} {
t.Run(tc.cidr, func(t *testing.T) {
var prefix netip.Prefix
if tc.cidr != "" {
prefix = netip.MustParsePrefix(tc.cidr)
}
if got := IsPublicPrefix(prefix); got != tc.public {
t.Errorf("IsPublicPrefix(%v) = %t, want %t", prefix, got, tc.public)
}
})
}
}
+92
View File
@@ -177,3 +177,95 @@ ON CONFLICT (key) DO NOTHING;
-- Replace the old built-in HTTP URL without changing custom settings.
UPDATE settings SET value = 'https://speedtest.selectel.ru/10MB', updated_at = now()
WHERE key = 'speedtest_url' AND value = 'http://cachefly.cachefly.net/10mb.test';
-- ---------------------------------------------------------------------------
-- HTTP gateway: the checker owns the published snapshot, the gateway owns
-- only its runtime and health. The views expose no historical rows or settings.
-- ---------------------------------------------------------------------------
INSERT INTO settings (key, value) VALUES ('gateway_check_interval_minutes', '20')
ON CONFLICT (key) DO NOTHING;
CREATE OR REPLACE VIEW gateway_current_session WITH (security_barrier = true) AS
SELECT id AS session_id, finished_at AS session_finished_at
FROM check_sessions
WHERE is_current AND status = 'completed';
CREATE OR REPLACE VIEW gateway_candidates WITH (security_barrier = true) AS
SELECT cs.id AS session_id, cs.finished_at AS session_finished_at,
sp.id AS membership_id, sp.proxy_id, sp.canonical_url, sp.protocol,
sp.country, sp.exit_ip, sp.speed_mbps
FROM check_sessions cs
JOIN session_proxies sp ON sp.session_id = cs.id
WHERE cs.is_current AND cs.status = 'completed';
CREATE OR REPLACE VIEW gateway_check_interval WITH (security_barrier = true) AS
SELECT value FROM settings WHERE key = 'gateway_check_interval_minutes';
CREATE TABLE IF NOT EXISTS gateway_node_health (
proxy_id bigint PRIMARY KEY REFERENCES proxies(id) ON DELETE CASCADE,
tested_membership_id bigint NOT NULL,
ok boolean NOT NULL,
checked_at timestamptz NOT NULL,
latency_ms integer,
CHECK ((ok AND latency_ms IS NOT NULL AND latency_ms >= 0)
OR (NOT ok AND latency_ms IS NULL))
);
CREATE TABLE IF NOT EXISTS gateway_runtime (
id integer PRIMARY KEY CHECK (id = 1),
store_uuid uuid NOT NULL DEFAULT gen_random_uuid(),
heartbeat_at timestamptz,
last_started_at timestamptz,
last_attempt_finished_at timestamptz,
last_success_at timestamptz,
next_full_at timestamptz,
phase text NOT NULL DEFAULT 'idle' CHECK (phase IN ('idle', 'checking', 'degraded')),
last_error_code text CHECK (last_error_code IN ('config', 'control', 'database', 'probe', 'interrupted'))
);
INSERT INTO gateway_runtime (id) VALUES (1) ON CONFLICT (id) DO NOTHING;
-- Publication takes short-lived locks without granting the gateway access to
-- the checker tables. Bind their schema here; never use the caller's search_path.
DO $gateway_ddl$
BEGIN
EXECUTE format($definition$
CREATE OR REPLACE FUNCTION %1$I.gateway_lock_current(expected_session_id bigint)
RETURNS boolean
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp
AS $body$
BEGIN
IF expected_session_id IS NULL THEN
-- Before the first publication there is no row to lock.
LOCK TABLE %1$I.check_sessions IN SHARE MODE;
RETURN NOT EXISTS (
SELECT 1 FROM %1$I.check_sessions
WHERE is_current AND status = 'completed'
);
END IF;
PERFORM 1 FROM %1$I.check_sessions
WHERE id = expected_session_id AND is_current AND status = 'completed'
FOR SHARE;
RETURN FOUND;
END;
$body$
$definition$, current_schema());
EXECUTE format($definition$
CREATE OR REPLACE FUNCTION %1$I.gateway_lock_memberships(expected_session_id bigint, memberships bigint[])
RETURNS TABLE(proxy_id bigint, membership_id bigint)
LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, pg_temp
AS $body$
SELECT sp.proxy_id, sp.id
FROM %1$I.check_sessions cs
JOIN %1$I.session_proxies sp ON sp.session_id = cs.id
WHERE cs.id = expected_session_id AND cs.is_current AND cs.status = 'completed'
AND sp.id = ANY(memberships)
FOR SHARE OF cs FOR KEY SHARE OF sp;
$body$
$definition$, current_schema());
END;
$gateway_ddl$;
REVOKE EXECUTE ON FUNCTION gateway_lock_current(bigint), gateway_lock_memberships(bigint, bigint[]) FROM PUBLIC;
+14
View File
@@ -0,0 +1,14 @@
# Gateway release image smoke test
On the isolated Linux test host (local Docker Engine 28+ with CPU and memory limits), make the exact release image and a PostgreSQL 16 image available locally. Supply native Linux executable builds of the pinned reference Xray and the [`imagefixture`](imagefixture) helper. The script does not build or pull either image or binary.
```bash
# Build the helper separately for the test host's architecture (amd64 shown).
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /tmp/gateway-imagefixture ./tests/gateway/imagefixture
bash tests/gateway/image-smoke.sh "$RELEASE_IMAGE" "$POSTGRES16_IMAGE" "$XRAY_BIN" /tmp/gateway-imagefixture
```
The smoke test starts the release entrypoint with its declared nonroot user. It creates a randomly selected, isolated Docker bridge, publishes no host ports, and uses only temporary PostgreSQL data and synthesized credentials. The bridge uses non-special IPv4 addresses to exercise the release address policy unchanged; those addresses have no bridge address on the host and are never external destinations. The helper independently verifies catalog exports and authorization, HTTP and HTTPS routes against an origin that checks the peer, and restart, loss, and recovery of service. Container logs are disabled and no response bodies or credentials are printed.
The run is bounded to four minutes plus cleanup. Cleanup is scoped to this run's unique Docker label and private fixture directory. This verifies the actual image on a synthetic network, not an external canary or authorization to enable a production inventory.
+279
View File
@@ -0,0 +1,279 @@
#!/usr/bin/env bash
# Exercise an already-built release image. Do not pull images or publish ports.
set +x
set -Eeuo pipefail
umask 077
if (( $# != 4 )); then
printf 'Usage: bash %s RELEASE_IMAGE POSTGRES16_IMAGE XRAY_BIN ORIGIN_HELPER_BIN\n' "$0" >&2
exit 2
fi
stage='checking prerequisites'
work=''
run_label=''
release_id=''
deadline=$((SECONDS + 240))
die() {
printf 'Gateway image smoke: %s: %s\n' "$stage" "$1" >&2
exit 1
}
phase() {
stage=$1
printf 'Gateway image smoke: %s\n' "$stage"
}
dock() {
local budget=$1 remaining=$((deadline - SECONDS))
shift
(( remaining > 0 )) || return 124
if (( remaining < budget )); then budget=$remaining; fi
timeout --kill-after=2s "${budget}s" docker "$@"
}
cleanup() {
local rc=$? ids failed=0
local -a resources
trap - EXIT
trap '' INT TERM
set +e
if [[ -n $run_label ]]; then
if ids=$(timeout --kill-after=2s 10s docker container ls -aq --filter "label=$run_label" 2>/dev/null); then
if [[ -n $ids ]]; then
mapfile -t resources <<< "$ids"
timeout --kill-after=2s 15s docker container rm -fv "${resources[@]}" >/dev/null 2>&1 || failed=1
fi
else
failed=1
fi
if ids=$(timeout --kill-after=2s 10s docker network ls -q --filter "label=$run_label" 2>/dev/null); then
if [[ -n $ids ]]; then
mapfile -t resources <<< "$ids"
timeout --kill-after=2s 10s docker network rm "${resources[@]}" >/dev/null 2>&1 || failed=1
fi
else
failed=1
fi
fi
if [[ -n $work ]]; then
rm -rf -- "$work" || failed=1
fi
if (( failed )); then
printf 'Gateway image smoke: incomplete cleanup; owned Docker resources have label %s\n' "$run_label" >&2
(( rc != 0 )) || rc=1
elif (( rc == 0 )); then
printf 'Gateway image smoke: PASS (isolated release image %s)\n' "$release_id"
fi
exit "$rc"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'die "unexpected command failure"' ERR
[[ $(uname -s) == Linux ]] || die 'run this script on the Linux Docker host'
command -v docker >/dev/null && command -v timeout >/dev/null || die 'Docker and GNU timeout are required'
# Bind mounts use local paths: never send this run to a remote Docker endpoint.
endpoint=${DOCKER_HOST:-}
if [[ -n ${DOCKER_CONTEXT:-} || -z $endpoint ]]; then
endpoint=$(dock 8 context inspect --format '{{.Endpoints.docker.Host}}' 2>/dev/null) || die 'cannot read the Docker context'
fi
[[ $endpoint == unix:///* ]] || die 'a local Unix Docker endpoint is required'
version=$(dock 8 version --format '{{.Server.Version}}' 2>/dev/null) || die 'cannot query Docker Engine'
[[ $version =~ ^([0-9]+)\. ]] && (( BASH_REMATCH[1] >= 28 )) || die 'Docker Engine 28+ is required for isolated bridge mode'
release_id=$(dock 8 image inspect --format '{{.Id}}' -- "$1" 2>/dev/null) || die 'release image must already be local'
pg_image=$(dock 8 image inspect --format '{{.Id}}' -- "$2" 2>/dev/null) || die 'PostgreSQL 16 image must already be local'
[[ $release_id =~ ^sha256:[[:xdigit:]]{64}$ && $pg_image =~ ^sha256:[[:xdigit:]]{64}$ ]] || die 'expected one image per argument'
image_user=$(dock 8 image inspect --format '{{.Config.User}}' "$release_id" 2>/dev/null) || die 'cannot inspect release user'
image_user=${image_user%%:*}
[[ $image_user =~ ^[1-9][0-9]*$ || $image_user == nonroot ]] || die 'release image must default to a nonroot user'
xray_bin=$(realpath -e -- "$3" 2>/dev/null) || die 'XRAY_BIN is missing'
fixture_bin=$(realpath -e -- "$4" 2>/dev/null) || die 'fixture helper is missing'
repo=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)
for path in "$xray_bin" "$fixture_bin"; do
[[ -f $path && -x $path && $path != *[,$'\n'$'\r']* ]] || die 'helper binaries must be executable regular files with mount-safe paths'
done
[[ -r $repo/internal/db/schema.sql && -r $repo/deploy/gateway-grants.sql ]] || die 'checker schema and gateway grants are required'
work=$(mktemp -d /tmp/perchik-gateway-smoke.XXXXXXXXXX)
fixture=$work/fixture
mkdir -- "$fixture"
read -r uuid < /proc/sys/kernel/random/uuid
run_name=perchik-gateway-smoke-$uuid
run_label=mo.eeee.perchik.gateway-smoke=$uuid
network=$run_name
pg=$run_name-db
verifier=$run_name-verifier
origin=$run_name-origin
gateway=$run_name-release
phase 'creating an isolated Docker bridge'
# TEST-NET and private addresses correctly fail the release policy. A tiny
# non-special range works only inside this bridge: isolated mode gives the
# host no bridge IPv4 address, and --internal supplies no external route.
# Docker rejects overlapping IPAM pools; retry a randomly selected /27.
prefix=''
for (( i = 0; i < 10; i++ )); do
candidate=11.254.$((RANDOM % 254 + 1))
if dock 5 network create --driver bridge --internal --ipv6=false \
--subnet "$candidate.0/27" --opt com.docker.network.bridge.gateway_mode_ipv4=isolated \
--label "$run_label" "$network" >/dev/null 2>&1; then
prefix=$candidate
break
fi
done
[[ -n $prefix ]] || die 'could not allocate a non-overlapping isolated network'
# All containers have a fixed address and only this private network. Hosts
# resolve the fixture origin locally and cannot consult external DNS.
common=(--detach --pull=never --restart=no --log-driver=none --label "$run_label"
--network "$network" --add-host "origin.gateway.test:$prefix.10" --dns 127.0.0.1
--env HTTP_PROXY= --env HTTPS_PROXY= --env ALL_PROXY= --env NO_PROXY=
--env http_proxy= --env https_proxy= --env all_proxy= --env no_proxy=
--security-opt no-new-privileges --pids-limit 96)
# All tool containers reuse the already-local PostgreSQL base. Its declared
# data volume is overridden, so even these containers create no named volume.
pg_tmp=/var/lib/postgresql/data
small_pg=(--tmpfs "$pg_tmp:rw,nosuid,nodev,noexec,size=8m")
fixture_env=(--env "GATEWAY_FIXTURE_PREFIX=$prefix")
restricted=(--read-only --cap-drop ALL --cap-add DAC_OVERRIDE)
certs=(--mount "type=bind,src=$fixture/server.pem,dst=/fixture/server.pem,readonly"
--mount "type=bind,src=$fixture/server-key.pem,dst=/fixture/server-key.pem,readonly")
fixture_run() {
dock 65 exec "$verifier" /opt/imagefixture "$1" /fixture >/dev/null 2>&1 || die "fixture check '$1' failed or timed out"
}
phase 'generating synthetic credentials, CA and peers'
dock 12 run "${common[@]}" "${restricted[@]}" "${small_pg[@]}" "${fixture_env[@]}" \
--name "$verifier" --ip "$prefix.21" --user 0:0 --cpus 0.50 --memory 128m \
--mount "type=bind,src=$fixture,dst=/fixture" \
--mount "type=bind,src=$fixture_bin,dst=/opt/imagefixture,readonly" \
--entrypoint /bin/sleep "$pg_image" infinity >/dev/null 2>&1 || die 'cannot start the fixture tools container'
fixture_run generate
# Secrets are read by Docker from mode-0600 files or SQL stdin, never argv.
random_hex() { od -An -N32 -tx1 /dev/urandom | tr -d ' \n'; }
pg_password=$(random_hex)
gateway_password=$(random_hex)
printf 'POSTGRES_USER=postgres\nPOSTGRES_DB=gateway_smoke\nPOSTGRES_HOST_AUTH_METHOD=scram-sha-256\nPOSTGRES_PASSWORD=%s\n' \
"$pg_password" > "$work/postgres.env"
{
printf 'GATEWAY_DB_DSN=postgres://gateway_smoke_app:%s@%s.4:5432/gateway_smoke?sslmode=disable&search_path=gateway_smoke\n' \
"$gateway_password" "$prefix"
} | dock 8 exec -i "$verifier" /bin/sh -c 'cat >> /fixture/gateway.env' >/dev/null 2>&1 || die 'cannot stage the gateway DSN'
dock 8 exec "$verifier" /bin/cat /fixture/gateway.env > "$work/gateway.env" 2>/dev/null || die 'cannot stage the release environment file'
phase 'provisioning temporary PostgreSQL 16 and least-privilege grants'
dock 12 run "${common[@]}" --name "$pg" --ip "$prefix.4" \
--cpus 0.75 --memory 320m --tmpfs "$pg_tmp:rw,nosuid,nodev,noexec,size=192m" \
--env-file "$work/postgres.env" "$pg_image" \
-c max_connections=30 -c shared_buffers=32MB >/dev/null 2>&1 || die 'cannot start PostgreSQL'
unset pg_password
pg_ready_until=$((SECONDS + 25))
# TCP readiness on the container's own address excludes the entrypoint's
# temporary Unix-socket-only bootstrap server.
until dock 3 exec "$pg" pg_isready -q -h "$prefix.4" -d gateway_smoke -U postgres >/dev/null 2>&1; do
(( SECONDS < pg_ready_until && SECONDS < deadline )) || die 'PostgreSQL readiness timed out'
sleep 0.25
done
psql_admin() {
dock 12 exec -i --env 'PGOPTIONS=-c search_path=gateway_smoke' "$pg" \
psql -X -w -U postgres -d gateway_smoke -v ON_ERROR_STOP=1 "$@"
}
pg_version=$(psql_admin -Atqc 'SHOW server_version_num' 2>/dev/null) || die 'cannot query PostgreSQL version'
[[ $pg_version =~ ^16[0-9]{4}$ ]] || die 'the running server is not PostgreSQL 16'
{
printf 'CREATE SCHEMA gateway_smoke;\nREVOKE ALL ON SCHEMA public FROM PUBLIC;\nREVOKE CONNECT, TEMP ON DATABASE gateway_smoke FROM PUBLIC;\n'
printf "CREATE ROLE gateway_smoke_app LOGIN NOINHERIT PASSWORD '%s';\n" "$gateway_password"
printf 'GRANT CONNECT ON DATABASE gateway_smoke TO gateway_smoke_app;\n'
} | psql_admin -q >/dev/null 2>&1 || die 'cannot provision fixture database and login'
unset gateway_password
psql_admin -q < "$repo/internal/db/schema.sql" >/dev/null 2>&1 || die 'cannot apply checker schema'
psql_admin -q -v gateway_role=gateway_smoke_app -v gateway_schema=gateway_smoke \
< "$repo/deploy/gateway-grants.sql" >/dev/null 2>&1 || die 'cannot apply gateway grants'
fixture_run privileges
phase 'starting the isolated HTTPS origin and four independent Xray peers'
dock 12 run "${common[@]}" "${restricted[@]}" "${small_pg[@]}" "${fixture_env[@]}" "${certs[@]}" \
--name "$origin" --ip "$prefix.10" --user 0:0 --cpus 0.50 --memory 128m \
--mount "type=bind,src=$fixture_bin,dst=/opt/imagefixture,readonly" \
--entrypoint /opt/imagefixture "$pg_image" origin /fixture >/dev/null 2>&1 || die 'cannot start the fixture origin'
protocols=(ss trojan vmess vless)
peers=()
start_peer() {
local index=$1 protocol=${protocols[$1]}
dock 8 exec -d "${peers[index]}" /bin/sh -ec '
printf "%s\n" "$$" > /run/xray/pid
exec /opt/xray run -config "$1"
' xray-peer "/fixture/xray-$protocol.json" >/dev/null 2>&1 || die "cannot start the $protocol reference peer"
}
# Keep the bridge endpoint present while closing the listener. Removing the
# endpoint could turn a refusal into unanswered SYNs during ARP cache expiry.
stop_peer() {
local index=$1 protocol=${protocols[$1]}
dock 7 exec "${peers[index]}" /bin/sh -ec '
read -r pid < /run/xray/pid
kill -TERM "$pid"
while kill -0 "$pid" 2>/dev/null; do sleep 0.05; done
rm /run/xray/pid
' >/dev/null 2>&1 || die "cannot stop the $protocol reference peer"
}
for i in "${!protocols[@]}"; do
protocol=${protocols[i]}
peer=$run_name-$protocol
config=xray-$protocol.json
dock 12 run "${common[@]}" "${restricted[@]}" "${small_pg[@]}" "${certs[@]}" --init \
--name "$peer" --ip "$prefix.$((11 + i))" --user 0:0 --cpus 0.30 --memory 128m \
--tmpfs /run/xray:rw,nosuid,nodev,noexec,size=64k \
--mount "type=bind,src=$xray_bin,dst=/opt/xray,readonly" \
--mount "type=bind,src=$fixture/$config,dst=/fixture/$config,readonly" \
--entrypoint /bin/sleep "$pg_image" infinity >/dev/null 2>&1 || die "cannot anchor the $protocol reference peer"
peers+=("$peer")
start_peer "$i"
done
fixture_run peers-ready
phase 'starting the unmodified release entrypoint and checking an empty catalog'
# Do not override the image's user, command or entrypoint. Only the test CA
# is mounted into the release container; peer credentials arrive via its DB.
dock 12 run "${common[@]}" --name "$gateway" --ip "$prefix.20" --cpus 0.50 --memory 192m \
--read-only --cap-drop ALL --env-file "$work/gateway.env" --env SSL_CERT_FILE=/run/gateway-smoke-ca.pem \
--mount "type=bind,src=$fixture/ca.pem,dst=/run/gateway-smoke-ca.pem,readonly" \
"$release_id" >/dev/null 2>&1 || die 'cannot start the release container'
fixture_run empty
phase 'publishing four candidates and verifying exported HTTP and CONNECT routes'
dock 8 exec "$verifier" /bin/cat /fixture/seed.sql 2>/dev/null | psql_admin -q >/dev/null 2>&1 || die 'cannot seed the synthetic snapshot'
fixture_run verify
phase 'checking that a stopped peer cannot fail over'
stop_peer 0
fixture_run failed-route
start_peer 0
fixture_run peers-ready
restart_gateway() {
dock 16 restart --time 10 "$gateway" >/dev/null 2>&1 || die 'cannot restart the release container'
}
phase 'checking stable exported credentials after restart'
restart_gateway
fixture_run snapshot
phase 'checking withdrawal after a successful probe pass with all peers down'
for i in "${!peers[@]}"; do stop_peer "$i"; done
restart_gateway
fixture_run down
phase 'checking recovery via the same exported credentials'
for i in "${!peers[@]}"; do start_peer "$i"; done
fixture_run peers-ready
restart_gateway
fixture_run snapshot
+198
View File
@@ -0,0 +1,198 @@
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"time"
)
type catalogPayload struct {
SessionID *int64 `json:"session_id"`
FinishedAt time.Time `json:"session_finished_at"`
AsOf time.Time `json:"as_of"`
Total int `json:"total"`
Items []catalogItem `json:"items"`
}
type catalogItem struct {
ID string `json:"proxy_id"`
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
URL string `json:"proxy_url"`
Country string `json:"country"`
Protocol string `json:"protocol"`
ExitIP string `json:"exit_ip"`
Speed float64 `json:"speed_mbps"`
Latency int `json:"latency_ms"`
CheckedAt time.Time `json:"checked_at"`
}
func (c checkClient) checkReadyCatalog(ctx context.Context) ([]string, error) {
all := []int{0, 1, 2, 3}
for _, selection := range []struct {
query url.Values
ids []int
}{
{nil, all},
{url.Values{"country": {"DE"}, "protocol": {"ss,vmess", "trojan"}, "min_speed_mbps": {"10"}, "sort": {"speed"}}, []int{2, 0}},
} {
if _, err := c.checkCatalog(ctx, selection.query, selection.ids, true); err != nil {
return nil, err
}
}
links := make([]string, 0, len(peers))
for i, peer := range peers {
query := url.Values{"protocol": {peer.protocol}, "country": {peer.country}, "min_speed_mbps": {strconv.Itoa((i + 1) * 10)}}
selected, err := c.checkCatalog(ctx, query, []int{i}, true)
if err != nil {
return nil, fmt.Errorf("%s selection: %w", peer.protocol, err)
}
links = append(links, selected[0])
}
return links, nil
}
func (c checkClient) checkCatalog(ctx context.Context, filter url.Values, ids []int, hasSession bool) ([]string, error) {
result, err := c.readCatalog(ctx, filter, ids, hasSession)
if err != nil {
return nil, err
}
data, err := c.catalogResponse(ctx, filter, "csv", "text/csv; charset=utf-8")
if err != nil {
return nil, err
}
if err := compareCSV(data, result); err != nil {
return nil, err
}
for _, format := range []string{"txt", "proxy-url-list-txt"} {
data, err := c.catalogResponse(ctx, filter, format, "text/plain; charset=utf-8")
if err != nil {
return nil, err
}
lines, err := textRecords(data, len(result.Items))
if err != nil {
return nil, fmt.Errorf("%s catalog: %w", format, err)
}
for i, line := range lines {
item := result.Items[i]
if format == "txt" {
// This dedicated bridge has only IPv4 fixture endpoints.
if !slices.Equal(strings.Split(line, ":"), []string{item.Host, strconv.Itoa(item.Port), item.Username, item.Password}) {
return nil, errors.New("TXT catalog credentials differ from JSON")
}
} else if u, err := c.parseLink(ids[i], line); err != nil || u.String() != item.URL {
return nil, errors.New("proxy URL list differs from JSON selection")
}
}
if format == "proxy-url-list-txt" {
return lines, nil
}
}
return nil, errors.New("missing proxy URL list")
}
func textRecords(data []byte, want int) ([]string, error) {
if want == 0 && len(data) == 0 {
return nil, nil
}
content, ok := strings.CutSuffix(string(data), "\n")
if !ok {
return nil, errors.New("expected newline-terminated records")
}
lines := strings.Split(content, "\n")
if len(lines) != want {
return nil, errors.New("wrong text catalog row count")
}
return lines, nil
}
func (c checkClient) catalogResponse(ctx context.Context, filter url.Values, format, mediaType string) ([]byte, error) {
query := url.Values{"format": {format}}
for key, values := range filter {
query[key] = values
}
code, header, body, err := c.apiRequest(ctx, "/v1/proxies", query, c.token)
if err != nil || code != http.StatusOK || header.Get("Content-Type") != mediaType || header.Get("Cache-Control") != "no-store" {
return nil, fmt.Errorf("invalid %s catalog response (status %d)", format, code)
}
return body, nil
}
func (c checkClient) readCatalog(ctx context.Context, filter url.Values, ids []int, hasSession bool) (catalogPayload, error) {
var result catalogPayload
body, err := c.catalogResponse(ctx, filter, "json", "application/json")
if err != nil {
return result, err
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
if decoder.Decode(&result) != nil || decoder.Decode(new(any)) != io.EOF || result.AsOf.IsZero() ||
result.Total != len(ids) || result.Items == nil || len(result.Items) != len(ids) ||
(result.SessionID != nil) != hasSession || result.FinishedAt.IsZero() == hasSession ||
(result.SessionID != nil && *result.SessionID != 1) {
return result, errors.New("invalid JSON catalog metadata or row count")
}
for pos, i := range ids {
item := result.Items[pos]
u, err := c.parseLink(i, item.URL)
if err != nil {
return result, err
}
password, _ := u.User.Password()
if item.ID != strconv.Itoa(i+1) || item.Host != c.ip(gatewayIP) || item.Port != 8081 ||
item.Username != u.User.Username() || item.Password != password || item.Country != peers[i].country ||
item.Protocol != peers[i].protocol || item.ExitIP != c.peerIP(i) || item.Speed != float64((i+1)*10) ||
item.Latency < 0 || item.CheckedAt.IsZero() || item.CheckedAt.After(result.AsOf) {
return result, fmt.Errorf("invalid JSON catalog fields for %s fixture", peers[i].protocol)
}
}
return result, nil
}
func (c checkClient) parseLink(i int, link string) (*url.URL, error) {
u, err := url.Parse(link)
if err != nil || u.Scheme != "http" || u.Host != c.addr(gatewayIP, proxyPort) ||
u.Path != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" ||
u.User == nil || u.User.Username() != "node-"+strconv.Itoa(i+1) {
return nil, fmt.Errorf("invalid %s fixture proxy URL", peers[i].protocol)
}
password, ok := u.User.Password()
decoded, err := base64.RawURLEncoding.Strict().DecodeString(password)
if !ok || err != nil || len(decoded) != 32 {
return nil, fmt.Errorf("invalid %s fixture proxy credentials", peers[i].protocol)
}
return u, nil
}
func compareCSV(data []byte, result catalogPayload) error {
rows, err := csv.NewReader(bytes.NewReader(data)).ReadAll()
if err != nil || len(rows) != len(result.Items)+1 || !slices.Equal(rows[0], []string{
"proxy_id", "host", "port", "username", "password", "proxy_url", "country", "protocol",
"exit_ip", "speed_mbps", "latency_ms", "checked_at", "session_finished_at",
}) {
return errors.New("invalid CSV catalog header or row count")
}
for i, item := range result.Items {
if !slices.Equal(rows[i+1], []string{
item.ID, item.Host, strconv.Itoa(item.Port), item.Username, item.Password, item.URL, item.Country,
item.Protocol, item.ExitIP, strconv.FormatFloat(item.Speed, 'g', -1, 64), strconv.Itoa(item.Latency),
item.CheckedAt.Format(time.RFC3339Nano), result.FinishedAt.Format(time.RFC3339Nano),
}) {
return errors.New("CSV catalog fields differ from JSON selection")
}
}
return nil
}
+279
View File
@@ -0,0 +1,279 @@
package main
import (
"bytes"
"context"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"slices"
"time"
)
const responseLimit = challengeSize + 4096
type checkClient struct {
fixture
token string
api *http.Client
roots *x509.CertPool
}
type statusPayload struct {
State string `json:"state"`
Candidates int `json:"candidate_count"`
Ready int `json:"ready_count"`
LastSuccess time.Time `json:"last_success_at"`
CurrentSession *int64 `json:"session_id"`
}
type baseline struct {
LastSuccess time.Time `json:"last_success"`
URLs []string `json:"urls"`
}
func (f fixture) verify(ctx context.Context, mode string) error {
token, err := f.setting("GATEWAY_API_TOKEN")
if err != nil {
return err
}
ca, err := f.read("ca.pem")
if err != nil {
return errors.New("read fixture client CA")
}
c := checkClient{fixture: f, token: token, roots: x509.NewCertPool()}
if !c.roots.AppendCertsFromPEM(ca) {
return errors.New("parse fixture client CA")
}
c.api = &http.Client{
Transport: &http.Transport{DialContext: f.clientDial},
Timeout: 3 * time.Second, CheckRedirect: noRedirect,
}
defer c.api.CloseIdleConnections()
if mode == "empty" {
if _, err := c.wait(ctx, 0, 0, time.Time{}); err != nil {
return err
}
_, err := c.checkCatalog(ctx, nil, nil, false)
return err
}
const snapshotFile = "links.json"
var previous baseline
data, err := f.read(snapshotFile)
switch {
case err == nil:
if json.Unmarshal(data, &previous) != nil || len(previous.URLs) != len(peers) || previous.LastSuccess.IsZero() {
return errors.New("invalid fixture link baseline")
}
case errors.Is(err, os.ErrNotExist) && mode == "verify":
default:
return errors.New("missing fixture link baseline")
}
switch mode {
case "failed-route":
if err := c.checkRoute(ctx, 0, previous.URLs[0], http.StatusBadGateway); err != nil {
return err
}
return c.checkRoute(ctx, 1, previous.URLs[1], http.StatusOK)
case "down":
if _, err := c.wait(ctx, len(peers), 0, previous.LastSuccess); err != nil {
return err
}
if _, err := c.checkCatalog(ctx, nil, nil, true); err != nil {
return err
}
for i, link := range previous.URLs {
if err := c.checkRoute(ctx, i, link, http.StatusServiceUnavailable); err != nil {
return err
}
}
return nil
}
lastSuccess, err := c.wait(ctx, len(peers), len(peers), previous.LastSuccess)
if err != nil {
return err
}
links, err := c.checkReadyCatalog(ctx)
if err != nil {
return err
}
if previous.URLs != nil && !slices.Equal(links, previous.URLs) {
return errors.New("exported links changed after restart")
}
if err := c.checkAuth(ctx, links[0]); err != nil {
return err
}
for i, link := range links {
if err := c.checkRoute(ctx, i, link, http.StatusOK); err != nil {
return err
}
}
if previous.URLs == nil {
data, err := json.Marshal(baseline{LastSuccess: lastSuccess, URLs: links})
if err != nil {
return errors.New("encode fixture link baseline")
}
return f.write(snapshotFile, data, 0o600)
}
return nil
}
func noRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
func (c checkClient) apiRequest(ctx context.Context, path string, query url.Values, token string) (int, http.Header, []byte, error) {
u := url.URL{Scheme: "http", Host: c.addr(gatewayIP, apiPort), Path: path, RawQuery: query.Encode()}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return 0, nil, nil, errors.New("construct fixture API request")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
return doRequest(c.api, req)
}
func doRequest(client *http.Client, req *http.Request) (int, http.Header, []byte, error) {
res, err := client.Do(req)
if err != nil {
return 0, nil, nil, errors.New("fixture request did not complete")
}
defer res.Body.Close()
body, err := io.ReadAll(io.LimitReader(res.Body, responseLimit+1))
if err != nil || len(body) > responseLimit {
return res.StatusCode, res.Header, nil, errors.New("invalid fixture response body")
}
return res.StatusCode, res.Header, body, nil
}
func (c checkClient) wait(ctx context.Context, candidates, ready int, after time.Time) (time.Time, error) {
tick := time.NewTicker(250 * time.Millisecond)
defer tick.Stop()
var last statusPayload
for {
code, _, _, err := c.apiRequest(ctx, "/readyz", nil, "")
if err == nil && code == http.StatusOK {
code, _, data, err := c.apiRequest(ctx, "/v1/status", nil, c.token)
if err == nil && code == http.StatusOK && json.Unmarshal(data, &last) == nil &&
last.Candidates == candidates && last.Ready == ready && last.State == "idle" &&
last.LastSuccess.After(after) && (last.CurrentSession == nil) == (candidates == 0) {
return last.LastSuccess, nil
}
}
select {
case <-ctx.Done():
return time.Time{}, fmt.Errorf("gateway did not publish a successful %d/%d fixture pass (last counts %d/%d)",
ready, candidates, last.Ready, last.Candidates)
case <-tick.C:
}
}
}
func (c checkClient) checkAuth(ctx context.Context, link string) error {
if code, _, _, err := c.apiRequest(ctx, "/healthz", nil, ""); err != nil || code != http.StatusOK {
return errors.New("gateway liveness endpoint did not return 200")
}
for _, token := range []string{"", "invalid-fixture-token"} {
code, header, _, err := c.apiRequest(ctx, "/v1/proxies", nil, token)
if err != nil || code != http.StatusUnauthorized || header.Get("WWW-Authenticate") != "Bearer" {
return errors.New("catalog did not reject absent/invalid bearer credentials")
}
}
u, err := c.parseLink(0, link)
if err != nil {
return err
}
for _, invalid := range []*url.Userinfo{nil, url.UserPassword(u.User.Username(), c.token)} {
u.User = invalid
if err := c.runRoute(ctx, 0, u, http.StatusProxyAuthRequired); err != nil {
return err
}
}
return nil
}
func (c checkClient) checkRoute(ctx context.Context, i int, link string, want int) error {
u, err := c.parseLink(i, link)
if err != nil {
return err
}
return c.runRoute(ctx, i, u, want)
}
func (c checkClient) runRoute(ctx context.Context, i int, proxyURL *url.URL, want int) error {
for _, scheme := range []string{"http", "https"} {
got, err := c.exchange(ctx, i, scheme, proxyURL, want == http.StatusOK)
if err != nil || got != want {
return fmt.Errorf("%s %s fixture exchange: expected status %d and matching origin proof when successful (got %d)",
peers[i].protocol, scheme, want, got)
}
}
return nil
}
func (c checkClient) exchange(ctx context.Context, i int, scheme string, proxyURL *url.URL, checkEcho bool) (int, error) {
connectStatus := make(chan int, 1)
tr := &http.Transport{
Proxy: http.ProxyURL(proxyURL), DialContext: c.clientDial, DisableKeepAlives: true,
TLSClientConfig: &tls.Config{RootCAs: c.roots, MinVersion: tls.VersionTLS12},
OnProxyConnectResponse: func(_ context.Context, _ *url.URL, _ *http.Request, res *http.Response) error {
if res.StatusCode == http.StatusProxyAuthRequired && res.Header.Get("Proxy-Authenticate") != `Basic realm="http-gateway"` {
return errors.New("invalid proxy authentication challenge")
}
connectStatus <- res.StatusCode
return nil
},
}
defer tr.CloseIdleConnections()
client := &http.Client{Transport: tr, Timeout: 8 * time.Second, CheckRedirect: noRedirect}
port := httpPort
if scheme == "https" {
port = httpsPort
}
var nonceBytes [16]byte
rand.Read(nonceBytes[:])
nonce := hex.EncodeToString(nonceBytes[:])
var challenge []byte
if checkEcho {
challenge = make([]byte, challengeSize)
rand.Read(challenge)
}
u := url.URL{Scheme: scheme, Host: net.JoinHostPort(originName, port), Path: "/echo"}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(challenge))
if err != nil {
return 0, errors.New("construct fixture origin request")
}
req.Header.Set(nonceHeader, nonce)
req.Header.Set(routeHeader, c.peerIP(i))
req.Header.Set("Authorization", "Fixture "+nonce)
code, header, body, err := doRequest(client, req)
if scheme == "https" {
select {
case status := <-connectStatus:
if status != http.StatusOK && code == 0 {
return status, nil // A non-200 CONNECT is returned as a client error.
}
default:
return code, errors.New("no CONNECT acknowledgement")
}
} else if code == http.StatusProxyAuthRequired && header.Get("Proxy-Authenticate") != `Basic realm="http-gateway"` {
return code, errors.New("invalid proxy authentication challenge")
}
if err == nil && checkEcho && (header.Get(routeHeader) != c.peerIP(i) ||
header.Get(nonceHeader) != nonce || !bytes.Equal(body, challenge)) {
return code, errors.New("origin route or echo differs")
}
return code, err
}
+209
View File
@@ -0,0 +1,209 @@
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"math/big"
"net"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gofrs/uuid"
)
const cipherName = "aes-128-gcm"
func (f fixture) generate() error {
if err := f.generateCertificates(); err != nil {
return err
}
var seed strings.Builder
seed.WriteString(`\set ON_ERROR_STOP on
BEGIN;
DO $$ BEGIN
IF current_schema() IS DISTINCT FROM 'gateway_smoke'
OR EXISTS (SELECT FROM check_sessions) OR EXISTS (SELECT FROM proxies) THEN
RAISE EXCEPTION 'expected an empty gateway_smoke fixture schema';
END IF;
END $$;
INSERT INTO check_sessions (id, status, is_current, finished_at, valid)
OVERRIDING SYSTEM VALUE VALUES (1, 'completed', true, now(), 4);
`)
var enrollment []string
for i, peer := range peers {
address, port := f.peerIP(i), peerPort(i)
upstream, err := f.generatePeer(i, address, port)
if err != nil {
return err
}
id := i + 1
source := "fixture-a"
if id%2 == 0 {
source = "fixture-b"
}
fmt.Fprintf(&seed, `INSERT INTO proxies (id, canonical_url, protocol, host, port, source_name)
OVERRIDING SYSTEM VALUE VALUES (%d, %s, '%s', '%s', %d, '%s');
INSERT INTO session_proxies (session_id, proxy_id, canonical_url, protocol, host, port, source_name, country, exit_ip, speed_mbps)
VALUES (1, %d, %s, '%s', '%s', %d, '%s', '%s', '%s', %d);
`, id, sqlLiteral(upstream), peer.protocol, address, port, source,
id, sqlLiteral(upstream), peer.protocol, address, port, source, peer.country, address, id*10)
enrollment = append(enrollment, address+"/32")
}
seed.WriteString("COMMIT;\n")
if err := f.write("seed.sql", []byte(seed.String()), 0o600); err != nil {
return err
}
var apiSecret, nodeSecret [32]byte
rand.Read(apiSecret[:])
rand.Read(nodeSecret[:])
env := fmt.Sprintf(`GATEWAY_PUBLIC_PROXY_ADDR=%s
GATEWAY_API_TOKEN=%s
GATEWAY_NODE_SECRET=%s
GATEWAY_PROBE_URL=https://%s:%s/health204
GATEWAY_ALLOWED_DESTINATIONS=%s:%s,%s:%s
GATEWAY_UPSTREAM_NETWORKS=%s
`, f.addr(gatewayIP, proxyPort), base64.RawURLEncoding.EncodeToString(apiSecret[:]),
base64.RawURLEncoding.EncodeToString(nodeSecret[:]), originName, httpsPort,
originName, httpPort, originName, httpsPort, strings.Join(enrollment, ","))
return f.write("gateway.env", []byte(env), 0o600)
}
func sqlLiteral(s string) string { return "'" + strings.ReplaceAll(s, "'", "''") + "'" }
func (f fixture) generatePeer(i int, ip string, port int) (string, error) {
const inboundTag = "smoke-peer"
protocol := peers[i].protocol
credential := rand.Text()
if protocol == "vmess" || protocol == "vless" {
id, err := uuid.NewV4()
if err != nil {
return "", errors.New("generate fixture UUID")
}
credential = id.String()
}
u := url.URL{Scheme: protocol, Host: net.JoinHostPort(ip, strconv.Itoa(port)), User: url.User(credential)}
stream := map[string]any{"network": "tcp"}
var settings map[string]any
switch protocol {
case "ss":
protocol = "shadowsocks"
settings = map[string]any{"method": cipherName, "password": credential, "network": "tcp"}
u.User = url.User(base64.RawURLEncoding.EncodeToString([]byte(cipherName + ":" + credential)))
case "trojan":
settings = map[string]any{"clients": []map[string]string{{"password": credential}}}
case "vmess":
settings = map[string]any{"clients": []map[string]string{{"id": credential, "security": cipherName}}}
case "vless":
settings = map[string]any{"clients": []map[string]string{{"id": credential}}, "decryption": "none"}
}
if protocol == "trojan" || protocol == "vless" {
stream["security"] = "tls"
stream["tlsSettings"] = map[string]any{
"minVersion": "1.2", "rejectUnknownSni": true,
"certificates": []map[string]any{{
"certificateFile": filepath.Join(f.dir, "server.pem"),
"keyFile": filepath.Join(f.dir, "server-key.pem"),
"oneTimeLoading": true,
}},
}
query := url.Values{"type": {"tcp"}, "security": {"tls"}, "sni": {peerName}}
if protocol == "vless" {
query.Set("encryption", "none")
}
u.RawQuery = query.Encode()
}
config, err := json.Marshal(map[string]any{
"log": map[string]string{"access": "none", "error": "none", "loglevel": "none"},
"inbounds": []map[string]any{{
"tag": inboundTag, "listen": ip, "port": port, "protocol": protocol,
"settings": settings, "streamSettings": stream,
}},
"outbounds": []map[string]any{
{"protocol": "blackhole", "tag": "deny"},
{"protocol": "freedom", "tag": "origin", "sendThrough": ip},
},
"routing": map[string]any{"domainStrategy": "AsIs", "rules": []map[string]any{{
"type": "field", "inboundTag": []string{inboundTag}, "network": "tcp",
"ip": []string{f.ip(originIP) + "/32"}, "port": httpPort + "," + httpsPort, "outboundTag": "origin",
}}},
})
if err != nil {
return "", errors.New("encode fixture peer config")
}
if err := f.write("xray-"+peers[i].protocol+".json", config, 0o600); err != nil {
return "", err
}
if protocol != "vmess" {
return u.String(), nil
}
payload, err := json.Marshal(map[string]any{
"v": "2", "add": ip, "port": port, "id": credential, "aid": 0,
"net": "tcp", "scy": cipherName,
})
if err != nil {
return "", errors.New("encode fixture VMess endpoint")
}
return "vmess://" + base64.RawStdEncoding.EncodeToString(payload), nil
}
func (f fixture) generateCertificates() error {
const ttl = 12 * time.Hour
now := time.Now()
ca := x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "Gateway release smoke CA"},
NotBefore: now.Add(-5 * time.Minute), NotAfter: now.Add(ttl),
IsCA: true, BasicConstraintsValid: true, MaxPathLenZero: true,
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
}
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return errors.New("generate fixture CA key")
}
caDER, err := x509.CreateCertificate(rand.Reader, &ca, &ca, &caKey.PublicKey, caKey)
if err != nil {
return errors.New("create fixture CA certificate")
}
leaf := x509.Certificate{
SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: originName}, DNSNames: []string{originName, peerName},
NotBefore: ca.NotBefore, NotAfter: ca.NotAfter, KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return errors.New("generate fixture server key")
}
leafDER, err := x509.CreateCertificate(rand.Reader, &leaf, &ca, &key.PublicKey, caKey)
if err != nil {
return errors.New("create fixture server certificate")
}
keyDER, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return errors.New("encode fixture server key")
}
for _, file := range []struct {
name, tag string
der []byte
perm os.FileMode
}{
{"ca.pem", "CERTIFICATE", caDER, 0o644},
{"server.pem", "CERTIFICATE", leafDER, 0o644},
{"server-key.pem", "PRIVATE KEY", keyDER, 0o600},
} {
if err := f.write(file.name, pem.EncodeToMemory(&pem.Block{Type: file.tag, Bytes: file.der}), file.perm); err != nil {
return err
}
}
return nil
}
+178
View File
@@ -0,0 +1,178 @@
// Command imagefixture supplies the disposable release-image smoke network.
package main
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
const (
originName = "origin.gateway.test"
peerName = "peer.gateway.test"
httpPort = "18080"
httpsPort = "18443"
proxyPort = "8081"
apiPort = "8082"
databaseIP = 4
originIP = 10
gatewayIP = 20
clientIP = 21
)
var peers = [...]struct {
protocol string
country string
}{
{"ss", "DE"},
{"trojan", "NL"},
{"vmess", "DE"},
{"vless", "NL"},
}
type fixture struct {
dir string
prefix string
}
func main() {
if err := run(); err != nil {
// Only locally generated diagnostics reach here. In particular, never
// print URL, PostgreSQL driver, Xray, or response-body errors.
fmt.Fprintln(os.Stderr, "imagefixture:", err)
os.Exit(1)
}
}
func run() error {
if len(os.Args) != 3 {
return errors.New("usage: imagefixture <generate|origin|peers-ready|empty|verify|snapshot|failed-route|down|privileges> <fixture-dir>")
}
prefix := os.Getenv("GATEWAY_FIXTURE_PREFIX")
octet, err := strconv.Atoi(strings.TrimPrefix(prefix, "11.254."))
if err != nil || octet < 1 || octet > 254 || prefix != "11.254."+strconv.Itoa(octet) {
return errors.New("GATEWAY_FIXTURE_PREFIX must be the dedicated Docker smoke prefix 11.254.<1..254>")
}
f := fixture{dir: os.Args[2], prefix: prefix}
mode := os.Args[1]
switch mode {
case "generate":
return f.generate()
case "origin":
return f.serveOrigin()
case "peers-ready":
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
defer cancel()
return f.waitPeers(ctx)
case "empty", "verify", "snapshot", "failed-route", "down", "privileges":
ctx, cancel := context.WithTimeout(context.Background(), 55*time.Second)
defer cancel()
if mode == "privileges" {
return f.verifyPrivileges(ctx)
}
return f.verify(ctx, mode)
default:
return errors.New("unknown fixture mode")
}
}
func (f fixture) ip(suffix int) string { return f.prefix + "." + strconv.Itoa(suffix) }
func (f fixture) addr(suffix int, port string) string { return net.JoinHostPort(f.ip(suffix), port) }
func (f fixture) peerIP(i int) string { return f.ip(11 + i) }
func peerPort(i int) int { return 11001 + i }
func (f fixture) write(name string, data []byte, perm os.FileMode) error {
file, err := os.OpenFile(filepath.Join(f.dir, name), os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
if err != nil {
return fmt.Errorf("create %s", name)
}
// The nonroot release container mounts this public trust root directly.
if perm == 0o644 && file.Chmod(perm) != nil {
file.Close()
return fmt.Errorf("set public certificate permissions on %s", name)
}
_, writeErr := file.Write(data)
closeErr := file.Close()
if writeErr != nil || closeErr != nil {
return fmt.Errorf("write %s", name)
}
return nil
}
func (f fixture) read(name string) ([]byte, error) {
data, err := os.ReadFile(filepath.Join(f.dir, name))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, os.ErrNotExist
}
return nil, fmt.Errorf("read %s", name)
}
return data, nil
}
func (f fixture) setting(name string) (string, error) {
if value := os.Getenv(name); value != "" {
return value, nil
}
data, err := f.read("gateway.env")
if err != nil {
return "", err
}
for line := range strings.SplitSeq(string(data), "\n") {
key, value, _ := strings.Cut(line, "=")
if key == name && value != "" {
return value, nil
}
}
return "", fmt.Errorf("missing %s in fixture environment", name)
}
// Bind all verifier sockets to its explicitly assigned bridge address and
// pin every destination. Exported credentials never choose the dial target.
func (f fixture) clientDial(ctx context.Context, network, addr string) (net.Conn, error) {
if network != "tcp" {
return nil, errors.New("unexpected fixture network")
}
switch addr {
case f.addr(gatewayIP, apiPort), f.addr(gatewayIP, proxyPort), f.addr(databaseIP, "5432"):
default:
return nil, errors.New("refusing connection outside the smoke fixture")
}
return f.dialFixture(ctx, addr)
}
func (f fixture) dialFixture(ctx context.Context, addr string) (net.Conn, error) {
dialer := net.Dialer{
LocalAddr: net.TCPAddrFromAddrPort(netip.AddrPortFrom(netip.MustParseAddr(f.ip(clientIP)), 0)),
Timeout: 3 * time.Second,
}
return dialer.DialContext(ctx, "tcp4", addr)
}
func (f fixture) waitPeers(ctx context.Context) error {
tick := time.NewTicker(150 * time.Millisecond)
defer tick.Stop()
for i, peer := range peers {
addr := net.JoinHostPort(f.peerIP(i), strconv.Itoa(peerPort(i)))
for {
conn, err := f.dialFixture(ctx, addr)
if err == nil {
conn.Close()
break
}
select {
case <-ctx.Done():
return fmt.Errorf("fixture %s peer did not open its listener", peer.protocol)
case <-tick.C:
}
}
}
return nil
}
+118
View File
@@ -0,0 +1,118 @@
package main
import (
"context"
"crypto/tls"
"encoding/hex"
"errors"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
)
const (
challengeSize = 80 * 1024
routeHeader = "X-Fixture-Route"
nonceHeader = "X-Fixture-Nonce"
)
func (f fixture) serveOrigin() error {
cert, err := tls.LoadX509KeyPair(filepath.Join(f.dir, "server.pem"), filepath.Join(f.dir, "server-key.pem"))
if err != nil {
return errors.New("load fixture origin TLS identity")
}
plain, err := net.Listen("tcp4", f.addr(originIP, httpPort))
if err != nil {
return errors.New("bind fixture HTTP origin")
}
defer plain.Close()
secure, err := net.Listen("tcp4", f.addr(originIP, httpsPort))
if err != nil {
return errors.New("bind fixture HTTPS origin")
}
defer secure.Close()
newServer := func() *http.Server {
return &http.Server{
Handler: http.HandlerFunc(f.serveChallenge), MaxHeaderBytes: 8 * 1024,
ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 8 * time.Second,
WriteTimeout: 8 * time.Second, IdleTimeout: 5 * time.Second,
ErrorLog: log.New(io.Discard, "", 0),
}
}
httpServer, httpsServer := newServer(), newServer()
httpsServer.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
done := make(chan error, 2)
go func() { done <- httpServer.Serve(plain) }()
go func() { done <- httpsServer.ServeTLS(secure, "", "") }()
select {
case <-ctx.Done():
shutdown, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = httpServer.Shutdown(shutdown)
_ = httpsServer.Shutdown(shutdown)
<-done
<-done
return nil
case <-done:
_ = httpServer.Close()
_ = httpsServer.Close()
<-done
return errors.New("fixture origin listener stopped")
}
}
func (f fixture) serveChallenge(w http.ResponseWriter, r *http.Request) {
port := httpPort
if r.TLS != nil {
port = httpsPort
}
if r.Host != net.JoinHostPort(originName, port) || r.URL.RawQuery != "" {
w.WriteHeader(http.StatusBadRequest)
return
}
remote, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
var knownPeer bool
for i := range peers {
knownPeer = knownPeer || remote == f.peerIP(i)
}
switch {
case r.Method == http.MethodGet && r.URL.Path == "/health204" && r.TLS != nil:
if remote != f.ip(gatewayIP) && !knownPeer {
w.WriteHeader(http.StatusForbidden)
return
}
w.WriteHeader(http.StatusNoContent)
case r.Method == http.MethodPost && r.URL.Path == "/echo":
nonce := r.Header.Get(nonceHeader)
_, nonceErr := hex.DecodeString(nonce)
if !knownPeer || r.Header.Get(routeHeader) != remote || len(nonce) != 32 || nonceErr != nil ||
r.Header.Get("Authorization") != "Fixture "+nonce || r.Header.Get("Proxy-Authorization") != "" ||
r.Header.Get("X-Gateway-Probe") != "" {
w.WriteHeader(http.StatusForbidden)
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, challengeSize))
if err != nil || len(body) != challengeSize {
w.WriteHeader(http.StatusBadRequest)
return
}
w.Header().Set(routeHeader, remote)
w.Header().Set(nonceHeader, nonce)
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write(body)
default:
w.WriteHeader(http.StatusNotFound)
}
}
+65
View File
@@ -0,0 +1,65 @@
package main
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
func (f fixture) verifyPrivileges(ctx context.Context) error {
dsn, err := f.setting("GATEWAY_DB_DSN")
if err != nil {
return err
}
cfg, err := pgx.ParseConfig(dsn)
if err != nil || cfg.Host != f.ip(databaseIP) || cfg.Port != 5432 || cfg.Database != "gateway_smoke" ||
cfg.User != "gateway_smoke_app" || cfg.RuntimeParams["search_path"] != "gateway_smoke" {
return errors.New("fixture database must use the isolated PostgreSQL address, database, schema, and login")
}
cfg.DialFunc = f.clientDial
conn, err := pgx.ConnectConfig(ctx, cfg)
if err != nil {
return errors.New("connect with restricted fixture database role")
}
defer conn.Close(ctx)
var restricted bool
err = conn.QueryRow(ctx, `SELECT current_schema() = 'gateway_smoke' AND NOT (
rolsuper OR rolcreatedb OR rolcreaterole OR rolreplication OR rolbypassrls OR
has_schema_privilege(current_user, 'gateway_smoke', 'CREATE') OR
has_database_privilege(current_user, current_database(), 'CREATE'))
FROM pg_catalog.pg_roles WHERE rolname = current_user`).Scan(&restricted)
if err != nil || !restricted {
return errors.New("fixture database role has elevated privileges or a wrong schema")
}
var one int
err = conn.QueryRow(ctx, `SELECT 1 FROM gateway_runtime WHERE id = 1 AND EXISTS (
SELECT 1 FROM gateway_check_interval WHERE value::integer BETWEEN 15 AND 30)
AND (SELECT count(*) FROM gateway_candidates) >= 0
AND (SELECT count(*) FROM gateway_current_session) >= 0
AND (SELECT count(*) FROM gateway_node_health) >= 0`).Scan(&one)
if err != nil || one != 1 {
return errors.New("restricted role cannot read required gateway data")
}
for _, check := range []struct {
name, statement string
}{
{"settings (including bot token)", `SELECT value FROM settings WHERE key = 'telegram_bot_token'`},
{"subscriptions", `SELECT 1 FROM subscriptions WHERE false`},
{"snapshot history", `SELECT 1 FROM check_sessions WHERE false`},
{"snapshot writes", `UPDATE session_proxies SET protocol = 'forbidden' WHERE false`},
{"settings writes", `UPDATE settings SET value = 'forbidden' WHERE false`},
{"store identity writes", `UPDATE gateway_runtime SET store_uuid = gen_random_uuid() WHERE false`},
{"health deletes", `DELETE FROM gateway_node_health WHERE false`},
} {
_, err := conn.Exec(ctx, check.statement)
var dbErr *pgconn.PgError
if !errors.As(err, &dbErr) || dbErr.Code != "42501" {
return fmt.Errorf("fixture database role did not receive permission denied for %s", check.name)
}
}
return nil
}
+283
View File
@@ -0,0 +1,283 @@
//go:build linux
// Command gateway is the disposable database and browser fixture for verify.sh.
package main
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"git.eeee.moe/omar/zhguchiy_perchik/internal/db"
"github.com/jackc/pgx/v5"
)
func main() {
log.SetFlags(0)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := run(ctx, os.Args[1:]); err != nil {
log.Fatal("gateway-contract: ", err)
}
}
func run(ctx context.Context, args []string) error {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
return errors.New("TEST_DATABASE_URL must name a disposable PostgreSQL database")
}
if len(args) == 1 && args[0] == "check-db" {
ready, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
cn, err := pgx.Connect(ready, dsn)
if err != nil {
return errors.New("cannot connect to TEST_DATABASE_URL")
}
defer cn.Close(ready)
var version int
var allowed bool
err = cn.QueryRow(ready, `SELECT current_setting('server_version_num')::int,
(rolsuper OR (rolcreatedb AND rolcreaterole)) AND has_database_privilege(current_database(), 'CREATE')
FROM pg_catalog.pg_roles WHERE rolname = current_user`).Scan(&version, &allowed)
if err != nil || version < 160000 || version >= 170000 {
return errors.New("the contract requires PostgreSQL server major version 16")
}
if !allowed {
return errors.New("the disposable DB role needs CREATE on the database, CREATEDB, and CREATEROLE")
}
return nil
}
if len(args) != 3 || args[0] != "browser" {
return errors.New("usage: setup check-db | setup browser <admin API binary> <artifact directory>")
}
return browser(ctx, dsn, args[1], args[2])
}
func browser(ctx context.Context, dsn, apiBin, artifactDir string) (result error) {
setupCtx, cancelSetup := context.WithTimeout(ctx, 15*time.Second)
defer cancelSetup()
admin, err := pgx.Connect(setupCtx, dsn)
if err != nil {
return errors.New("cannot connect to the browser fixture database")
}
defer func() {
cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = admin.Close(cleanup)
}()
schema := "gateway_ui_" + strings.ToLower(rand.Text())
quoted := pgx.Identifier{schema}.Sanitize()
if _, err := admin.Exec(setupCtx, "CREATE SCHEMA "+quoted); err != nil {
return errors.New("could not create the browser fixture schema")
}
defer func() {
cleanup, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if _, err := admin.Exec(cleanup, "DROP SCHEMA "+quoted+" CASCADE"); err != nil {
result = errors.Join(result, errors.New("could not drop the browser fixture schema"))
}
}()
scopedDSN, err := withSchema(dsn, schema)
if err != nil {
return err
}
store, err := db.New(setupCtx, scopedDSN)
if err != nil {
return errors.New("could not connect to the scoped browser fixture schema")
}
err = store.ApplySchema(setupCtx)
store.Close()
if err != nil {
return errors.New("could not apply the embedded checker schema for the browser fixture")
}
artifactDir, err = filepath.Abs(artifactDir)
if err != nil {
return errors.New("could not resolve the browser artifact directory")
}
ctx, stop := context.WithTimeout(ctx, 3*time.Minute)
var processes []*process
defer func() {
stop()
for _, proc := range processes {
<-proc.done
}
}()
apiAddr, err := freeAddress()
if err != nil {
return err
}
const username = "gateway-ui-admin"
password := testSecret()
api := exec.CommandContext(ctx, apiBin)
api.Env = append(fixtureEnv(), "DB_DSN="+scopedDSN, "LISTEN_ADDR="+apiAddr,
"ADMIN_USER="+username, "ADMIN_PASSWORD="+password, "SESSION_SECRET="+testSecret(),
"LOG_LEVEL=error", "CORS_ORIGIN=")
apiProc, err := start(api, syscall.SIGKILL)
if err != nil {
return fmt.Errorf("start admin API: %w", err)
}
processes = append(processes, apiProc)
if err := waitHTTP(ctx, apiProc, "admin API", "http://"+apiAddr+"/healthz", http.StatusOK); err != nil {
return err
}
uiAddr, err := freeAddress()
if err != nil {
return err
}
uiURL := "http://" + uiAddr
port := strings.TrimPrefix(uiAddr, "127.0.0.1:")
vite := exec.CommandContext(ctx, "node", "node_modules/vite/bin/vite.js", "--host", "127.0.0.1", "--port", port, "--strictPort")
vite.Dir = "frontend"
vite.Env = append(fixtureEnv(), "VITE_API_TARGET=http://"+apiAddr)
viteProc, err := start(vite, syscall.SIGKILL)
if err != nil {
return fmt.Errorf("start Vite: %w", err)
}
processes = append(processes, viteProc)
if err := waitHTTP(ctx, viteProc, "Vite with admin API proxy", uiURL+"/api/v1/auth/me", http.StatusUnauthorized); err != nil {
return err
}
suite := exec.CommandContext(ctx, "npm", "run", "test:gateway-ui")
suite.Dir = "frontend"
suite.Stdout, suite.Stderr = os.Stdout, os.Stderr
suite.Env = append(fixtureEnv(), "GATEWAY_UI_BASE_URL="+uiURL,
"GATEWAY_UI_USERNAME="+username, "GATEWAY_UI_PASSWORD="+password,
"GATEWAY_UI_ARTIFACTS_DIR="+artifactDir, "GATEWAY_API_TOKEN="+testSecret(), "GATEWAY_NODE_SECRET="+testSecret())
// Give Playwright time to close Chromium, which may use a separate process group.
suite.WaitDelay = 5 * time.Second
tests, err := start(suite, syscall.SIGTERM)
if err != nil {
return fmt.Errorf("start browser suite: %w", err)
}
processes = append(processes, tests)
select {
case <-apiProc.done:
return errors.New("admin API exited while browser tests were running")
case <-viteProc.done:
return errors.New("Vite exited while browser tests were running")
case <-ctx.Done():
return fmt.Errorf("browser suite: %w", ctx.Err())
case <-tests.done:
if tests.err != nil {
return fmt.Errorf("browser suite: %w", tests.err)
}
return nil
}
}
func fixtureEnv() []string {
env := os.Environ()
clean := env[:0]
for _, pair := range env {
key, _, _ := strings.Cut(pair, "=")
switch key {
case "TEST_DATABASE_URL", "DB_DSN", "ADMIN_USER", "ADMIN_PASSWORD", "SESSION_SECRET":
continue
}
if !strings.HasPrefix(key, "GATEWAY_") {
clean = append(clean, pair)
}
}
return clean
}
func withSchema(dsn, schema string) (string, error) {
if strings.HasPrefix(dsn, "postgresql://") || strings.HasPrefix(dsn, "postgres://") {
uri, err := url.Parse(dsn)
if err != nil {
return "", errors.New("invalid TEST_DATABASE_URL")
}
q := uri.Query()
q.Set("search_path", schema)
uri.RawQuery = q.Encode()
return uri.String(), nil
}
return dsn + " search_path=" + schema, nil
}
func testSecret() string {
var b [32]byte
rand.Read(b[:])
return base64.RawURLEncoding.EncodeToString(b[:])
}
func freeAddress() (string, error) {
ln, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
return "", fmt.Errorf("reserve a loopback fixture port: %w", err)
}
addr := ln.Addr().String()
return addr, ln.Close()
}
// A process group covers npm/Playwright and Vite/esbuild descendants too.
type process struct {
done chan struct{}
err error
}
func start(cmd *exec.Cmd, stopSignal syscall.Signal) (*process, error) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
err := syscall.Kill(-cmd.Process.Pid, stopSignal)
if errors.Is(err, syscall.ESRCH) {
return os.ErrProcessDone
}
return err
}
if err := cmd.Start(); err != nil {
return nil, err
}
proc := &process{done: make(chan struct{})}
go func() {
proc.err = cmd.Wait()
close(proc.done)
}()
return proc, nil
}
func waitHTTP(ctx context.Context, proc *process, name, address string, expected int) error {
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
transport := &http.Transport{}
defer transport.CloseIdleConnections()
client := &http.Client{Transport: transport, Timeout: 500 * time.Millisecond}
tick := time.NewTicker(50 * time.Millisecond)
defer tick.Stop()
for {
select {
case <-proc.done:
return fmt.Errorf("%s exited before readiness", name)
case <-ctx.Done():
return fmt.Errorf("%s did not reach readiness: %w", name, ctx.Err())
case <-tick.C:
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil)
if err != nil {
return fmt.Errorf("build %s readiness request: %w", name, err)
}
if resp, err := client.Do(req); err == nil {
_ = resp.Body.Close()
if resp.StatusCode == expected {
return nil
}
}
}
}
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env bash
# Run the mandatory gateway contract on native Linux/WSL. TEST_DATABASE_URL,
# when supplied, must point to a disposable PostgreSQL 16 database with a role
# allowed to create databases, schemas and roles. Never set it to production.
set +x
set -euo pipefail
umask 077
cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.."
fail() { printf 'gateway-contract: %s\n' "$*" >&2; exit 1; }
for cmd in go node npm cc grep tee; do
command -v "$cmd" >/dev/null || fail "$cmd is required"
done
[[ $(uname -s) == Linux ]] || fail 'use native Linux or WSL'
[[ $(node -p 'process.versions.node.split(".")[0]') == 22 ]] || fail 'Node.js 22 is required'
scratch=$(mktemp -d)
pg_dir=
xray_staged=
pg_started=0
pg_run=()
cleanup() {
local status=$?
trap - EXIT
if (( pg_started )) && "${pg_run[@]}" "$pg_bin/pg_ctl" -D "$pg_dir/data" status >/dev/null 2>&1; then
if ! "${pg_run[@]}" "$pg_bin/pg_ctl" -D "$pg_dir/data" -m immediate -w -t 10 stop >/dev/null 2>&1; then
printf 'gateway-contract: could not stop temporary PostgreSQL; kept %s\n' "$pg_dir" >&2
pg_dir=
status=1
fi
fi
[[ -z $pg_dir ]] || rm -rf -- "$pg_dir" || status=1
[[ -z $xray_staged ]] || rm -f -- "$xray_staged" || status=1
rm -rf -- "$scratch" || status=1
exit "$status"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
if [[ -z ${TEST_DATABASE_URL:-} ]]; then
pg_bin=${PG_BIN:-}
if [[ -z $pg_bin ]]; then
if command -v initdb >/dev/null; then
pg_bin=$(dirname -- "$(command -v initdb)")
elif [[ -x /usr/lib/postgresql/16/bin/initdb ]]; then
pg_bin=/usr/lib/postgresql/16/bin
elif command -v pg_config >/dev/null; then
pg_bin=$(pg_config --bindir)
else
fail 'install PostgreSQL 16 or set PG_BIN to its bin directory'
fi
fi
[[ -x $pg_bin/initdb && -x $pg_bin/pg_ctl ]] || fail 'cannot find initdb and pg_ctl (see PG_BIN)'
[[ $("$pg_bin/initdb" --version) == 'initdb (PostgreSQL) 16.'* ]] || fail 'PostgreSQL 16 initdb is required'
pg_dir=$(mktemp -d /tmp/gateway-pg.XXXXXXXX)
if (( EUID == 0 )); then
command -v runuser >/dev/null && id postgres >/dev/null 2>&1 || fail 'root needs the local postgres user and runuser'
chown postgres -- "$pg_dir"
pg_run=(runuser -u postgres --)
fi
printf 'Starting temporary PostgreSQL 16 (private Unix socket)\n'
"${pg_run[@]}" "$pg_bin/initdb" -D "$pg_dir/data" --auth=trust --no-locale --encoding=UTF8 --username=gateway_ci >/dev/null
pg_started=1
"${pg_run[@]}" "$pg_bin/pg_ctl" -D "$pg_dir/data" -l "$pg_dir/postgres.log" \
-o "-p 5432 -c listen_addresses='' -c unix_socket_directories=$pg_dir -c unix_socket_permissions=0700" \
-w -t 20 start || fail 'temporary PostgreSQL did not start'
export TEST_DATABASE_URL="postgresql:///postgres?host=$pg_dir&port=5432&user=gateway_ci&sslmode=disable"
fi
export TEST_DATABASE_URL
go build -o "$scratch/setup" ./tests/gateway
"$scratch/setup" check-db
xray_version=25.3.6
xray_revision=2cba2c4d59e48a04aa5d09b8e4c2b2d26f8608a4
pinned_cached_xray() {
[[ -x $1 ]] && go version -m "$1" | grep -E "^[[:space:]]*build[[:space:]]+vcs.revision=$xray_revision$" >/dev/null
}
if [[ -z ${XRAY_BIN:-} ]]; then
cache_dir=${GATEWAY_XRAY_CACHE_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/gateway-contract/xray}
mkdir -p -- "$cache_dir"
XRAY_BIN="$cache_dir/xray-$xray_revision-$(go env GOOS)-$(go env GOARCH)"
if ! pinned_cached_xray "$XRAY_BIN"; then
command -v git >/dev/null || fail 'git is required to build the reference Xray'
printf 'Building pinned reference Xray %s\n' "$xray_version"
git init --quiet "$scratch/xray"
git -C "$scratch/xray" fetch --quiet --depth=1 https://github.com/XTLS/Xray-core.git "refs/tags/v$xray_version"
[[ $(git -C "$scratch/xray" rev-parse 'FETCH_HEAD^{commit}') == "$xray_revision" ]] || fail 'Xray tag does not match the pinned commit'
git -C "$scratch/xray" checkout --quiet --detach FETCH_HEAD
(cd -- "$scratch/xray"; GOWORK=off go build -buildvcs=true -o "$scratch/xray-bin" ./main)
pinned_cached_xray "$scratch/xray-bin" || fail 'reference Xray build does not carry the pinned revision'
xray_staged=$(mktemp "$cache_dir/.xray.XXXXXXXX")
install -m 700 -- "$scratch/xray-bin" "$xray_staged"
mv -f -- "$xray_staged" "$XRAY_BIN"
xray_staged=
fi
fi
XRAY_BIN=$(command -v -- "$XRAY_BIN") || fail 'XRAY_BIN is not executable'
XRAY_BIN=$(realpath -- "$XRAY_BIN")
xray_banner=$("$XRAY_BIN" version) || fail 'XRAY_BIN version failed'
[[ $xray_banner == "Xray $xray_version "* ]] || fail "XRAY_BIN must report Xray $xray_version"
export XRAY_BIN
printf 'Building the production gateway and test admin API\n'
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o "$scratch/http-gateway" ./cmd/http-gateway
go build -o "$scratch/admin-api" ./cmd/api
# The product advisory lock is database-wide, not schema-wide. Keep the DB
# contract suite and tagged E2E suite in separate, sequential invocations.
printf 'Running gateway and caller race tests\n'
go test -race -count=1 -timeout=3m -skip '^TestRealityVisionXray$' \
./cmd/http-gateway ./cmd/checker ./cmd/api ./internal/gateway ./internal/db ./internal/config ./internal/api \
./internal/netpolicy ./internal/checker ./internal/dialer/... ./internal/worker
printf 'Running reference-peer gateway and REALITY acceptance tests\n'
go test -race -tags=gateway_e2e -run '^(TestGatewayE2E|TestRealityVisionXray$)' -count=1 -timeout=3m -v \
./internal/gateway ./internal/dialer/vless | tee "$scratch/e2e.log"
for test in TestGatewayE2EFullChain TestGatewayE2EWire TestRealityVisionXray; do
grep -F -- "--- PASS: $test (" "$scratch/e2e.log" >/dev/null || fail "$test did not run successfully"
done
printf 'Building the frontend and preparing Chromium\n'
(
cd frontend
npm ci
npm run build
chromium_args=()
[[ ${GATEWAY_INSTALL_BROWSER_DEPS:-} != 1 ]] || chromium_args+=(--with-deps)
./node_modules/.bin/playwright install "${chromium_args[@]}" chromium
)
printf 'Running authenticated browser tests against the real admin API\n'
"$scratch/setup" browser "$scratch/admin-api" "${GATEWAY_UI_ARTIFACTS_DIR:-$scratch/browser}"