Add authenticated SOCKS5 exports and a live public web switch
CI / validate (push) Successful in 38s
CI / gateway-contract (push) Successful in 2m1s
CI / images (deploy/Dockerfile.web, web) (push) Successful in 50s
CI / images (deploy/Dockerfile.checker, checker) (push) Successful in 1m4s
CI / images (deploy/Dockerfile.api, api) (push) Successful in 1m14s
CI / images (deploy/Dockerfile.http-gateway, http-gateway) (push) Successful in 1m11s
CI / validate (push) Successful in 38s
CI / gateway-contract (push) Successful in 2m1s
CI / images (deploy/Dockerfile.web, web) (push) Successful in 50s
CI / images (deploy/Dockerfile.checker, checker) (push) Successful in 1m4s
CI / images (deploy/Dockerfile.api, api) (push) Successful in 1m14s
CI / images (deploy/Dockerfile.http-gateway, http-gateway) (push) Successful in 1m11s
Use the same pinned upstream, node credentials and routing restrictions for both proxy listeners. Apply the admin-selected destination policy on each new request and verify exports with independent proxy clients.
This commit is contained in:
1 parent
e67c4e4e1d
commit
4499a6ee37
41 files changed
+1760
-273
No files matched your search
+7
-4
@@ -25,17 +25,20 @@ WEB_PORT=8088
|
||||
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.
|
||||
# Published and advertised SOCKS5 port; the container always listens on 1080.
|
||||
GATEWAY_SOCKS_PORT=1080
|
||||
# HTTP proxy address clients can reach; SOCKS5 exports reuse its host.
|
||||
# For example, 127.0.0.1:8081 or a private VPN name:port.
|
||||
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.
|
||||
# Fixed HTTPS control 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
|
||||
# Comma-separated exact DNS names and TCP ports, including the probe authority.
|
||||
# Set "Allow all public websites" in admin Settings, not in the environment.
|
||||
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.
|
||||
|
||||
+15
-4
@@ -14,7 +14,7 @@ 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 |
|
||||
| `http-gateway` | Go (`cmd/http-gateway`), optional `gateway` profile | Private HTTP/CONNECT on 8081 and SOCKS5 on 1080; authenticated catalog and status API on 8082 |
|
||||
|
||||
Single Go module (`git.eeee.moe/omar/zhguchiy_perchik`) with three binaries
|
||||
sharing `internal/` packages (dialers, upstream parser + canonicalization,
|
||||
@@ -44,8 +44,8 @@ subscription conversion and API are new.
|
||||
- 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`.
|
||||
`gateway_candidates`. The monitor uses the HTTP proxy listener to check a fixed
|
||||
HTTPS control 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
|
||||
@@ -53,6 +53,16 @@ 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.
|
||||
|
||||
The catalog selects HTTP (default) or SOCKS5 via `proxy_type`, without changing
|
||||
which nodes are ready or their credentials. SOCKS5 uses `socks5h://` export
|
||||
links and requires username/password authentication for TCP CONNECT only;
|
||||
there is no no-auth mode, BIND, or UDP ASSOCIATE.
|
||||
|
||||
The destination allowlist remains active in both modes. The persisted
|
||||
`gateway_allow_all_sites` setting adds public HTTP on port 80, HTTP CONNECT on
|
||||
port 443, and SOCKS5 CONNECT on either port. Address checks, peer enrollment,
|
||||
and the fixed control probe are unchanged.
|
||||
|
||||
## Validity criterion (all gates)
|
||||
|
||||
1. Successful protocol handshake + exit IP obtained within timeout.
|
||||
@@ -127,7 +137,8 @@ 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,
|
||||
gateway_check_interval_minutes(20, integer 15 through 30).
|
||||
gateway_check_interval_minutes(20, integer 15 through 30),
|
||||
gateway_allow_all_sites(false, boolean).
|
||||
Exit-IP echo URL is hardcoded with fallbacks (not a setting).
|
||||
|
||||
## Deploy
|
||||
|
||||
@@ -16,7 +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 |
|
||||
| `http-gateway` | Go (`cmd/http-gateway`), optional `gateway` profile | Private HTTP/CONNECT and SOCKS5 proxies with a 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,
|
||||
@@ -60,13 +60,17 @@ 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 optional `gateway` Compose profile publishes three separate private ports:
|
||||
|
||||
- **8081** for plain HTTP and HTTPS through HTTP CONNECT.
|
||||
- **8082** for the catalog and status API.
|
||||
- **1080** for authenticated SOCKS5 TCP CONNECT.
|
||||
|
||||
All three bind to host loopback by default. For remote clients, bind them to
|
||||
the host's private VPN interface and restrict ingress to authorized VPN
|
||||
clients with the host firewall. Never bind to a wildcard or expose any port
|
||||
on the WAN: client credentials are cleartext on the hop to the gateway.
|
||||
Public nginx does not route any of these ports.
|
||||
The normal stack does not require any `GATEWAY_*` variables.
|
||||
|
||||
### Provisioning
|
||||
@@ -81,16 +85,17 @@ The normal stack does not require any `GATEWAY_*` variables.
|
||||
IPv6 `/64` or narrower. Prefer individual `/32` or `/128` addresses. These
|
||||
limits apply to the actual TCP peer, not the exit IP or destination. Do not
|
||||
add external proxy pools or unrelated addresses to those networks.
|
||||
2. **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.
|
||||
2. **Configure the destination allowlist and probe.** Set
|
||||
`GATEWAY_ALLOWED_DESTINATIONS` to exact comma-separated DNS names with ports,
|
||||
for example `origin.example:80,origin.example:443,probe.example:443`. Include
|
||||
the probe authority in the list even if it uses a port other than 443.
|
||||
`GATEWAY_PROBE_URL` is the only direct control destination: a fixed HTTPS URL
|
||||
without credentials, query, or fragment. Keep the configured Cloudflare
|
||||
probe when changing the destination policy. The endpoint must return exactly
|
||||
`204` without a redirect, have a trusted TLS certificate, and be reachable
|
||||
directly from the gateway and through each enrolled peer. HTTP CONNECT and
|
||||
SOCKS5 CONNECT restrict the TCP destination, not URL paths inside TLS; the
|
||||
gateway does not decrypt the connection.
|
||||
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
|
||||
@@ -122,9 +127,10 @@ The normal stack does not require any `GATEWAY_*` variables.
|
||||
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).
|
||||
or `[fd12:3456::9]:8081` on a private VPN. HTTP exports use this address;
|
||||
SOCKS5 exports use its host with `GATEWAY_SOCKS_PORT` (default `1080`).
|
||||
`GATEWAY_BIND_IP`, `GATEWAY_PROXY_PORT`, `GATEWAY_API_PORT`, and
|
||||
`GATEWAY_SOCKS_PORT` control host publication (bracket an IPv6 bind IP).
|
||||
Generate two independent
|
||||
32-byte random base64url strings without padding for `GATEWAY_API_TOKEN`
|
||||
and `GATEWAY_NODE_SECRET`:
|
||||
@@ -155,22 +161,31 @@ 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.
|
||||
8081, 8082, and 1080 on all interfaces; the Compose host bind settings do not
|
||||
change these sockets. Keep the host private and restrict all three ports at
|
||||
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.
|
||||
not `HEAD`): `/healthz` means the process can answer; `/readyz` means the HTTP,
|
||||
SOCKS5, and API listeners, DB/schema and the single-instance advisory lock are usable.
|
||||
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.
|
||||
checker. Periodic availability and latency checks still use the HTTP proxy
|
||||
listener, not SOCKS5. Country and speed remain in the last completed checker
|
||||
snapshot. Removed nodes are unavailable immediately for new connections and
|
||||
requests; successful gateway checks expire after twice the effective interval.
|
||||
|
||||
In **Settings → HTTP gateway**, **Allow all public websites** is off by default:
|
||||
only the configured allowlist is permitted. Turning it on also allows public
|
||||
DNS names and public IP literals via HTTP on port 80, HTTP CONNECT on port
|
||||
443, or SOCKS5 CONNECT on either port. All DNS answers and IP literals still
|
||||
pass the same public-address and
|
||||
local-interface checks; the exact allowlist, upstream enrollment, and proxy
|
||||
authentication stay in effect. The switch is saved in the database as
|
||||
`gateway_allow_all_sites`; no environment variable enables or overrides it.
|
||||
|
||||
### Catalog and proxy clients
|
||||
|
||||
@@ -185,6 +200,7 @@ format:
|
||||
| `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. |
|
||||
| `proxy_type` | `http` (default) or `socks5`; selects the client-facing proxy address and URL scheme, not the upstream protocol. |
|
||||
| `format` | `json` (default), `csv`, `txt`, or `proxy-url-list-txt`. |
|
||||
|
||||
Both `country` and `protocol` support comma-separated or repeated values (OR
|
||||
@@ -194,13 +210,18 @@ 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.
|
||||
`proxy-url-list-txt` emits `http://` or `socks5h://` gateway links, not upstream
|
||||
provider links. SOCKS5 uses the same node username and password as HTTP. It
|
||||
requires username/password authentication and supports only TCP CONNECT, not
|
||||
no-auth mode, UDP ASSOCIATE, or BIND. The `socks5h://` scheme makes the client
|
||||
send the destination hostname to the gateway for resolution.
|
||||
|
||||
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:
|
||||
with a line `proxy = "<exported proxy URL>"` for a selected node. Add
|
||||
`proxy_type=socks5` to the catalog query to use the SOCKS5 listener with the same
|
||||
credentials:
|
||||
|
||||
```sh
|
||||
umask 077
|
||||
@@ -222,8 +243,8 @@ 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),
|
||||
18081/18082/11080), adjust the advertised HTTP 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;
|
||||
@@ -236,10 +257,11 @@ 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
|
||||
Verify all three listeners and each of SS, Trojan, VMess and VLESS with a
|
||||
dedicated authorized peer. On each route, compare all four filtered export
|
||||
formats, use an exported credential for HTTP and HTTPS via each client-facing
|
||||
proxy type, 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
|
||||
|
||||
@@ -41,7 +41,7 @@ func run(ctx context.Context) error {
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
// Run binds both listeners and waits for the checker schema and lease.
|
||||
// Run binds all listeners and waits for the checker schema and lease.
|
||||
return gateway.Run(ctx, store, cfg, gateway.RuntimeOptions{
|
||||
Build: func(_ context.Context, endpoints gateway.RuntimeEndpoints) (gateway.RuntimeComponents, error) {
|
||||
return gateway.NewRuntimeComponents(store, cfg, endpoints)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Private HTTP gateway. Build context is the repo root.
|
||||
# Private HTTP and SOCKS5 gateway. Build context is the repo root.
|
||||
FROM golang:1.26 AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
@@ -10,5 +10,5 @@ RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/http-ga
|
||||
FROM gcr.io/distroless/static-debian12:nonroot
|
||||
COPY --from=build /out/http-gateway /http-gateway
|
||||
USER nonroot:nonroot
|
||||
EXPOSE 8081 8082
|
||||
EXPOSE 8081 8082 1080
|
||||
ENTRYPOINT ["/http-gateway"]
|
||||
@@ -71,9 +71,11 @@ services:
|
||||
GATEWAY_PROBE_URL: ${GATEWAY_PROBE_URL:-}
|
||||
GATEWAY_ALLOWED_DESTINATIONS: ${GATEWAY_ALLOWED_DESTINATIONS:-}
|
||||
GATEWAY_UPSTREAM_NETWORKS: ${GATEWAY_UPSTREAM_NETWORKS:-}
|
||||
GATEWAY_SOCKS_PORT: ${GATEWAY_SOCKS_PORT:-1080}
|
||||
ports:
|
||||
- "${GATEWAY_BIND_IP:-127.0.0.1}:${GATEWAY_PROXY_PORT:-8081}:8081"
|
||||
- "${GATEWAY_BIND_IP:-127.0.0.1}:${GATEWAY_API_PORT:-8082}:8082"
|
||||
- "${GATEWAY_BIND_IP:-127.0.0.1}:${GATEWAY_SOCKS_PORT:-1080}:1080"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
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 { Badge, Button, Input, Label, Toggle } 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 allowAllSitesKey = "gateway_allow_all_sites";
|
||||
const allowAllSitesLabel = "Allow all public websites";
|
||||
const settingsQueryKey = ["settings"];
|
||||
const statusQueryKey = ["gateway-status"];
|
||||
const intervalError = "Enter a whole number from 15 to 30.";
|
||||
@@ -19,15 +21,15 @@ const gatewayStates = {
|
||||
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;
|
||||
function selectGatewaySettings(settings: Settings) {
|
||||
return { interval: settings[intervalKey], allowAllSites: settings[allowAllSitesKey] };
|
||||
}
|
||||
|
||||
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 settings = useQuery({ queryKey: settingsQueryKey, queryFn: api.settings, select: selectGatewaySettings });
|
||||
const status = useQuery({
|
||||
queryKey: statusQueryKey,
|
||||
queryFn: ({ signal }) => api.gatewayStatus(signal),
|
||||
@@ -44,7 +46,7 @@ export default function GatewaySettings() {
|
||||
: { 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 interval = draft ?? settings.data?.interval ?? current?.interval_minutes?.toString() ?? "";
|
||||
const waitingForInterval = settings.isLoading && !interval;
|
||||
const save = useMutation({
|
||||
mutationFn: (value: string) => api.updateSettings({ [intervalKey]: value }),
|
||||
@@ -56,6 +58,19 @@ export default function GatewaySettings() {
|
||||
void qc.invalidateQueries({ queryKey: statusQueryKey });
|
||||
},
|
||||
});
|
||||
const allowAllSites = settings.data?.allowAllSites;
|
||||
const policyAvailable = allowAllSites === "true" || allowAllSites === "false";
|
||||
const savePolicy = useMutation({
|
||||
mutationFn: (enabled: boolean) => api.updateSettings({ [allowAllSitesKey]: enabled ? "true" : "false" }),
|
||||
onSuccess: async (_, enabled) => {
|
||||
await qc.cancelQueries({ queryKey: settingsQueryKey });
|
||||
qc.setQueryData<Settings>(settingsQueryKey, (previous) => ({
|
||||
...previous,
|
||||
[allowAllSitesKey]: enabled ? "true" : "false",
|
||||
}));
|
||||
void qc.invalidateQueries({ queryKey: settingsQueryKey });
|
||||
},
|
||||
});
|
||||
|
||||
function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
@@ -134,6 +149,28 @@ export default function GatewaySettings() {
|
||||
{save.isSuccess ? "Interval saved." : save.isPending ? "Saving interval..." : waitingForInterval ? "Loading saved interval..." : null}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<fieldset
|
||||
aria-label="Gateway destination policy"
|
||||
aria-describedby={`${id}-destination-policy`}
|
||||
disabled={!policyAvailable || savePolicy.isPending}
|
||||
className="mt-4 min-w-0 border-t border-ink-700 pt-4 disabled:[&_button]:opacity-50"
|
||||
>
|
||||
<label className="flex min-h-11 w-fit items-center gap-3 text-sm font-medium sm:min-h-9">
|
||||
<Toggle checked={allowAllSites === "true"} onChange={savePolicy.mutate} label={allowAllSitesLabel} />
|
||||
{allowAllSitesLabel}
|
||||
</label>
|
||||
<p id={`${id}-destination-policy`} className="text-sm text-fog-muted">
|
||||
Off: Only configured allowlist entries. On: Also allows public sites via HTTP on port 80, HTTP CONNECT on port 443,
|
||||
or SOCKS5 on either port.
|
||||
</p>
|
||||
<div role="status" className="text-sm text-fog-muted [&:not(:empty)]:mt-2">
|
||||
{savePolicy.isError ? <span className="text-rose">Could not save the gateway destination policy. Try again.</span>
|
||||
: savePolicy.isPending ? "Saving destination policy..."
|
||||
: savePolicy.isSuccess ? "Destination policy saved."
|
||||
: !policyAvailable ? settings.isLoading ? "Loading destination policy..." : "Destination policy unavailable." : null}
|
||||
</div>
|
||||
</fieldset>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -187,6 +187,7 @@ const KEYS = {
|
||||
tgFinish: "telegram_notify_finish",
|
||||
};
|
||||
|
||||
// Do not let the checker form submit stale values for independently saved gateway settings.
|
||||
function selectCheckSettings(settings: SettingsMap): SettingsMap {
|
||||
const checkSettings: SettingsMap = {};
|
||||
for (const key of Object.values(KEYS)) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { devices, expect, test, type APIRequestContext, type Page, type Response
|
||||
const settingsPath = "/api/v1/settings";
|
||||
const statusPath = "/api/v1/gateway/status";
|
||||
const intervalKey = "gateway_check_interval_minutes";
|
||||
const allowAllSitesKey = "gateway_allow_all_sites";
|
||||
const speedURLKey = "speedtest_url";
|
||||
|
||||
const checkingStatus = {
|
||||
@@ -127,6 +128,46 @@ test("requires operator auth and saves 15 and 30 across actual reloads", async (
|
||||
}
|
||||
});
|
||||
|
||||
test("public websites switch persists both states without leaking into the checker save", async ({ page }) => {
|
||||
await signIn(page);
|
||||
const baseline = await readSettings(page.request);
|
||||
expect(baseline[allowAllSitesKey]).toMatch(/^(?:true|false)$/);
|
||||
const speedURL = "https://speed.example.test/gateway-policy";
|
||||
try {
|
||||
if (baseline[allowAllSitesKey] === "true") {
|
||||
await patchSettings(page.request, { [allowAllSitesKey]: "false" });
|
||||
}
|
||||
await page.goto("/settings");
|
||||
const policy = gateway(page).getByRole("switch", { name: "Allow all public websites", exact: true });
|
||||
const speed = page.getByPlaceholder(/__down\?bytes=10000000/);
|
||||
await expect(policy).toBeEnabled();
|
||||
await expect(policy).not.toBeChecked();
|
||||
await expect(speed).toHaveValue(baseline[speedURLKey]);
|
||||
await speed.fill(speedURL);
|
||||
|
||||
expect(await patchFromUI(page, () => policy.press("Space"))).toEqual({ [allowAllSitesKey]: "true" });
|
||||
await expect(policy).toBeChecked();
|
||||
await expect(speed).toHaveValue(speedURL);
|
||||
const checker = await patchFromUI(page, () => page.getByRole("button", { name: "Save settings", exact: true }).click());
|
||||
expect(Object.hasOwn(checker, allowAllSitesKey)).toBe(false);
|
||||
expect(checker[speedURLKey]).toBe(speedURL);
|
||||
expect((await readSettings(page.request))[allowAllSitesKey]).toBe("true");
|
||||
|
||||
await page.reload();
|
||||
await expect(policy).toBeChecked();
|
||||
expect(await patchFromUI(page, () => policy.click())).toEqual({ [allowAllSitesKey]: "false" });
|
||||
expect((await readSettings(page.request))[allowAllSitesKey]).toBe("false");
|
||||
await page.reload();
|
||||
await expect(policy).toBeEnabled();
|
||||
await expect(policy).not.toBeChecked();
|
||||
} finally {
|
||||
await patchSettings(page.request, {
|
||||
[allowAllSitesKey]: baseline[allowAllSitesKey],
|
||||
[speedURLKey]: baseline[speedURLKey],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
@@ -26,6 +26,7 @@ func TestGatewaySettingsREST(t *testing.T) {
|
||||
cookie := &http.Cookie{Name: sessionCookie, Value: s.signToken(time.Now().Add(time.Hour))}
|
||||
const path = "/api/v1/settings"
|
||||
const key = config.KeyGatewayCheckIntervalMinutes
|
||||
const allowAllKey = config.KeyGatewayAllowAllSites
|
||||
|
||||
request := func(t *testing.T, method, body string, authenticated bool, want int) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
@@ -55,10 +56,14 @@ func TestGatewaySettingsREST(t *testing.T) {
|
||||
|
||||
request(t, http.MethodGet, "", false, http.StatusUnauthorized)
|
||||
request(t, http.MethodPatch, `{"gateway_check_interval_minutes":"15"}`, false, http.StatusUnauthorized)
|
||||
request(t, http.MethodPatch, `{"gateway_allow_all_sites":"true"}`, 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")
|
||||
}
|
||||
if initial[allowAllKey] != "false" {
|
||||
t.Fatal("the settings response did not include the disabled gateway policy default")
|
||||
}
|
||||
|
||||
for _, value := range []string{`"14"`, `"31"`, `"15.5"`, `"+20"`, `"020"`, `" 20"`, `""`, `15`, `null`, `"invalid-interval-marker"`} {
|
||||
t.Run("invalid="+value, func(t *testing.T) {
|
||||
@@ -83,9 +88,36 @@ func TestGatewaySettingsREST(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
for _, value := range []string{`"TRUE"`, `"False"`, `" true"`, `"false "`, `"1"`, `"t"`, `""`, `true`, `false`, `null`, `"invalid-policy-marker"`} {
|
||||
t.Run("invalidPolicy="+value, func(t *testing.T) {
|
||||
body := `{"gateway_allow_all_sites":` + value + `,"gateway_check_interval_minutes":"15","workers":"17"}`
|
||||
res := request(t, http.MethodPatch, body, true, http.StatusBadRequest)
|
||||
if strings.Contains(res.Body.String(), "invalid-policy-marker") {
|
||||
t.Fatal("validation response echoed an invalid setting value")
|
||||
}
|
||||
got := read(t)
|
||||
if got[allowAllKey] != "false" || got[key] != "30" || got[config.KeyWorkers] != initial[config.KeyWorkers] {
|
||||
t.Fatal("rejected gateway policy PATCH modified settings")
|
||||
}
|
||||
if stored, present, err := database.GetSetting(t.Context(), allowAllKey); err != nil || !present || stored != "false" {
|
||||
t.Fatal("rejected PATCH modified the persisted gateway policy")
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, value := range []string{"true", "false"} {
|
||||
body := `{"gateway_allow_all_sites":"` + value + `"}`
|
||||
request(t, http.MethodPatch, body, true, http.StatusOK)
|
||||
got := read(t)
|
||||
if got[allowAllKey] != value || got[key] != "30" || got[config.KeyWorkers] != initial[config.KeyWorkers] {
|
||||
t.Fatalf("could not save gateway policy %s independently of other settings", value)
|
||||
}
|
||||
}
|
||||
|
||||
const invalidStored = "invalid-stored-interval-marker"
|
||||
const invalidStoredPolicy = "invalid-stored-policy-marker"
|
||||
if err := database.SetSettings(t.Context(), map[string]string{
|
||||
key: invalidStored, "gateway_node_secret": "unused-secret-placeholder",
|
||||
key: invalidStored, allowAllKey: invalidStoredPolicy,
|
||||
"gateway_node_secret": "unused-secret-placeholder", "gateway_api_token": "unused-token-placeholder",
|
||||
}); err != nil {
|
||||
t.Fatal("could not seed malformed gateway settings")
|
||||
}
|
||||
@@ -94,19 +126,38 @@ func TestGatewaySettingsREST(t *testing.T) {
|
||||
if _, present := got[key]; present {
|
||||
t.Fatal("settings response exposed the malformed interval")
|
||||
}
|
||||
if got[allowAllKey] != "false" {
|
||||
t.Fatal("settings response did not fail closed on malformed gateway policy")
|
||||
}
|
||||
if _, present := got["gateway_node_secret"]; present {
|
||||
t.Fatal("settings response exposed a noneditable gateway credential")
|
||||
}
|
||||
if _, present := got["gateway_api_token"]; 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")
|
||||
}
|
||||
if stored, present, err := database.GetSetting(t.Context(), allowAllKey); err != nil || !present || stored != invalidStoredPolicy {
|
||||
t.Fatal("updating an unrelated setting changed the malformed gateway policy")
|
||||
}
|
||||
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")
|
||||
}
|
||||
request(t, http.MethodPatch, `{"gateway_allow_all_sites":"true"}`, true, http.StatusOK)
|
||||
if read(t)[allowAllKey] != "true" {
|
||||
t.Fatal("could not repair the malformed gateway policy using PATCH")
|
||||
}
|
||||
if _, err := database.Pool().Exec(t.Context(), `DELETE FROM settings WHERE key = $1`, allowAllKey); err != nil {
|
||||
t.Fatal("could not remove the gateway policy setting")
|
||||
}
|
||||
if read(t)[allowAllKey] != "false" {
|
||||
t.Fatal("missing gateway policy did not default to disabled")
|
||||
}
|
||||
}
|
||||
|
||||
func gatewaySettingsTestDB(t *testing.T) *db.DB {
|
||||
|
||||
@@ -24,6 +24,7 @@ var editableKeys = map[string]struct{}{
|
||||
config.KeyTelegramNotifyFinish: {},
|
||||
|
||||
config.KeyGatewayCheckIntervalMinutes: {},
|
||||
config.KeyGatewayAllowAllSites: {},
|
||||
}
|
||||
|
||||
func (s *Server) handleGetSettings(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -33,13 +34,19 @@ func (s *Server) handleGetSettings(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
out := make(map[string]string, len(editableKeys))
|
||||
out[config.KeyGatewayAllowAllSites] = "false"
|
||||
for k := range editableKeys {
|
||||
if v, ok := m[k]; ok {
|
||||
if k == config.KeyGatewayCheckIntervalMinutes {
|
||||
switch k {
|
||||
case config.KeyGatewayCheckIntervalMinutes:
|
||||
if _, err := config.ParseGatewayCheckIntervalMinutes(v); err != nil {
|
||||
// Do not expose a malformed stored value. Gateway status reports the config error.
|
||||
continue
|
||||
}
|
||||
case config.KeyGatewayAllowAllSites:
|
||||
if err := config.ValidateGatewayAllowAllSites(v); err != nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out[k] = v
|
||||
}
|
||||
@@ -59,6 +66,12 @@ func (s *Server) handleUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if allowAllSites, ok := req[config.KeyGatewayAllowAllSites]; ok {
|
||||
if err := config.ValidateGatewayAllowAllSites(allowAllSites); 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 {
|
||||
|
||||
@@ -44,6 +44,19 @@ func ParseGatewayCheckIntervalMinutes(v string) (int, error) {
|
||||
return 0, errGatewayCheckInterval
|
||||
}
|
||||
|
||||
// KeyGatewayAllowAllSites enables public web routing beyond the destination allowlist.
|
||||
const KeyGatewayAllowAllSites = "gateway_allow_all_sites"
|
||||
|
||||
var errGatewayAllowAllSites = errors.New("gateway_allow_all_sites must be true or false")
|
||||
|
||||
// ValidateGatewayAllowAllSites accepts only the canonical settings values.
|
||||
func ValidateGatewayAllowAllSites(v string) error {
|
||||
if v != "true" && v != "false" {
|
||||
return errGatewayAllowAllSites
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DefaultSpeedTestURL is the bounded HTTPS sample used for new installations.
|
||||
const DefaultSpeedTestURL = "https://speedtest.selectel.ru/10MB"
|
||||
|
||||
|
||||
@@ -31,9 +31,10 @@ type GatewayCandidate struct {
|
||||
|
||||
// GatewayNode identifies one upstream for dialing. It is not a catalog item.
|
||||
type GatewayNode struct {
|
||||
ProxyID int64
|
||||
MembershipID int64
|
||||
CanonicalURL string `json:"-"`
|
||||
ProxyID int64
|
||||
MembershipID int64
|
||||
CanonicalURL string `json:"-"`
|
||||
AllowAllSites bool
|
||||
}
|
||||
|
||||
type GatewayCatalogSort string
|
||||
@@ -232,14 +233,14 @@ func (d *DB) lookupGatewayNode(ctx context.Context, proxyID, probeMembershipID i
|
||||
}
|
||||
|
||||
var row pgx.Row
|
||||
const fields = `SELECT c.proxy_id, c.membership_id, c.canonical_url`
|
||||
const fields = `SELECT c.proxy_id, c.membership_id, c.canonical_url, c.allow_all_sites`
|
||||
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)
|
||||
err = row.Scan(&node.ProxyID, &node.MembershipID, &node.CanonicalURL, &node.AllowAllSites)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -409,6 +409,58 @@ func TestGatewayReadStatusAndDatabaseFailures(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayReadAllowAllSites(t *testing.T) {
|
||||
ctx, owner, gateway := newGatewayMonitorFixture(t)
|
||||
at := time.Date(2026, time.January, 3, 0, 0, 0, 0, time.UTC)
|
||||
session := gatewayReadSession(t, ctx, owner, "completed", true, at)
|
||||
id := gatewayReadProxy(t, ctx, owner, nil, "allow-all", "ss")
|
||||
membership := gatewayReadMembership(t, ctx, owner, session, id, "NL", "fixture", 5)
|
||||
latency := int64(1)
|
||||
gatewayReadHealth(t, ctx, owner, id, membership, at, &latency)
|
||||
const key = config.KeyGatewayAllowAllSites
|
||||
|
||||
assertNode := func(t *testing.T, node *GatewayNode, err error, want bool) {
|
||||
t.Helper()
|
||||
if err != nil || node == nil || node.ProxyID != id || node.MembershipID != membership || node.AllowAllSites != want {
|
||||
t.Fatalf("lookup did not return current node with public web mode %t: %v", want, err)
|
||||
}
|
||||
data, err := json.Marshal(node)
|
||||
if err != nil || strings.Contains(string(data), "provider-credential") {
|
||||
t.Fatal("encoding the lookup result did not preserve credential redaction")
|
||||
}
|
||||
}
|
||||
assertPolicy := func(t *testing.T, want bool) {
|
||||
t.Helper()
|
||||
node, err := gateway.LookupGatewayNode(ctx, id, at)
|
||||
assertNode(t, node, err, want)
|
||||
node, err = gateway.LookupGatewayProbeNode(ctx, id, membership)
|
||||
assertNode(t, node, err, want)
|
||||
}
|
||||
|
||||
assertPolicy(t, false)
|
||||
if stored, present, err := owner.GetSetting(ctx, key); err != nil || !present || stored != "false" {
|
||||
t.Fatal("schema did not seed the disabled gateway policy")
|
||||
}
|
||||
for _, value := range []string{"true", "false", "TRUE", " true", "true ", "1", "t", ""} {
|
||||
t.Run("stored="+value, func(t *testing.T) {
|
||||
if err := owner.SetSetting(ctx, key, value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertPolicy(t, value == "true")
|
||||
})
|
||||
}
|
||||
execGatewayReadFixture(t, ctx, owner, `DELETE FROM settings WHERE key = $1`, key)
|
||||
assertPolicy(t, false)
|
||||
if err := owner.SetSetting(ctx, key, "true"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Re-applying the schema must preserve the setting and existing reader grants.
|
||||
if err := owner.ApplySchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertPolicy(t, true)
|
||||
}
|
||||
|
||||
func TestGatewayReadCatalogSnapshotDuringPublication(t *testing.T) {
|
||||
d, ctx := newGatewayReadTestDB(t)
|
||||
at := time.Date(2026, time.January, 3, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
@@ -193,9 +193,11 @@ 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.
|
||||
-- only its runtime and health. The views expose no historical rows or unrelated settings.
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO settings (key, value) VALUES ('gateway_check_interval_minutes', '20')
|
||||
INSERT INTO settings (key, value) VALUES
|
||||
('gateway_check_interval_minutes', '20'),
|
||||
('gateway_allow_all_sites', 'false')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
CREATE OR REPLACE VIEW gateway_current_session WITH (security_barrier = true) AS
|
||||
@@ -206,7 +208,9 @@ 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
|
||||
sp.country, sp.exit_ip, sp.speed_mbps,
|
||||
COALESCE((SELECT value COLLATE "C" = 'true' FROM settings
|
||||
WHERE key = 'gateway_allow_all_sites'), false) AS allow_all_sites
|
||||
FROM check_sessions cs
|
||||
JOIN session_proxies sp ON sp.session_id = cs.id
|
||||
WHERE cs.is_current AND cs.status = 'completed';
|
||||
|
||||
@@ -57,9 +57,6 @@ func (c Credentials) nodePassword(id int64) (password [gatewaySecretEncodedLen]b
|
||||
// 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
|
||||
@@ -72,7 +69,14 @@ func (c Credentials) AuthenticateProxy(r *http.Request) (int64, bool) {
|
||||
return 0, false
|
||||
}
|
||||
user, password, ok := bytes.Cut(decoded[:n], []byte(":"))
|
||||
if !ok || len(password) != gatewaySecretEncodedLen || !bytes.HasPrefix(user, []byte(nodeUsernamePrefix)) {
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
return c.authenticateNode(user, password)
|
||||
}
|
||||
|
||||
func (c Credentials) authenticateNode(user, password []byte) (int64, bool) {
|
||||
if c.storePrefix == "" || len(password) != gatewaySecretEncodedLen || !bytes.HasPrefix(user, []byte(nodeUsernamePrefix)) {
|
||||
return 0, false
|
||||
}
|
||||
decimal := user[len(nodeUsernamePrefix):]
|
||||
|
||||
+36
-22
@@ -19,22 +19,32 @@ type catalogStore interface {
|
||||
}
|
||||
|
||||
type catalogHandler struct {
|
||||
store catalogStore
|
||||
creds Credentials
|
||||
host string
|
||||
store catalogStore
|
||||
creds Credentials
|
||||
host string
|
||||
httpEndpoint catalogEndpoint
|
||||
socksEndpoint catalogEndpoint
|
||||
}
|
||||
|
||||
type catalogEndpoint struct {
|
||||
port uint16
|
||||
authority string
|
||||
scheme string
|
||||
}
|
||||
|
||||
func newCatalogEndpoint(host string, port uint16, scheme string) catalogEndpoint {
|
||||
return catalogEndpoint{port: port, authority: net.JoinHostPort(host, strconv.Itoa(int(port))), scheme: scheme}
|
||||
}
|
||||
|
||||
// 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))),
|
||||
store: store,
|
||||
creds: creds,
|
||||
host: cfg.PublicProxyHost,
|
||||
httpEndpoint: newCatalogEndpoint(cfg.PublicProxyHost, cfg.PublicProxyPort, "http"),
|
||||
socksEndpoint: newCatalogEndpoint(cfg.PublicProxyHost, cfg.PublicSOCKSPort, "socks5h"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,18 +65,22 @@ func (h *catalogHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "gateway unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
endpoint := &h.httpEndpoint
|
||||
if q.proxyType == catalogProxySOCKS {
|
||||
endpoint = &h.socksEndpoint
|
||||
}
|
||||
switch q.format {
|
||||
case catalogJSON:
|
||||
h.writeJSON(w, out)
|
||||
h.writeJSON(w, out, endpoint)
|
||||
case catalogCSV:
|
||||
h.writeCSV(w, out)
|
||||
h.writeCSV(w, out, endpoint)
|
||||
case catalogTXT, catalogURLs:
|
||||
h.writeText(w, out.Items, q.format == catalogURLs)
|
||||
h.writeText(w, out.Items, endpoint, q.format == catalogURLs)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *catalogHandler) proxyURL(username, password string) string {
|
||||
u := url.URL{Scheme: "http", Host: h.authority, User: url.UserPassword(username, password)}
|
||||
func (e *catalogEndpoint) proxyURL(username, password string) string {
|
||||
u := url.URL{Scheme: e.scheme, Host: e.authority, User: url.UserPassword(username, password)}
|
||||
return u.String()
|
||||
}
|
||||
|
||||
@@ -94,7 +108,7 @@ type catalogJSONItem struct {
|
||||
CheckedAt time.Time `json:"checked_at"`
|
||||
}
|
||||
|
||||
func (h *catalogHandler) writeJSON(w http.ResponseWriter, out db.GatewayCatalogResult) {
|
||||
func (h *catalogHandler) writeJSON(w http.ResponseWriter, out db.GatewayCatalogResult, endpoint *catalogEndpoint) {
|
||||
meta := catalogJSONMetadata{SessionID: out.SessionID, AsOf: out.AsOf.UTC(), Total: out.Total}
|
||||
if out.SessionFinishedAt != nil {
|
||||
finished := out.SessionFinishedAt.UTC()
|
||||
@@ -121,8 +135,8 @@ func (h *catalogHandler) writeJSON(w http.ResponseWriter, out db.GatewayCatalogR
|
||||
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,
|
||||
ProxyID: id, Host: h.host, Port: endpoint.port, Username: username, Password: password,
|
||||
ProxyURL: endpoint.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.
|
||||
@@ -133,7 +147,7 @@ func (h *catalogHandler) writeJSON(w http.ResponseWriter, out db.GatewayCatalogR
|
||||
_ = buf.Flush()
|
||||
}
|
||||
|
||||
func (h *catalogHandler) writeCSV(w http.ResponseWriter, out db.GatewayCatalogResult) {
|
||||
func (h *catalogHandler) writeCSV(w http.ResponseWriter, out db.GatewayCatalogResult, endpoint *catalogEndpoint) {
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
writer := csv.NewWriter(w)
|
||||
if err := writer.Write([]string{
|
||||
@@ -146,7 +160,7 @@ func (h *catalogHandler) writeCSV(w http.ResponseWriter, out db.GatewayCatalogRe
|
||||
if out.SessionFinishedAt != nil {
|
||||
finished = out.SessionFinishedAt.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
port := strconv.Itoa(int(h.port))
|
||||
port := strconv.Itoa(int(endpoint.port))
|
||||
var record [13]string
|
||||
for i := range out.Items {
|
||||
item := &out.Items[i]
|
||||
@@ -156,7 +170,7 @@ func (h *catalogHandler) writeCSV(w http.ResponseWriter, out db.GatewayCatalogRe
|
||||
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),
|
||||
record = [13]string{id, h.host, port, username, password, endpoint.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 {
|
||||
@@ -166,7 +180,7 @@ func (h *catalogHandler) writeCSV(w http.ResponseWriter, out db.GatewayCatalogRe
|
||||
writer.Flush()
|
||||
}
|
||||
|
||||
func (h *catalogHandler) writeText(w http.ResponseWriter, items []db.GatewayCatalogItem, asURL bool) {
|
||||
func (h *catalogHandler) writeText(w http.ResponseWriter, items []db.GatewayCatalogItem, endpoint *catalogEndpoint, asURL bool) {
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
if len(items) == 0 {
|
||||
return
|
||||
@@ -176,9 +190,9 @@ func (h *catalogHandler) writeText(w http.ResponseWriter, items []db.GatewayCata
|
||||
id := items[i].ProxyID
|
||||
username, password := nodeUsernamePrefix+strconv.FormatInt(id, 10), h.creds.Password(id)
|
||||
if asURL {
|
||||
_, _ = buf.WriteString(h.proxyURL(username, password))
|
||||
_, _ = buf.WriteString(endpoint.proxyURL(username, password))
|
||||
} else {
|
||||
_, _ = buf.WriteString(h.authority)
|
||||
_, _ = buf.WriteString(endpoint.authority)
|
||||
_ = buf.WriteByte(':')
|
||||
_, _ = buf.WriteString(username)
|
||||
_ = buf.WriteByte(':')
|
||||
|
||||
@@ -35,6 +35,7 @@ func catalogTestConfig(host string) Config {
|
||||
return Config{
|
||||
PublicProxyHost: host,
|
||||
PublicProxyPort: 18081,
|
||||
PublicSOCKSPort: 11080,
|
||||
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",
|
||||
@@ -122,29 +123,33 @@ func TestGatewayCatalogExports(t *testing.T) {
|
||||
}
|
||||
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)
|
||||
for _, host := range []string{"127.0.0.1", "gateway.test", "2001:db8::42"} {
|
||||
t.Run(host, func(t *testing.T) {
|
||||
cfg := catalogTestConfig(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")
|
||||
}
|
||||
})
|
||||
for _, proxy := range []struct {
|
||||
name, query, scheme, port string
|
||||
}{
|
||||
{"default", "", "http", "18081"},
|
||||
{"http", "&proxy_type=http", "http", "18081"},
|
||||
{"socks5", "&proxy_type=socks5", "socks5h", "11080"},
|
||||
} {
|
||||
for _, format := range catalogTestFormats {
|
||||
t.Run(proxy.name+"/"+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+proxy.query, cfg.APIToken)
|
||||
assertCatalogResponse(t, w, http.StatusOK, format.contentType)
|
||||
assertCatalogPrivateFieldsAbsent(t, w, cfg)
|
||||
switch format.name {
|
||||
case "json":
|
||||
assertCatalogJSON(t, w.Body, cfg, proxy.scheme, proxy.port)
|
||||
case "csv":
|
||||
assertCatalogCSV(t, w.Body.Bytes(), cfg, proxy.scheme, proxy.port)
|
||||
default:
|
||||
assertCatalogText(t, w.Body.String(), cfg, proxy.scheme, proxy.port, format.name == "proxy-url-list-txt")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -156,11 +161,11 @@ func catalogExpectedPassword(cfg Config, id string) string {
|
||||
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
func assertCatalogProxyURL(t *testing.T, rawURL, authority, username, password string) {
|
||||
func assertCatalogProxyURL(t *testing.T, rawURL, scheme, 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")
|
||||
if err != nil || u.Scheme != scheme || u.Host != authority || u.Path != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" || u.User == nil {
|
||||
t.Fatalf("catalog did not return a parsed %s gateway URL for the configured authority", scheme)
|
||||
}
|
||||
gotPassword, ok := u.User.Password()
|
||||
if !ok || u.User.Username() != username || gotPassword != password {
|
||||
@@ -168,7 +173,7 @@ func assertCatalogProxyURL(t *testing.T, rawURL, authority, username, password s
|
||||
}
|
||||
}
|
||||
|
||||
func assertCatalogJSON(t *testing.T, body io.Reader, cfg Config, authority string) {
|
||||
func assertCatalogJSON(t *testing.T, body io.Reader, cfg Config, scheme, port string) {
|
||||
t.Helper()
|
||||
var doc struct {
|
||||
SessionID int64 `json:"session_id"`
|
||||
@@ -209,7 +214,7 @@ func assertCatalogJSON(t *testing.T, body io.Reader, cfg Config, authority strin
|
||||
{"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) ||
|
||||
if item.ID != want.id || item.Host != cfg.PublicProxyHost || strconv.Itoa(item.Port) != port ||
|
||||
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)
|
||||
@@ -218,7 +223,7 @@ func assertCatalogJSON(t *testing.T, body io.Reader, cfg Config, authority strin
|
||||
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)
|
||||
assertCatalogProxyURL(t, item.ProxyURL, scheme, net.JoinHostPort(cfg.PublicProxyHost, port), username, password)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,7 +244,7 @@ func readCatalogCSV(t *testing.T, body []byte) [][]string {
|
||||
return rows[1:]
|
||||
}
|
||||
|
||||
func assertCatalogCSV(t *testing.T, body []byte, cfg Config, authority string) {
|
||||
func assertCatalogCSV(t *testing.T, body []byte, cfg Config, scheme, port string) {
|
||||
t.Helper()
|
||||
rows := readCatalogCSV(t, body)
|
||||
if len(rows) != 2 {
|
||||
@@ -251,26 +256,27 @@ func assertCatalogCSV(t *testing.T, body []byte, cfg Config, authority string) {
|
||||
} {
|
||||
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)) ||
|
||||
if row[0] != want.id || row[1] != cfg.PublicProxyHost || row[2] != port ||
|
||||
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)
|
||||
assertCatalogProxyURL(t, row[5], scheme, net.JoinHostPort(cfg.PublicProxyHost, port), username, password)
|
||||
}
|
||||
}
|
||||
|
||||
func assertCatalogText(t *testing.T, body string, cfg Config, authority string, asURL bool) {
|
||||
func assertCatalogText(t *testing.T, body string, cfg Config, scheme, port 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")
|
||||
}
|
||||
authority := net.JoinHostPort(cfg.PublicProxyHost, port)
|
||||
for i, id := range []string{"9007199254740993", "42"} {
|
||||
username, password := "node-"+id, catalogExpectedPassword(cfg, id)
|
||||
if asURL {
|
||||
assertCatalogProxyURL(t, lines[i], authority, username, password)
|
||||
assertCatalogProxyURL(t, lines[i], scheme, authority, username, password)
|
||||
continue
|
||||
}
|
||||
last := strings.LastIndexByte(lines[i], ':')
|
||||
@@ -283,8 +289,8 @@ func assertCatalogText(t *testing.T, body string, cfg Config, authority string,
|
||||
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 {
|
||||
host, gotPort, err := net.SplitHostPort(gotAuthority)
|
||||
if err != nil || gotAuthority != authority || host != cfg.PublicProxyHost || gotPort != port || gotUsername != username || gotPassword != password {
|
||||
t.Fatalf("TXT row %d did not parse as the configured authority and derived credentials", i)
|
||||
}
|
||||
}
|
||||
@@ -313,7 +319,14 @@ func TestGatewayCatalogEmptyAndUnavailable(t *testing.T) {
|
||||
})
|
||||
for _, format := range catalogTestFormats {
|
||||
t.Run(format.name, func(t *testing.T) {
|
||||
w := catalogTestRequest(h, http.MethodGet, "offset=9223372036854775807&format="+format.name, cfg.APIToken)
|
||||
query := "offset=9223372036854775807&format=" + format.name
|
||||
w := catalogTestRequest(h, http.MethodGet, query, cfg.APIToken)
|
||||
socks := catalogTestRequest(h, http.MethodGet, query+"&proxy_type=socks5", cfg.APIToken)
|
||||
if socks.Code != w.Code || !bytes.Equal(socks.Body.Bytes(), w.Body.Bytes()) ||
|
||||
socks.Header().Get("Content-Type") != w.Header().Get("Content-Type") ||
|
||||
socks.Header().Get("Cache-Control") != w.Header().Get("Cache-Control") {
|
||||
t.Fatal("SOCKS catalog should handle an empty result or storage error the same way as HTTP")
|
||||
}
|
||||
assertCatalogPrivateFieldsAbsent(t, w, cfg)
|
||||
if tc.err != nil {
|
||||
assertCatalogResponse(t, w, http.StatusServiceUnavailable, "text/plain; charset=utf-8")
|
||||
@@ -367,6 +380,8 @@ func TestGatewayCatalogRejectsRequestBeforeReadingStore(t *testing.T) {
|
||||
{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, "proxy_type=socks5h", cfg.APIToken, "invalid catalog query\n", http.StatusBadRequest},
|
||||
{http.MethodGet, "proxy_type=http&proxy_type=socks5", 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},
|
||||
} {
|
||||
@@ -381,3 +396,31 @@ func TestGatewayCatalogRejectsRequestBeforeReadingStore(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayCatalogAdvertisedSOCKSPort(t *testing.T) {
|
||||
env := identityTestEnv()
|
||||
for _, tc := range []struct {
|
||||
name, port string
|
||||
want uint16
|
||||
}{
|
||||
{"omitted", "", 1080},
|
||||
{"custom", "11080", 11080},
|
||||
{"zero", "0", 0},
|
||||
{"overflow", "65536", 0},
|
||||
{"not a port", "sensitive-port-value", 0},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
env["GATEWAY_SOCKS_PORT"] = tc.port
|
||||
cfg, err := parseGatewayConfig(func(k string) string { return env[k] })
|
||||
if tc.want == 0 {
|
||||
if err == nil || !strings.HasPrefix(err.Error(), "GATEWAY_SOCKS_PORT ") || strings.Contains(err.Error(), "sensitive-") {
|
||||
t.Fatal("expected a sanitized error for the invalid advertised SOCKS port")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || cfg.PublicSOCKSPort != tc.want || cfg.PublicProxyPort != 8081 {
|
||||
t.Fatal("SOCKS publication port should be independent of HTTP")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ type Config struct {
|
||||
DBDSN string
|
||||
PublicProxyHost string
|
||||
PublicProxyPort uint16
|
||||
PublicSOCKSPort uint16
|
||||
APIToken string
|
||||
NodeSecret [32]byte
|
||||
ProbeURL *url.URL
|
||||
@@ -47,6 +48,14 @@ func parseGatewayConfig(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("GATEWAY_PUBLIC_PROXY_ADDR must be a reachable host:port (bracket IPv6)")
|
||||
}
|
||||
|
||||
cfg.PublicSOCKSPort = 1080
|
||||
if port := getenv("GATEWAY_SOCKS_PORT"); port != "" {
|
||||
cfg.PublicSOCKSPort, ok = parseGatewayPort(port)
|
||||
if !ok {
|
||||
return Config{}, errors.New("GATEWAY_SOCKS_PORT must be a decimal port in 1..65535")
|
||||
}
|
||||
}
|
||||
|
||||
cfg.APIToken = getenv("GATEWAY_API_TOKEN")
|
||||
apiKey, ok := decodeGatewaySecret(cfg.APIToken)
|
||||
if !ok {
|
||||
@@ -62,7 +71,7 @@ func parseGatewayConfig(getenv func(string) string) (Config, error) {
|
||||
|
||||
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")
|
||||
return Config{}, errors.New("GATEWAY_ALLOWED_DESTINATIONS must be a list of exact DNS names with ports")
|
||||
}
|
||||
cfg.ProbeURL, ok = parseGatewayProbeURL(getenv("GATEWAY_PROBE_URL"))
|
||||
if !ok {
|
||||
|
||||
@@ -81,6 +81,7 @@ func TestGatewayLaunchConfigRejectsInvalidPolicyAndRedactsValues(t *testing.T) {
|
||||
{"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"},
|
||||
{"legacy public web mode", "GATEWAY_ALLOWED_DESTINATIONS", "public-web"},
|
||||
{"broad upstream", "GATEWAY_UPSTREAM_NETWORKS", "1.1.0.0/16"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
@@ -96,6 +97,19 @@ func TestGatewayLaunchConfigRejectsInvalidPolicyAndRedactsValues(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayLaunchConfigAcceptsListedCustomProbePort(t *testing.T) {
|
||||
env := identityTestEnv()
|
||||
env["GATEWAY_PROBE_URL"] = "https://probe.example:8443/check"
|
||||
env["GATEWAY_ALLOWED_DESTINATIONS"] = "probe.example:8443"
|
||||
cfg, err := parseGatewayConfig(func(k string) string { return env[k] })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.ProbeURL.Host != "probe.example:8443" {
|
||||
t.Fatalf("probe authority = %q, want probe.example:8443", cfg.ProbeURL.Host)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewaySecretEncoding(t *testing.T) {
|
||||
valid := identityTestToken(1)
|
||||
if got, ok := decodeGatewaySecret(valid); !ok || got != identityTestKey(1) {
|
||||
|
||||
@@ -17,9 +17,17 @@ const (
|
||||
catalogURLs catalogFormat = "proxy-url-list-txt"
|
||||
)
|
||||
|
||||
type catalogProxyType string
|
||||
|
||||
const (
|
||||
catalogProxyHTTP catalogProxyType = "http"
|
||||
catalogProxySOCKS catalogProxyType = "socks5"
|
||||
)
|
||||
|
||||
type catalogQuery struct {
|
||||
filter db.GatewayCatalogFilter
|
||||
format catalogFormat
|
||||
filter db.GatewayCatalogFilter
|
||||
format catalogFormat
|
||||
proxyType catalogProxyType
|
||||
}
|
||||
|
||||
func parseCatalogQuery(raw string) (catalogQuery, bool) {
|
||||
@@ -28,7 +36,7 @@ func parseCatalogQuery(raw string) (catalogQuery, bool) {
|
||||
// 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}}
|
||||
q := catalogQuery{format: catalogJSON, proxyType: catalogProxyHTTP, filter: db.GatewayCatalogFilter{Sort: db.GatewaySortID}}
|
||||
for key, values := range params {
|
||||
switch key {
|
||||
case "country", "protocol":
|
||||
@@ -63,6 +71,13 @@ func parseCatalogQuery(raw string) (catalogQuery, bool) {
|
||||
default:
|
||||
return catalogQuery{}, false
|
||||
}
|
||||
case "proxy_type":
|
||||
q.proxyType = catalogProxyType(value)
|
||||
switch q.proxyType {
|
||||
case catalogProxyHTTP, catalogProxySOCKS:
|
||||
default:
|
||||
return catalogQuery{}, false
|
||||
}
|
||||
case "sort":
|
||||
q.filter.Sort = db.GatewayCatalogSort(value)
|
||||
switch q.filter.Sort {
|
||||
|
||||
@@ -15,26 +15,27 @@ 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
|
||||
name string
|
||||
raw string
|
||||
format catalogFormat
|
||||
proxyType catalogProxyType
|
||||
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,
|
||||
{"defaults", "", catalogJSON, catalogProxyHTTP, 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&proxy_type=socks5", catalogCSV, catalogProxySOCKS,
|
||||
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,
|
||||
{"zeros are explicit", "min_speed_mbps=0&max_latency_ms=0&offset=0&limit=01&sort=speed&format=txt", catalogTXT, catalogProxyHTTP,
|
||||
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,
|
||||
{"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, catalogProxyHTTP,
|
||||
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,
|
||||
{"maximum finite speed", "min_speed_mbps=1.7976931348623157e308&sort=id&format=json&proxy_type=http", catalogJSON, catalogProxyHTTP,
|
||||
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)
|
||||
if !ok || got.format != tc.format || got.proxyType != tc.proxyType || !reflect.DeepEqual(got.filter, tc.filter) {
|
||||
t.Fatalf("catalog query did not preserve the requested format, proxy type and filter: %+v, valid=%t", got, ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -52,6 +53,12 @@ func TestGatewayCatalogQueryRejectsInvalidInput(t *testing.T) {
|
||||
{"illegal separator", "country=DE;sort=id"},
|
||||
{"unsupported format", "format=xml"},
|
||||
{"empty format", "format="},
|
||||
{"unsupported proxy type", "proxy_type=socks4"},
|
||||
{"URI scheme is not a proxy type", "proxy_type=socks5h"},
|
||||
{"empty proxy type", "proxy_type="},
|
||||
{"uppercase proxy type", "proxy_type=SOCKS5"},
|
||||
{"multiple proxy types", "proxy_type=http,socks5"},
|
||||
{"conflicting proxy types", "proxy_type=http&proxy_type=socks5"},
|
||||
{"unsupported sort", "sort=desc"},
|
||||
{"sort injection", "sort=id%3B+SELECT+1"},
|
||||
{"empty sort", "sort="},
|
||||
@@ -92,7 +99,7 @@ func TestGatewayCatalogQueryRejectsInvalidInput(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"} {
|
||||
for _, pair := range []string{"sort=id", "format=txt", "proxy_type=socks5", "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)
|
||||
@@ -121,6 +128,7 @@ func FuzzGatewayCatalogQuery(f *testing.F) {
|
||||
"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",
|
||||
"proxy_type=socks5&protocol=vless&format=proxy-url-list-txt", "proxy_type=http&proxy_type=socks5",
|
||||
} {
|
||||
f.Add(seed)
|
||||
}
|
||||
@@ -132,7 +140,7 @@ func FuzzGatewayCatalogQuery(f *testing.F) {
|
||||
}
|
||||
return
|
||||
}
|
||||
canonical := url.Values{"format": {string(q.format)}, "sort": {string(q.filter.Sort)}}
|
||||
canonical := url.Values{"format": {string(q.format)}, "sort": {string(q.filter.Sort)}, "proxy_type": {string(q.proxyType)}}
|
||||
for _, country := range q.filter.Countries {
|
||||
canonical.Add("country", country)
|
||||
}
|
||||
@@ -151,7 +159,7 @@ func FuzzGatewayCatalogQuery(f *testing.F) {
|
||||
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")
|
||||
t.Fatal("canonical query changed the parsed filters, format or proxy type")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -32,7 +32,7 @@ type forwardTiming struct {
|
||||
// connections that have been hijacked from the HTTP server.
|
||||
type ForwardProxy struct {
|
||||
store GatewayNodeStore
|
||||
resolveRequest func(context.Context, *http.Request) (string, string, error)
|
||||
resolveRequest func(context.Context, *http.Request, bool) (string, string, error)
|
||||
dispatcher dialer.Dialer
|
||||
tickets *probeTickets
|
||||
users chan struct{}
|
||||
@@ -133,7 +133,8 @@ func (p *ForwardProxy) open(ctx context.Context, r *http.Request, id, membership
|
||||
}
|
||||
return nil, http.StatusServiceUnavailable
|
||||
}
|
||||
_, destination, err := p.resolveRequest(setup, r)
|
||||
// A probe ticket only bypasses readiness for its exact configured target.
|
||||
_, destination, err := p.resolveRequest(setup, r, membership == 0 && node.AllowAllSites)
|
||||
if err != nil {
|
||||
switch {
|
||||
case forwardTimeout(setup, err):
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -66,7 +67,7 @@ func (f forwardTestDial) Dial(ctx context.Context, up *upstream.Upstream, dest s
|
||||
|
||||
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) {
|
||||
p.resolveRequest = func(_ context.Context, r *http.Request, _ bool) (string, string, error) {
|
||||
return r.URL.Host, dest, nil
|
||||
}
|
||||
return p
|
||||
@@ -324,6 +325,58 @@ func TestForwardKeepAliveReauthenticatesAndDoesNotFailOver(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardReadsAllowAllSitesForEveryRequest(t *testing.T) {
|
||||
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, "public origin")
|
||||
}))
|
||||
defer origin.Close()
|
||||
|
||||
var allowAllSites atomic.Bool
|
||||
store := forwardTestStore{ready: func(id int64) (*db.GatewayNode, error) {
|
||||
node := forwardTestNode(id, 1)
|
||||
node.AllowAllSites = allowAllSites.Load()
|
||||
return node, nil
|
||||
}}
|
||||
policy := newRouteTestPolicy(t, routeTestConfig())
|
||||
policy.resolveIP = func(_ context.Context, name string) ([]netip.Addr, error) {
|
||||
if name != "unlisted.operator.test." {
|
||||
return nil, errors.New("unexpected fixture DNS name")
|
||||
}
|
||||
return []netip.Addr{netip.MustParseAddr("1.1.1.1")}, nil
|
||||
}
|
||||
var dials atomic.Int32
|
||||
p := NewForwardProxy(store, policy, forwardTestDial(func(ctx context.Context, up *upstream.Upstream, destination string) (net.Conn, error) {
|
||||
dials.Add(1)
|
||||
if up.Host != "peer1.fixture" || destination != "1.1.1.1:80" {
|
||||
t.Error("request did not use the selected node and pinned destination")
|
||||
return nil, errors.New("unexpected fixture node or destination")
|
||||
}
|
||||
return (&net.Dialer{}).DialContext(ctx, "tcp", origin.Listener.Addr().String())
|
||||
}), nil)
|
||||
addr, credentials := serveForwardTest(t, p)
|
||||
c, r := forwardTestTCP(t, addr)
|
||||
auth := forwardTestBasic(credentials, 1)
|
||||
for _, enabled := range []bool{false, true, false, true} {
|
||||
allowAllSites.Store(enabled)
|
||||
want := http.StatusForbidden
|
||||
if enabled {
|
||||
want = http.StatusOK
|
||||
}
|
||||
if _, err := fmt.Fprintf(c, "GET http://unlisted.operator.test/ HTTP/1.1\r\nHost: unlisted.operator.test\r\n%s\r\n", auth); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := forwardTestResponse(t, r, http.MethodGet, want)
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if err != nil || (enabled && string(body) != "public origin") {
|
||||
t.Fatalf("allowAllSites=%t: body=%q, err=%v", enabled, body, err)
|
||||
}
|
||||
}
|
||||
if got := dials.Load(); got != 2 {
|
||||
t.Fatalf("got %d upstream dials, want one for each allowed request", got)
|
||||
}
|
||||
}
|
||||
|
||||
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") != "" {
|
||||
|
||||
@@ -74,6 +74,7 @@ type chainCatalog struct {
|
||||
sessionID int64
|
||||
finished time.Time
|
||||
forbidden []string
|
||||
socks bool
|
||||
}
|
||||
|
||||
// Client-facing record, declared independently of the server's DTO and writers.
|
||||
@@ -94,6 +95,9 @@ type chainExportRow struct {
|
||||
|
||||
func (c chainCatalog) body(t *testing.T, filter, format, contentType string) []byte {
|
||||
t.Helper()
|
||||
if c.socks {
|
||||
filter += "&proxy_type=socks5"
|
||||
}
|
||||
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))
|
||||
@@ -196,7 +200,7 @@ func (c chainCatalog) exports(t *testing.T, filter string, want []db.SessionProx
|
||||
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)}
|
||||
textURLs[i] = &url.URL{Scheme: jsonURLs[i].Scheme, Host: address, User: url.UserPassword(user, password)}
|
||||
}
|
||||
chainSameURLs(t, jsonURLs, textURLs)
|
||||
if use != nil {
|
||||
@@ -230,8 +234,12 @@ func (c chainCatalog) lines(t *testing.T, filter, format string, count int) []st
|
||||
|
||||
func (c chainCatalog) parseURL(t *testing.T, format, raw string) *url.URL {
|
||||
t.Helper()
|
||||
scheme, address := "http", c.runtime.endpoint.ProxyAddr
|
||||
if c.socks {
|
||||
scheme, address = "socks5h", c.runtime.endpoint.SOCKSAddr
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Scheme != "http" || u.Host != c.runtime.endpoint.ProxyAddr || u.User == nil ||
|
||||
if err != nil || u.Scheme != scheme || u.Host != address || 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)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
@@ -54,7 +55,7 @@ func TestGatewayE2EFullChain(t *testing.T) {
|
||||
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")
|
||||
runtime := startChainRuntime(t, cfg, policy, ca.Roots, "127.0.0.1:0", "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 {
|
||||
@@ -65,6 +66,8 @@ func TestGatewayE2EFullChain(t *testing.T) {
|
||||
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}}
|
||||
socksCatalog := catalog
|
||||
socksCatalog.socks = true
|
||||
runtime.requireStatus(t, "/readyz", "", http.StatusOK)
|
||||
runtime.requireStatus(t, "/v1/proxies", "", http.StatusUnauthorized)
|
||||
runtime.requireStatus(t, "/v1/proxies", "not-the-token", http.StatusUnauthorized)
|
||||
@@ -77,6 +80,27 @@ func TestGatewayE2EFullChain(t *testing.T) {
|
||||
}
|
||||
opens.requireSince(t, mark, second.Addr.String(), second.Addr.String(), first.Addr.String(), first.Addr.String())
|
||||
})
|
||||
socks := socksCatalog.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)
|
||||
for _, target := range []string{origin.HTTPURL, origin.HTTPSURL} {
|
||||
nonce := []byte(rand.Text())
|
||||
wireRoundTrip(t, client, origin, peer, target, http.MethodPost, nonce, nonce, false)
|
||||
}
|
||||
}
|
||||
opens.requireSince(t, mark, second.Addr.String(), second.Addr.String(), first.Addr.String(), first.Addr.String())
|
||||
})
|
||||
for i, u := range socks {
|
||||
if u.User.String() != initial[i].User.String() {
|
||||
t.Fatal("SOCKS and HTTP exports did not use the same node credentials")
|
||||
}
|
||||
}
|
||||
wrong := *socks[1]
|
||||
wrong.User = url.UserPassword(socks[1].User.Username(), "invalid-fixture-password")
|
||||
mark := opens.mark()
|
||||
chainRequireSOCKSReject(t, newWireClient(t, &wrong, ca.Roots), origin, first, "username/password authentication failed")
|
||||
opens.requireSince(t, mark)
|
||||
filtered := catalog.exports(t, onlyFirst, []db.SessionProxy{a}, nil)
|
||||
firstPassword, _ := initial[1].User.Password()
|
||||
secondPassword, _ := initial[0].User.Password()
|
||||
@@ -85,12 +109,18 @@ func TestGatewayE2EFullChain(t *testing.T) {
|
||||
}
|
||||
firstClient := newWireClient(t, initial[1], ca.Roots)
|
||||
secondClient := newWireClient(t, initial[0], ca.Roots)
|
||||
firstSOCKS := newWireClient(t, socks[1], ca.Roots)
|
||||
secondSOCKS := newWireClient(t, socks[0], ca.Roots)
|
||||
|
||||
first.Stop(t)
|
||||
mark := opens.mark()
|
||||
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)
|
||||
mark = opens.mark()
|
||||
chainRequireSOCKSReject(t, firstSOCKS, origin, first, chainSOCKSGeneralFailure)
|
||||
opens.requireSince(t, mark, first.Addr.String(), first.Addr.String())
|
||||
wireRoundTrip(t, secondSOCKS, origin, second, origin.HTTPSURL, http.MethodGet, nil, []byte(rand.Text()), false)
|
||||
|
||||
// Use the database clock to expire this positive sample without waiting
|
||||
// a wall-clock TTL or changing production timing or forwarding policy.
|
||||
@@ -102,6 +132,8 @@ func TestGatewayE2EFullChain(t *testing.T) {
|
||||
mark = opens.mark()
|
||||
chainRequireForwardStatus(t, firstClient, origin, first, http.StatusServiceUnavailable)
|
||||
catalog.exports(t, onlyFirst, nil, nil)
|
||||
chainRequireSOCKSReject(t, firstSOCKS, origin, first, chainSOCKSGeneralFailure)
|
||||
socksCatalog.exports(t, onlyFirst, nil, nil)
|
||||
opens.requireSince(t, mark)
|
||||
|
||||
// Replacing a membership in the same published snapshot triggers an
|
||||
@@ -115,8 +147,10 @@ func TestGatewayE2EFullChain(t *testing.T) {
|
||||
}
|
||||
mark = opens.mark()
|
||||
chainRequireForwardStatus(t, firstClient, origin, first, http.StatusServiceUnavailable)
|
||||
chainRequireSOCKSReject(t, firstSOCKS, origin, first, chainSOCKSGeneralFailure)
|
||||
opens.requireSince(t, mark)
|
||||
catalog.exports(t, all, []db.SessionProxy{b}, nil)
|
||||
socksCatalog.exports(t, all, []db.SessionProxy{b}, nil)
|
||||
|
||||
first = first.Restart(t)
|
||||
chainDBOK(t, "remove failed membership", store.DeleteSessionProxies(t.Context(), sessionID, []int64{a.ProxyID}))
|
||||
@@ -129,14 +163,30 @@ func TestGatewayE2EFullChain(t *testing.T) {
|
||||
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)
|
||||
chainSameURLs(t, socks, socksCatalog.exports(t, all, []db.SessionProxy{b, a}, nil))
|
||||
wireRoundTrip(t, firstSOCKS, origin, first, origin.HTTPURL, http.MethodGet, nil, []byte(rand.Text()), false)
|
||||
|
||||
proxyAddr := runtime.endpoint.ProxyAddr
|
||||
proxyAddr, socksAddr := runtime.endpoint.ProxyAddr, runtime.endpoint.SOCKSAddr
|
||||
runtime.stop(t)
|
||||
catalog.runtime = startChainRuntime(t, cfg, policy, ca.Roots, proxyAddr)
|
||||
catalog.runtime = startChainRuntime(t, cfg, policy, ca.Roots, proxyAddr, socksAddr)
|
||||
socksCatalog.runtime = catalog.runtime
|
||||
catalog.runtime.waitStatus(t, sessionID, 2, *recovered.LastSuccessAt)
|
||||
chainSameURLs(t, initial, catalog.exports(t, all, []db.SessionProxy{b, a}, nil))
|
||||
chainSameURLs(t, socks, socksCatalog.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)
|
||||
wireRoundTrip(t, firstSOCKS, origin, first, origin.HTTPSURL, http.MethodGet, nil, []byte(rand.Text()), false)
|
||||
|
||||
// A live peer with fresh positive health must still lose access as soon
|
||||
// as its membership is removed from the current published snapshot.
|
||||
chainDBOK(t, "remove healthy membership", store.DeleteSessionProxies(t.Context(), sessionID, []int64{a.ProxyID}))
|
||||
mark = opens.mark()
|
||||
chainRequireForwardStatus(t, firstClient, origin, first, http.StatusServiceUnavailable)
|
||||
chainRequireSOCKSReject(t, firstSOCKS, origin, first, chainSOCKSGeneralFailure)
|
||||
catalog.exports(t, all, []db.SessionProxy{b}, nil)
|
||||
socksCatalog.exports(t, all, []db.SessionProxy{b}, nil)
|
||||
opens.requireSince(t, mark)
|
||||
wireRoundTrip(t, secondSOCKS, origin, second, origin.HTTPURL, http.MethodGet, nil, []byte(rand.Text()), false)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -238,7 +288,7 @@ type chainRuntime struct {
|
||||
err error // Published by closing done.
|
||||
}
|
||||
|
||||
func startChainRuntime(t *testing.T, cfg Config, policy *RoutePolicy, roots *x509.CertPool, proxyAddr string) *chainRuntime {
|
||||
func startChainRuntime(t *testing.T, cfg Config, policy *RoutePolicy, roots *x509.CertPool, proxyAddr, socksAddr string) *chainRuntime {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
runtime := &chainRuntime{cancel: cancel, done: make(chan struct{}), token: cfg.APIToken}
|
||||
@@ -250,7 +300,7 @@ func startChainRuntime(t *testing.T, cfg Config, policy *RoutePolicy, roots *x50
|
||||
endpoints := make(chan RuntimeEndpoints, 1)
|
||||
go func() {
|
||||
runtime.err = Run(ctx, store, cfg, RuntimeOptions{
|
||||
ProxyAddr: proxyAddr, APIAddr: "127.0.0.1:0",
|
||||
ProxyAddr: proxyAddr, APIAddr: "127.0.0.1:0", SOCKSAddr: socksAddr,
|
||||
Build: func(_ context.Context, e RuntimeEndpoints) (RuntimeComponents, error) {
|
||||
host, port, err := net.SplitHostPort(e.ProxyAddr)
|
||||
if err != nil {
|
||||
@@ -262,6 +312,15 @@ func startChainRuntime(t *testing.T, cfg Config, policy *RoutePolicy, roots *x50
|
||||
}
|
||||
bound := cfg
|
||||
bound.PublicProxyHost, bound.PublicProxyPort = host, uint16(number)
|
||||
_, port, err = net.SplitHostPort(e.SOCKSAddr)
|
||||
if err != nil {
|
||||
return RuntimeComponents{}, err
|
||||
}
|
||||
number, err = strconv.ParseUint(port, 10, 16)
|
||||
if err != nil {
|
||||
return RuntimeComponents{}, err
|
||||
}
|
||||
bound.PublicSOCKSPort = uint16(number)
|
||||
components, err := newRuntimeComponents(store, bound, e, policy, roots)
|
||||
if err == nil {
|
||||
endpoints <- e
|
||||
@@ -324,3 +383,25 @@ func chainRequireForwardStatus(t *testing.T, client *http.Client, origin *testfi
|
||||
t.Fatalf("proxy status = %d, want %d, or unexpected origin dial", resp.StatusCode, want)
|
||||
}
|
||||
}
|
||||
|
||||
const chainSOCKSGeneralFailure = "unknown error general SOCKS server failure"
|
||||
|
||||
func chainRequireSOCKSReject(t *testing.T, client *http.Client, origin *testfixture.Origin, peer *testfixture.Peer, want string) {
|
||||
t.Helper()
|
||||
for _, target := range []string{origin.HTTPURL, origin.HTTPSURL} {
|
||||
x := origin.Expect(t, peer.Source, testfixture.Exchange{Response: []byte("unexpected SOCKS route")})
|
||||
connections := origin.Connections()
|
||||
resp, err := client.Do(newWireRequest(t, t.Context(), target, x.Path, http.MethodGet, nil))
|
||||
if resp != nil {
|
||||
resp.Body.Close()
|
||||
t.Fatalf("SOCKS rejection returned an HTTP %d response", resp.StatusCode)
|
||||
}
|
||||
var op *net.OpError
|
||||
if !errors.As(err, &op) || op.Op != "socks connect" || op.Err.Error() != want {
|
||||
t.Fatalf("expected SOCKS rejection %q, got %v", want, wireClientError(err))
|
||||
}
|
||||
if x.Hits() != 0 || origin.Connections() != connections {
|
||||
t.Fatal("rejected SOCKS connection reached the origin")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,7 +82,9 @@ func monitorHTTPNode(t *testing.T, candidate db.GatewayCandidate, endpoint *url.
|
||||
t.Error("CONNECT did not use the selected node credentials and ticket membership")
|
||||
return nil, nil
|
||||
}
|
||||
return forwardTestNode(id, membership), nil
|
||||
node := forwardTestNode(id, membership)
|
||||
node.AllowAllSites = true
|
||||
return node, nil
|
||||
},
|
||||
}
|
||||
return NewForwardProxy(store, policy, dial, tickets), tickets
|
||||
@@ -248,7 +250,7 @@ func TestHTTPGatewayProberClassifiesConnectFailure(t *testing.T) {
|
||||
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) {
|
||||
forward.resolveRequest = func(context.Context, *http.Request, bool) (string, string, error) {
|
||||
return "", "", context.DeadlineExceeded
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ func NewRoutePolicy(cfg Config) *RoutePolicy {
|
||||
|
||||
// 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) {
|
||||
func (p *RoutePolicy) ResolveRequest(ctx context.Context, r *http.Request, allowAllSites bool) (authority, destination string, err error) {
|
||||
var defaultPort uint16 = 80
|
||||
u := r.URL
|
||||
if u == nil || u.Host == "" || u.User != nil || u.Opaque != "" || u.OmitHost ||
|
||||
@@ -92,12 +92,15 @@ func (p *RoutePolicy) ResolveRequest(ctx context.Context, r *http.Request) (auth
|
||||
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
|
||||
if _, listed := p.destinations[authority]; !listed || target.ip.IsValid() {
|
||||
webPort := uint16(80)
|
||||
if r.Method == http.MethodConnect {
|
||||
webPort = 443
|
||||
}
|
||||
if !allowAllSites || target.port != webPort {
|
||||
return "", "", ErrDestinationDenied
|
||||
}
|
||||
}
|
||||
pinned, err := p.pin(ctx, target, false, ErrDestinationDenied)
|
||||
if err != nil {
|
||||
|
||||
@@ -53,6 +53,46 @@ func readRouteTestRequest(t *testing.T, wire string) *http.Request {
|
||||
return r
|
||||
}
|
||||
|
||||
func TestPublicWebDestinations(t *testing.T) {
|
||||
cfg := routeTestConfig()
|
||||
cfg.AllowedDestinations["app.operator.test:8080"] = struct{}{}
|
||||
cfg.AllowedDestinations["app.operator.test:8443"] = struct{}{}
|
||||
p := newRouteTestPolicy(t, cfg)
|
||||
p.resolveIP = func(context.Context, string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("1.1.1.1")}, nil
|
||||
}
|
||||
for _, tc := range []struct{ method, target, pinned string }{
|
||||
{"GET", "http://new.example/", "1.1.1.1:80"},
|
||||
{"GET", "http://1.1.1.1/", "1.1.1.1:80"},
|
||||
{"GET", "http://app.operator.test:8080/", "1.1.1.1:8080"},
|
||||
{"CONNECT", "another.example:443", "1.1.1.1:443"},
|
||||
{"CONNECT", "app.operator.test:8443", "1.1.1.1:8443"},
|
||||
{"CONNECT", "[2606:4700::1111]:443", "[2606:4700::1111]:443"},
|
||||
{"CONNECT", "another.example:22", ""},
|
||||
{"GET", "http://new.example:443/", ""},
|
||||
{"CONNECT", "another.example:80", ""},
|
||||
{"GET", "http://gateway.operator.test/", ""},
|
||||
{"GET", "http://169.254.169.254/", ""},
|
||||
{"CONNECT", "127.0.0.1:443", ""},
|
||||
} {
|
||||
r := readRouteTestRequest(t, tc.method+" "+tc.target+" HTTP/1.1\r\nHost: ignored.example\r\n\r\n")
|
||||
_, got, err := p.ResolveRequest(t.Context(), r, true)
|
||||
var wantErr error
|
||||
if tc.pinned == "" {
|
||||
wantErr = ErrDestinationDenied
|
||||
}
|
||||
if got != tc.pinned || err != wantErr {
|
||||
t.Errorf("%s %s: got %q, %v; want %q, %v", tc.method, tc.target, got, err, tc.pinned, wantErr)
|
||||
}
|
||||
}
|
||||
if _, err := p.DialControl(t.Context(), "tcp", "another.example:443"); err != errControlDenied {
|
||||
t.Errorf("unexpected control route: %v", err)
|
||||
}
|
||||
if _, err := p.DialUpstream(t.Context(), "tcp", "9.9.9.9:443"); err != ErrUpstreamDenied {
|
||||
t.Errorf("unexpected upstream route: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteRequestPinsExactDestination(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, wire, lookup, authority, host, pinned string
|
||||
@@ -89,7 +129,7 @@ func TestRouteRequestPinsExactDestination(t *testing.T) {
|
||||
return tt.ips, nil
|
||||
}
|
||||
r := readRouteTestRequest(t, tt.wire)
|
||||
authority, pinned, err := policy.ResolveRequest(t.Context(), r)
|
||||
authority, pinned, err := policy.ResolveRequest(t.Context(), r, false)
|
||||
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)
|
||||
}
|
||||
@@ -141,7 +181,7 @@ func TestRouteRequestRejectsInvalidOrUnapprovedBeforeDNS(t *testing.T) {
|
||||
if tt.denied {
|
||||
want = ErrDestinationDenied
|
||||
}
|
||||
authority, pinned, err := policy.ResolveRequest(t.Context(), r)
|
||||
authority, pinned, err := policy.ResolveRequest(t.Context(), r, false)
|
||||
if err != want || authority != "" || pinned != "" {
|
||||
t.Fatalf("resolved (%q, %q, %v), want %v", authority, pinned, err, want)
|
||||
}
|
||||
@@ -172,7 +212,7 @@ func TestRouteCONNECTRequiresUnframedHTTP11Authority(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)
|
||||
_, _, err := policy.ResolveRequest(t.Context(), r, true)
|
||||
if err != ErrInvalidDestination {
|
||||
t.Fatalf("err = %v, want invalid destination", err)
|
||||
}
|
||||
@@ -204,9 +244,16 @@ func TestRouteRequestRejectsAnyUnsafeAnswer(t *testing.T) {
|
||||
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)
|
||||
for _, allowAllSites := range []bool{false, true} {
|
||||
host := "app.operator.test"
|
||||
if allowAllSites {
|
||||
host = "unlisted.operator.test"
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodGet, "http://"+host+"/", nil)
|
||||
_, ip, err := policy.ResolveRequest(t.Context(), r, allowAllSites)
|
||||
if err != ErrDestinationDenied || ip != "" {
|
||||
t.Fatalf("allowAllSites=%t: resolved (%q, %v), want denial with no pinned IP", allowAllSites, ip, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -329,16 +376,16 @@ func TestRouteFailsClosedWithoutLeakingNetworkErrors(t *testing.T) {
|
||||
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 {
|
||||
if _, _, err := policy.ResolveRequest(ctx, r, false); 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 {
|
||||
if _, _, err := policy.ResolveRequest(t.Context(), r, false); 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 {
|
||||
if _, _, err := policy.ResolveRequest(t.Context(), r, false); err != context.DeadlineExceeded {
|
||||
t.Fatalf("timed out lookup: %v", err)
|
||||
}
|
||||
policy.localIPs = func() ([]netip.Addr, error) { return nil, privateError }
|
||||
|
||||
@@ -236,7 +236,7 @@ func TestForwardSeparateProbeBudgetAndShutdownClosesHijacks(t *testing.T) {
|
||||
defer c.Close()
|
||||
return forwardTestConnect(t, c, r, auth, ticket, "", status)
|
||||
}
|
||||
request(auth2, "", 503) // pending: ordinary access cannot open the node.
|
||||
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)
|
||||
@@ -305,7 +305,7 @@ func TestForwardProbeTimeoutClassification(t *testing.T) {
|
||||
return nil, context.DeadlineExceeded
|
||||
}, tickets, "192.0.2.77:443")
|
||||
if tc.routeFail {
|
||||
p.resolveRequest = func(context.Context, *http.Request) (string, string, error) {
|
||||
p.resolveRequest = func(context.Context, *http.Request, bool) (string, string, error) {
|
||||
return "", "", context.DeadlineExceeded
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,15 +20,18 @@ import (
|
||||
const (
|
||||
defaultProxyAddr = ":8081"
|
||||
defaultAPIAddr = ":8082"
|
||||
defaultSOCKSAddr = ":1080"
|
||||
maxSOCKSPreAuth = 64
|
||||
)
|
||||
|
||||
// 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.
|
||||
// binding all 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
|
||||
SOCKSAddr string
|
||||
Build func(context.Context, RuntimeEndpoints) (RuntimeComponents, error)
|
||||
}
|
||||
|
||||
@@ -37,6 +40,7 @@ type RuntimeOptions struct {
|
||||
type RuntimeEndpoints struct {
|
||||
ProxyAddr string
|
||||
APIAddr string
|
||||
SOCKSAddr string
|
||||
ProbeProxyAddr string
|
||||
Credentials Credentials
|
||||
Lease *db.GatewayLease
|
||||
@@ -51,11 +55,12 @@ type RuntimeComponents struct {
|
||||
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.
|
||||
// ProxyLifecycle handles authenticated HTTP requests and whole SOCKS sessions.
|
||||
// ServeSOCKS is synchronous. Shutdown must close active tunnels and wait for
|
||||
// their handlers; net/http no longer owns hijacked sockets.
|
||||
type ProxyLifecycle interface {
|
||||
ServeProxy(http.ResponseWriter, *http.Request, int64)
|
||||
ServeSOCKS(context.Context, net.Conn, Credentials)
|
||||
Shutdown(context.Context) error
|
||||
}
|
||||
|
||||
@@ -63,7 +68,7 @@ type runtimeTiming struct {
|
||||
startup, retry, dbCall, heartbeat, shutdown time.Duration
|
||||
}
|
||||
|
||||
// Run owns both listeners, the database lease, the monitor, and their shutdown.
|
||||
// Run owns all 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 {
|
||||
@@ -83,6 +88,8 @@ type runtimeActive struct {
|
||||
lease *db.GatewayLease
|
||||
catalog http.Handler
|
||||
proxy http.Handler
|
||||
socks ProxyLifecycle
|
||||
creds Credentials
|
||||
heartbeat atomic.Bool
|
||||
}
|
||||
|
||||
@@ -106,6 +113,9 @@ func runGateway(parent context.Context, store *db.DB, cfg Config, opts RuntimeOp
|
||||
if opts.APIAddr == "" {
|
||||
opts.APIAddr = defaultAPIAddr
|
||||
}
|
||||
if opts.SOCKSAddr == "" {
|
||||
opts.SOCKSAddr = defaultSOCKSAddr
|
||||
}
|
||||
|
||||
proxyListener, err := listen(parent, "tcp", opts.ProxyAddr)
|
||||
if err != nil {
|
||||
@@ -123,6 +133,14 @@ func runGateway(parent context.Context, store *db.DB, cfg Config, opts RuntimeOp
|
||||
return errors.New("could not bind gateway API listener")
|
||||
}
|
||||
defer apiListener.Close()
|
||||
socksListener, err := listen(parent, "tcp", opts.SOCKSAddr)
|
||||
if err != nil {
|
||||
if parent.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return errors.New("could not bind gateway SOCKS listener")
|
||||
}
|
||||
defer socksListener.Close()
|
||||
probeProxyAddr, err := runtimeLoopbackAddr(proxyListener.Addr())
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -138,6 +156,7 @@ func runGateway(parent context.Context, store *db.DB, cfg Config, opts RuntimeOp
|
||||
defer func() {
|
||||
stop(nil)
|
||||
runtime.active.Store(nil)
|
||||
_ = socksListener.Close()
|
||||
result = errors.Join(result, shutdownGateway(timing.shutdown, apiServer, proxyServer, components.Proxy))
|
||||
workers.Wait()
|
||||
if lease != nil {
|
||||
@@ -158,6 +177,7 @@ func runGateway(parent context.Context, store *db.DB, cfg Config, opts RuntimeOp
|
||||
}
|
||||
})
|
||||
}
|
||||
workers.Go(func() { runtime.serveSOCKS(socksListener, stop) })
|
||||
|
||||
startCtx, cancelStart := context.WithTimeout(ctx, timing.startup)
|
||||
defer cancelStart()
|
||||
@@ -183,6 +203,7 @@ func runGateway(parent context.Context, store *db.DB, cfg Config, opts RuntimeOp
|
||||
components, err = opts.Build(startCtx, RuntimeEndpoints{
|
||||
ProxyAddr: proxyListener.Addr().String(),
|
||||
APIAddr: apiListener.Addr().String(),
|
||||
SOCKSAddr: socksListener.Addr().String(),
|
||||
ProbeProxyAddr: probeProxyAddr,
|
||||
Credentials: credentials,
|
||||
Lease: lease,
|
||||
@@ -218,6 +239,8 @@ func runGateway(parent context.Context, store *db.DB, cfg Config, opts RuntimeOp
|
||||
lease: lease,
|
||||
catalog: components.Catalog,
|
||||
proxy: credentials.RequireProxyAuth(proxyFormHandler(components.Proxy)),
|
||||
socks: components.Proxy,
|
||||
creds: credentials,
|
||||
}
|
||||
active.heartbeat.Store(true)
|
||||
runtime.active.Store(active)
|
||||
@@ -354,6 +377,65 @@ func (rt *gatewayRuntime) serveProxy(w http.ResponseWriter, r *http.Request) {
|
||||
active.proxy.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func (rt *gatewayRuntime) serveSOCKS(listener net.Listener, stop context.CancelCauseFunc) {
|
||||
preAuth := make(chan struct{}, maxSOCKSPreAuth)
|
||||
var clients sync.WaitGroup
|
||||
defer clients.Wait()
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
if rt.ctx.Err() == nil {
|
||||
stop(errors.New("gateway SOCKS listener stopped"))
|
||||
}
|
||||
return
|
||||
}
|
||||
active := rt.serving()
|
||||
if active == nil {
|
||||
_ = conn.Close()
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case preAuth <- struct{}{}:
|
||||
default:
|
||||
_ = conn.Close()
|
||||
continue
|
||||
}
|
||||
clients.Go(func() {
|
||||
client := &runtimeSOCKSConn{Conn: conn, preAuth: preAuth}
|
||||
defer client.ReleasePreAuth()
|
||||
defer conn.Close()
|
||||
if rt.serving() != active {
|
||||
return
|
||||
}
|
||||
// Cancellation must interrupt reads even before proxy authentication.
|
||||
closeOnStop := context.AfterFunc(rt.ctx, func() { _ = conn.Close() })
|
||||
defer closeOnStop()
|
||||
active.socks.ServeSOCKS(rt.ctx, client, active.creds)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type runtimeSOCKSConn struct {
|
||||
net.Conn
|
||||
preAuth chan struct{}
|
||||
}
|
||||
|
||||
// ReleasePreAuth is called by the synchronous handler after claiming a user
|
||||
// slot. The deferred call covers every earlier exit without a second release.
|
||||
func (c *runtimeSOCKSConn) ReleasePreAuth() {
|
||||
if c.preAuth != nil {
|
||||
<-c.preAuth
|
||||
c.preAuth = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *runtimeSOCKSConn) CloseWrite() error {
|
||||
if conn, ok := c.Conn.(interface{ CloseWrite() error }); ok {
|
||||
return conn.CloseWrite()
|
||||
}
|
||||
return errors.ErrUnsupported
|
||||
}
|
||||
|
||||
func proxyFormHandler(proxy ProxyLifecycle) func(http.ResponseWriter, *http.Request, int64) {
|
||||
return func(w http.ResponseWriter, r *http.Request, id int64) {
|
||||
u := r.URL
|
||||
|
||||
@@ -22,34 +22,49 @@ import (
|
||||
"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)
|
||||
func TestGatewayRuntimeBindFailure(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
port int
|
||||
}{
|
||||
{name: "API", port: 2},
|
||||
{name: "SOCKS", port: 3},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
occupied, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer occupied.Close()
|
||||
addresses := [3]string{"127.0.0.1:0", "127.0.0.1:0", "127.0.0.1:0"}
|
||||
addresses[tc.port-1] = occupied.Addr().String()
|
||||
var bound []string
|
||||
bindings := 0
|
||||
opts := RuntimeOptions{
|
||||
ProxyAddr: addresses[0],
|
||||
APIAddr: addresses[1],
|
||||
SOCKSAddr: addresses[2],
|
||||
Build: func(context.Context, RuntimeEndpoints) (RuntimeComponents, error) {
|
||||
t.Fatal("built components despite listener bind failure")
|
||||
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 err == nil {
|
||||
bound = append(bound, listener.Addr().String())
|
||||
}
|
||||
return listener, err
|
||||
})
|
||||
if err == nil || err.Error() != "could not bind gateway "+tc.name+" listener" || bindings != tc.port || len(bound) != tc.port-1 {
|
||||
t.Fatalf("did not reach %s bind and fail cleanly: %v, bindings=%d", tc.name, err, bindings)
|
||||
}
|
||||
for _, addr := range bound {
|
||||
assertRuntimeListenerClosed(t, addr)
|
||||
}
|
||||
})
|
||||
}
|
||||
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) {
|
||||
@@ -68,6 +83,7 @@ func TestGatewayRuntimePostgres(t *testing.T) {
|
||||
}
|
||||
assertRuntimeListenerClosed(t, first.api)
|
||||
assertRuntimeListenerClosed(t, first.proxy)
|
||||
assertRuntimeListenerClosed(t, first.socks)
|
||||
select {
|
||||
case <-components.endpoints:
|
||||
t.Fatal("components were built before schema was applied")
|
||||
@@ -82,6 +98,7 @@ func TestGatewayRuntimePostgres(t *testing.T) {
|
||||
}
|
||||
assertRuntimeListenerClosed(t, expired.api)
|
||||
assertRuntimeListenerClosed(t, expired.proxy)
|
||||
assertRuntimeListenerClosed(t, expired.socks)
|
||||
|
||||
second := startRuntimeTest(t, store, cfg, timing, components.build)
|
||||
assertRuntimeStarting(t, second, cfg)
|
||||
@@ -114,7 +131,7 @@ func TestGatewayRuntimePostgres(t *testing.T) {
|
||||
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 {
|
||||
if endpoint.Lease == nil || endpoint.APIAddr != first.api || endpoint.ProxyAddr != first.proxy || endpoint.SOCKSAddr != first.socks || endpoint.ProbeProxyAddr != first.proxy {
|
||||
t.Fatal("factory did not receive the active lease and bound listener addresses")
|
||||
}
|
||||
assertRuntimeAPI(t, first.api, cfg)
|
||||
@@ -137,6 +154,7 @@ func TestGatewayRuntimePostgres(t *testing.T) {
|
||||
}
|
||||
assertRuntimeListenerClosed(t, second.api)
|
||||
assertRuntimeListenerClosed(t, second.proxy)
|
||||
assertRuntimeListenerClosed(t, second.socks)
|
||||
assertRuntimeHTTP(t, first.api, http.MethodGet, "/readyz", "", http.StatusOK)
|
||||
|
||||
conn, reader := dialRuntimeWire(t, first.proxy)
|
||||
@@ -146,6 +164,7 @@ func TestGatewayRuntimePostgres(t *testing.T) {
|
||||
response.Body.Close()
|
||||
t.Fatalf("tunnel setup status = %d", response.StatusCode)
|
||||
}
|
||||
socksClients := fillRuntimeSOCKSBudget(t, first.socks, components.proxy, endpoint.Credentials)
|
||||
first.cancel()
|
||||
if err := first.wait(t); err != nil {
|
||||
t.Fatalf("graceful shutdown: %v", err)
|
||||
@@ -154,9 +173,16 @@ func TestGatewayRuntimePostgres(t *testing.T) {
|
||||
t.Fatalf("hijacked socket not closed on shutdown: %v", err)
|
||||
}
|
||||
waitRuntimeEvent(t, components.proxy.tunnelDone)
|
||||
for _, client := range socksClients {
|
||||
assertRuntimeSOCKSClosed(t, client)
|
||||
}
|
||||
if got := components.proxy.socksActive.Load(); got != 0 {
|
||||
t.Fatalf("runtime exited before %d SOCKS handlers drained", got)
|
||||
}
|
||||
waitRuntimeEvent(t, components.stopped)
|
||||
assertRuntimeListenerClosed(t, first.api)
|
||||
assertRuntimeListenerClosed(t, first.proxy)
|
||||
assertRuntimeListenerClosed(t, first.socks)
|
||||
assertRuntimeLeaseAvailable(t, store)
|
||||
})
|
||||
|
||||
@@ -176,6 +202,9 @@ func TestGatewayRuntimePostgres(t *testing.T) {
|
||||
instance := startRuntimeTest(t, store, cfg, lossTiming, components.build)
|
||||
waitRuntimeEvent(t, components.started)
|
||||
assertRuntimeHTTP(t, instance.api, http.MethodGet, "/readyz", "", http.StatusOK)
|
||||
socksClient, _ := dialRuntimeWire(t, instance.socks)
|
||||
defer socksClient.Close()
|
||||
waitRuntimeSOCKSEntry(t, components.proxy, (<-components.endpoints).Credentials)
|
||||
terminateRuntimeLease(t, store)
|
||||
if viaReady {
|
||||
assertRuntimeHTTP(t, instance.api, http.MethodGet, "/readyz", "", http.StatusServiceUnavailable)
|
||||
@@ -185,8 +214,10 @@ func TestGatewayRuntimePostgres(t *testing.T) {
|
||||
}
|
||||
waitRuntimeEvent(t, components.stopped)
|
||||
waitRuntimeEvent(t, components.proxy.closed)
|
||||
assertRuntimeSOCKSClosed(t, socksClient)
|
||||
assertRuntimeListenerClosed(t, instance.api)
|
||||
assertRuntimeListenerClosed(t, instance.proxy)
|
||||
assertRuntimeListenerClosed(t, instance.socks)
|
||||
assertRuntimeLeaseAvailable(t, store)
|
||||
})
|
||||
}
|
||||
@@ -334,10 +365,10 @@ func assertRuntimeLeaseAvailable(t *testing.T, store *db.DB) {
|
||||
}
|
||||
|
||||
type runtimeTestInstance struct {
|
||||
api, proxy string
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
err error // published by closing done
|
||||
api, proxy, socks 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 {
|
||||
@@ -348,10 +379,10 @@ func startRuntimeTest(t *testing.T, store *db.DB, cfg Config, timing runtimeTimi
|
||||
cancel()
|
||||
waitRuntimeEvent(t, instance.done)
|
||||
})
|
||||
addresses := make(chan string, 2)
|
||||
addresses := make(chan string, 3)
|
||||
go func() {
|
||||
defer close(instance.done)
|
||||
opts := RuntimeOptions{ProxyAddr: "127.0.0.1:0", APIAddr: "127.0.0.1:0", Build: build}
|
||||
opts := RuntimeOptions{ProxyAddr: "127.0.0.1:0", APIAddr: "127.0.0.1:0", SOCKSAddr: "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 {
|
||||
@@ -365,13 +396,13 @@ func startRuntimeTest(t *testing.T, store *db.DB, cfg Config, timing runtimeTimi
|
||||
case address := <-addresses:
|
||||
return address
|
||||
case <-instance.done:
|
||||
t.Fatalf("runtime exited before binding both listeners: %v", instance.err)
|
||||
t.Fatalf("runtime exited before binding all 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()
|
||||
instance.proxy, instance.api, instance.socks = readAddress(), readAddress(), readAddress()
|
||||
return instance
|
||||
}
|
||||
|
||||
@@ -410,7 +441,11 @@ func newRuntimeTestComponents() *runtimeTestComponents {
|
||||
endpoints: make(chan RuntimeEndpoints, 1),
|
||||
started: make(chan struct{}),
|
||||
stopped: make(chan struct{}),
|
||||
proxy: &runtimeTestProxy{closed: make(chan struct{}), tunnelDone: make(chan struct{})},
|
||||
proxy: &runtimeTestProxy{
|
||||
closed: make(chan struct{}),
|
||||
tunnelDone: make(chan struct{}),
|
||||
socksEntered: make(chan Credentials, maxSOCKSPreAuth+1),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -433,6 +468,8 @@ func (components *runtimeTestComponents) build(_ context.Context, endpoints Runt
|
||||
type runtimeTestProxy struct {
|
||||
closed, tunnelDone chan struct{}
|
||||
tunnel atomic.Bool
|
||||
socksEntered chan Credentials
|
||||
socksActive atomic.Int32
|
||||
}
|
||||
|
||||
func (p *runtimeTestProxy) ServeProxy(w http.ResponseWriter, r *http.Request, id int64) {
|
||||
@@ -458,6 +495,26 @@ func (p *runtimeTestProxy) ServeProxy(w http.ResponseWriter, r *http.Request, id
|
||||
<-p.closed
|
||||
}
|
||||
|
||||
func (p *runtimeTestProxy) ServeSOCKS(ctx context.Context, conn net.Conn, creds Credentials) {
|
||||
p.socksActive.Add(1)
|
||||
defer p.socksActive.Add(-1)
|
||||
select {
|
||||
case p.socksEntered <- creds:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
// A single test byte stands in for authentication. The real SOCKS wire
|
||||
// protocol is exercised separately; here the runtime must close the socket.
|
||||
var b [1]byte
|
||||
if _, err := io.ReadFull(conn, b[:]); err != nil {
|
||||
return
|
||||
}
|
||||
conn.(interface{ ReleasePreAuth() }).ReleasePreAuth()
|
||||
if _, err := conn.Write(b[:]); err == nil {
|
||||
_, _ = io.Copy(io.Discard, conn)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *runtimeTestProxy) Shutdown(ctx context.Context) error {
|
||||
close(p.closed)
|
||||
if p.tunnel.Load() {
|
||||
@@ -470,6 +527,59 @@ func (p *runtimeTestProxy) Shutdown(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func fillRuntimeSOCKSBudget(t *testing.T, addr string, proxy *runtimeTestProxy, creds Credentials) []net.Conn {
|
||||
t.Helper()
|
||||
clients := make([]net.Conn, 0, maxSOCKSPreAuth+1)
|
||||
for range maxSOCKSPreAuth {
|
||||
conn, _ := dialRuntimeWire(t, addr)
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
clients = append(clients, conn)
|
||||
waitRuntimeSOCKSEntry(t, proxy, creds)
|
||||
}
|
||||
overflow, _ := dialRuntimeWire(t, addr)
|
||||
defer overflow.Close()
|
||||
assertRuntimeSOCKSClosed(t, overflow)
|
||||
select {
|
||||
case <-proxy.socksEntered:
|
||||
t.Fatal("excess SOCKS connection reached the handler")
|
||||
default:
|
||||
}
|
||||
|
||||
// Once a worker becomes an active tunnel, another connection must be
|
||||
// admitted even though the tunnel is still open.
|
||||
if _, err := clients[0].Write([]byte{42}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ack [1]byte
|
||||
if _, err := io.ReadFull(clients[0], ack[:]); err != nil || ack[0] != 42 {
|
||||
t.Fatalf("test SOCKS authentication did not complete: %v", err)
|
||||
}
|
||||
replacement, _ := dialRuntimeWire(t, addr)
|
||||
t.Cleanup(func() { _ = replacement.Close() })
|
||||
waitRuntimeSOCKSEntry(t, proxy, creds)
|
||||
return append(clients, replacement)
|
||||
}
|
||||
|
||||
func waitRuntimeSOCKSEntry(t *testing.T, proxy *runtimeTestProxy, want Credentials) {
|
||||
t.Helper()
|
||||
select {
|
||||
case got := <-proxy.socksEntered:
|
||||
if got != want {
|
||||
t.Fatal("SOCKS handler did not receive the runtime credentials")
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("SOCKS connection did not reach the handler")
|
||||
}
|
||||
}
|
||||
|
||||
func assertRuntimeSOCKSClosed(t *testing.T, conn net.Conn) {
|
||||
t.Helper()
|
||||
var b [1]byte
|
||||
if n, err := conn.Read(b[:]); n != 0 || err == nil || errors.Is(err, os.ErrDeadlineExceeded) {
|
||||
t.Fatalf("SOCKS connection did not close: %d bytes, %v", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
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"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
socksVersion = 0x05
|
||||
socksPasswordMethod = 0x02
|
||||
socksNoMethod = 0xff
|
||||
socksAuthVersion = 0x01
|
||||
socksAuthFailed = 0x01
|
||||
|
||||
socksCmdConnect = 0x01
|
||||
socksIPv4 = 0x01
|
||||
socksDomain = 0x03
|
||||
socksIPv6 = 0x04
|
||||
|
||||
socksSucceeded = 0x00
|
||||
socksGeneralFailure = 0x01
|
||||
socksNotAllowed = 0x02
|
||||
socksCommandUnsupported = 0x07
|
||||
socksAddressUnsupported = 0x08
|
||||
)
|
||||
|
||||
// ServeSOCKS serves one authenticated SOCKS5 CONNECT and owns conn until it closes.
|
||||
func (p *ForwardProxy) ServeSOCKS(ctx context.Context, conn net.Conn, creds Credentials) {
|
||||
if !p.begin() {
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
var admitted, handedToRelay bool
|
||||
defer func() {
|
||||
if !handedToRelay {
|
||||
_ = conn.Close()
|
||||
}
|
||||
if admitted {
|
||||
<-p.users
|
||||
}
|
||||
p.end()
|
||||
}()
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
stopLifetime := context.AfterFunc(p.lifetime, cancel)
|
||||
defer stopLifetime()
|
||||
stopHandshake := context.AfterFunc(ctx, func() { _ = conn.Close() })
|
||||
defer stopHandshake()
|
||||
if ctx.Err() != nil || conn.SetDeadline(time.Now().Add(p.timing.setup)) != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if !negotiateSOCKS(conn) {
|
||||
return
|
||||
}
|
||||
writer := tunnelWriter{dst: conn}
|
||||
id, ok := authenticateSOCKS(conn, creds)
|
||||
if !ok {
|
||||
_, _ = writer.Write([]byte{socksAuthVersion, socksAuthFailed})
|
||||
return
|
||||
}
|
||||
select {
|
||||
case p.users <- struct{}{}:
|
||||
admitted = true
|
||||
default:
|
||||
_, _ = writer.Write([]byte{socksAuthVersion, socksAuthFailed})
|
||||
return
|
||||
}
|
||||
if admission, ok := conn.(interface{ ReleasePreAuth() }); ok {
|
||||
admission.ReleasePreAuth()
|
||||
}
|
||||
if _, err := writer.Write([]byte{socksAuthVersion, 0}); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
authority, port, reply := readSOCKSConnect(conn)
|
||||
if reply != socksSucceeded {
|
||||
_ = writeSOCKSReply(writer, reply)
|
||||
return
|
||||
}
|
||||
// Build the same destination shape as HTTP forwarding. ResolveRequest
|
||||
// applies the current policy and returns the pinned address to open.
|
||||
method := http.MethodConnect
|
||||
scheme := ""
|
||||
if port == 80 {
|
||||
method = http.MethodGet
|
||||
scheme = "http"
|
||||
}
|
||||
request := &http.Request{
|
||||
Method: method, ProtoMajor: 1, ProtoMinor: 1, Host: authority,
|
||||
URL: &url.URL{Scheme: scheme, Host: authority},
|
||||
}
|
||||
upstream, status := p.open(ctx, request, id, 0)
|
||||
writeErr := conn.SetWriteDeadline(time.Now().Add(p.timing.setup))
|
||||
if status != 0 {
|
||||
reply = socksGeneralFailure
|
||||
if status == http.StatusForbidden {
|
||||
reply = socksNotAllowed
|
||||
}
|
||||
}
|
||||
if writeErr == nil {
|
||||
writeErr = writeSOCKSReply(writer, reply)
|
||||
}
|
||||
if status != 0 {
|
||||
return
|
||||
}
|
||||
if writeErr != nil || conn.SetDeadline(time.Time{}) != nil {
|
||||
_ = upstream.Close()
|
||||
return
|
||||
}
|
||||
// Wire reads use exact lengths; relay can read the socket directly,
|
||||
// including bytes already sent alongside CONNECT.
|
||||
stopHandshake()
|
||||
handedToRelay = true
|
||||
relayConnect(ctx, conn, conn, upstream, p.timing.idle, p.timing.halfCloseGrace)
|
||||
}
|
||||
|
||||
func negotiateSOCKS(conn net.Conn) bool {
|
||||
var header [2]byte
|
||||
if _, err := io.ReadFull(conn, header[:]); err != nil || header[0] != socksVersion {
|
||||
return false
|
||||
}
|
||||
var methods [255]byte
|
||||
offered := methods[:header[1]]
|
||||
if _, err := io.ReadFull(conn, offered); err != nil {
|
||||
return false
|
||||
}
|
||||
method := byte(socksNoMethod)
|
||||
if slices.Contains(offered, socksPasswordMethod) {
|
||||
method = socksPasswordMethod
|
||||
}
|
||||
_, err := (tunnelWriter{dst: conn}).Write([]byte{socksVersion, method})
|
||||
return err == nil && method == socksPasswordMethod
|
||||
}
|
||||
|
||||
func authenticateSOCKS(r io.Reader, creds Credentials) (int64, bool) {
|
||||
var header [2]byte
|
||||
if _, err := io.ReadFull(r, header[:]); err != nil {
|
||||
return 0, false
|
||||
}
|
||||
var credentials [255 + 1 + 255]byte
|
||||
userLen := int(header[1])
|
||||
if _, err := io.ReadFull(r, credentials[:userLen+1]); err != nil {
|
||||
return 0, false
|
||||
}
|
||||
passLen := int(credentials[userLen])
|
||||
password := credentials[userLen+1 : userLen+1+passLen]
|
||||
if _, err := io.ReadFull(r, password); err != nil || header[0] != socksAuthVersion || userLen == 0 || passLen == 0 {
|
||||
return 0, false
|
||||
}
|
||||
return creds.authenticateNode(credentials[:userLen], password)
|
||||
}
|
||||
|
||||
func readSOCKSConnect(r io.Reader) (string, uint16, byte) {
|
||||
var header [4]byte
|
||||
if _, err := io.ReadFull(r, header[:]); err != nil {
|
||||
return "", 0, socksGeneralFailure
|
||||
}
|
||||
var address [255 + 2]byte // address followed by the network-order port
|
||||
var n int
|
||||
switch header[3] {
|
||||
case socksIPv4:
|
||||
n = 4
|
||||
case socksIPv6:
|
||||
n = 16
|
||||
case socksDomain:
|
||||
if _, err := io.ReadFull(r, address[:1]); err != nil {
|
||||
return "", 0, socksGeneralFailure
|
||||
}
|
||||
n = int(address[0])
|
||||
default:
|
||||
return "", 0, socksAddressUnsupported
|
||||
}
|
||||
if _, err := io.ReadFull(r, address[:n+2]); err != nil {
|
||||
return "", 0, socksGeneralFailure
|
||||
}
|
||||
if header[0] != socksVersion || header[2] != 0 {
|
||||
return "", 0, socksGeneralFailure
|
||||
}
|
||||
if header[1] != socksCmdConnect {
|
||||
return "", 0, socksCommandUnsupported
|
||||
}
|
||||
port := binary.BigEndian.Uint16(address[n : n+2])
|
||||
if port == 0 {
|
||||
return "", 0, socksGeneralFailure
|
||||
}
|
||||
if header[3] == socksDomain {
|
||||
host, ok := normalizeGatewayDNSName(string(address[:n]))
|
||||
if !ok {
|
||||
return "", 0, socksGeneralFailure
|
||||
}
|
||||
return net.JoinHostPort(host, strconv.Itoa(int(port))), port, socksSucceeded
|
||||
}
|
||||
ip, _ := netip.AddrFromSlice(address[:n])
|
||||
if ip.Is4In6() {
|
||||
return "", 0, socksNotAllowed
|
||||
}
|
||||
return netip.AddrPortFrom(ip, port).String(), port, socksSucceeded
|
||||
}
|
||||
|
||||
func writeSOCKSReply(w tunnelWriter, reply byte) error {
|
||||
// The tunneled protocol does not expose the address bound by the peer.
|
||||
_, err := w.Write([]byte{socksVersion, reply, 0, socksIPv4, 0, 0, 0, 0, 0, 0})
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"sync/atomic"
|
||||
"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/upstream"
|
||||
)
|
||||
|
||||
func socksTestCredentials(t *testing.T) Credentials {
|
||||
return identityTestCredentials(t, "838e3104-6966-4644-b625-932c6e6f62a9", [32]byte{1})
|
||||
}
|
||||
|
||||
func socksTestPipe(t *testing.T, ctx context.Context, p *ForwardProxy, creds Credentials, released chan<- struct{}) (net.Conn, <-chan struct{}) {
|
||||
t.Helper()
|
||||
client, server := net.Pipe()
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
if err := client.SetDeadline(time.Now().Add(forwardTestDeadline)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if released != nil {
|
||||
server = socksTestAdmissionConn{server, released}
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
p.ServeSOCKS(ctx, server, creds)
|
||||
}()
|
||||
return client, done
|
||||
}
|
||||
|
||||
type socksTestAdmissionConn struct {
|
||||
net.Conn
|
||||
released chan<- struct{}
|
||||
}
|
||||
|
||||
func (c socksTestAdmissionConn) ReleasePreAuth() { c.released <- struct{}{} }
|
||||
|
||||
func socksTestWrite(t *testing.T, writer io.Writer, frame []byte) {
|
||||
t.Helper()
|
||||
if n, err := writer.Write(frame); err != nil || n != len(frame) {
|
||||
t.Fatalf("write: %d/%d bytes: %v", n, len(frame), err)
|
||||
}
|
||||
}
|
||||
|
||||
func socksTestExpect(t *testing.T, reader io.Reader, want ...byte) {
|
||||
t.Helper()
|
||||
got := make([]byte, len(want))
|
||||
if _, err := io.ReadFull(reader, got); err != nil || !bytes.Equal(got, want) {
|
||||
t.Fatalf("reply = % x, %v; want % x", got, err, want)
|
||||
}
|
||||
}
|
||||
|
||||
func socksTestEOF(t *testing.T, reader io.Reader) {
|
||||
t.Helper()
|
||||
var b [1]byte
|
||||
if n, err := reader.Read(b[:]); n != 0 || err != io.EOF {
|
||||
t.Fatalf("expected closed connection, read %d bytes: %v", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func socksTestAuthenticate(t *testing.T, conn net.Conn, user, password string, status byte) {
|
||||
t.Helper()
|
||||
socksTestWrite(t, conn, []byte{5, 3, 0, 1, 2})
|
||||
socksTestExpect(t, conn, 5, 2)
|
||||
packet := append([]byte{1, byte(len(user))}, user...)
|
||||
packet = append(packet, byte(len(password)))
|
||||
packet = append(packet, password...)
|
||||
socksTestWrite(t, conn, packet)
|
||||
socksTestExpect(t, conn, 1, status)
|
||||
}
|
||||
|
||||
func socksTestDomain(host string, port uint16) []byte {
|
||||
packet := append([]byte{5, 1, 0, 3, byte(len(host))}, host...)
|
||||
return append(packet, byte(port>>8), byte(port))
|
||||
}
|
||||
|
||||
func socksTestExpectReply(t *testing.T, conn net.Conn, status byte) {
|
||||
t.Helper()
|
||||
socksTestExpect(t, conn, 5, status, 0, 1, 0, 0, 0, 0, 0, 0)
|
||||
}
|
||||
|
||||
func TestSOCKSRejectsInvalidWireAndCredentials(t *testing.T) {
|
||||
creds := socksTestCredentials(t)
|
||||
var lookups atomic.Int32
|
||||
p := NewForwardProxy(forwardTestStore{ready: func(int64) (*db.GatewayNode, error) {
|
||||
lookups.Add(1)
|
||||
return nil, nil
|
||||
}}, NewRoutePolicy(Config{}), nil, nil)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
greeting []byte
|
||||
methodReply []byte
|
||||
}{
|
||||
{"SOCKS4", []byte{4, 1}, nil},
|
||||
{"no methods", []byte{5, 0}, []byte{5, 255}},
|
||||
{"no-auth and GSSAPI only", []byte{5, 2, 0, 1}, []byte{5, 255}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c, done := socksTestPipe(t, context.Background(), p, creds, nil)
|
||||
socksTestWrite(t, c, tc.greeting)
|
||||
socksTestExpect(t, c, tc.methodReply...)
|
||||
socksTestEOF(t, c)
|
||||
forwardTestReceive(t, done)
|
||||
})
|
||||
}
|
||||
for _, tc := range []struct{ name, user, password string }{
|
||||
{"empty user", "", creds.Password(42)},
|
||||
{"empty password", "node-42", ""},
|
||||
{"wrong password", "node-42", creds.Password(7)},
|
||||
{"noncanonical node ID", "node-042", creds.Password(42)},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c, done := socksTestPipe(t, context.Background(), p, creds, nil)
|
||||
socksTestAuthenticate(t, c, tc.user, tc.password, 1)
|
||||
socksTestEOF(t, c)
|
||||
forwardTestReceive(t, done)
|
||||
})
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
packet []byte
|
||||
status byte
|
||||
}{
|
||||
{"BIND", []byte{5, 2, 0, 1, 1, 1, 1, 1, 0, 80}, 7},
|
||||
{"UDP ASSOCIATE", []byte{5, 3, 0, 1, 1, 1, 1, 1, 0, 80}, 7},
|
||||
{"unknown address type", []byte{5, 1, 0, 2}, 8},
|
||||
{"invalid request version", []byte{4, 1, 0, 1, 1, 1, 1, 1, 0, 80}, 1},
|
||||
{"reserved field", []byte{5, 1, 1, 1, 1, 1, 1, 1, 0, 80}, 1},
|
||||
{"empty domain", socksTestDomain("", 80), 1},
|
||||
{"authority disguised as domain", socksTestDomain("[2606:4700::1111]", 443), 1},
|
||||
{"zero port", socksTestDomain("app.operator.test", 0), 1},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c, done := socksTestPipe(t, context.Background(), p, creds, nil)
|
||||
socksTestAuthenticate(t, c, "node-42", creds.Password(42), 0)
|
||||
socksTestWrite(t, c, tc.packet)
|
||||
socksTestExpectReply(t, c, tc.status)
|
||||
socksTestEOF(t, c)
|
||||
forwardTestReceive(t, done)
|
||||
})
|
||||
}
|
||||
if got := lookups.Load(); got != 0 {
|
||||
t.Fatalf("invalid or unauthorized traffic performed %d node lookups", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSOCKSCurrentPolicyPinsDestinationAndSelectedNode(t *testing.T) {
|
||||
creds := socksTestCredentials(t)
|
||||
policy := newRouteTestPolicy(t, routeTestConfig())
|
||||
policy.resolveIP = func(_ context.Context, name string) ([]netip.Addr, error) {
|
||||
public := netip.MustParseAddr("1.1.1.1")
|
||||
switch name {
|
||||
case "app.operator.test.", "new.operator.test.":
|
||||
return []netip.Addr{public}, nil
|
||||
case "mixed.operator.test.":
|
||||
return []netip.Addr{public, netip.MustParseAddr("10.0.0.1")}, nil
|
||||
default:
|
||||
return nil, errors.New("unexpected DNS authority")
|
||||
}
|
||||
}
|
||||
var enabled atomic.Bool
|
||||
store := forwardTestStore{ready: func(id int64) (*db.GatewayNode, error) {
|
||||
node := forwardTestNode(id, 1)
|
||||
node.AllowAllSites = enabled.Load()
|
||||
return node, nil
|
||||
}}
|
||||
var routes []string
|
||||
p := NewForwardProxy(store, policy, forwardTestDial(func(_ context.Context, up *upstream.Upstream, dest string) (net.Conn, error) {
|
||||
routes = append(routes, up.Address()+" -> "+dest)
|
||||
return nil, errors.New("fixture dial failure")
|
||||
}), nil)
|
||||
ipv6 := netip.MustParseAddr("2606:4700::1111").As16()
|
||||
mapped := netip.MustParseAddr("::ffff:1.1.1.1").As16()
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
allow bool
|
||||
packet []byte
|
||||
status byte
|
||||
dial string
|
||||
}{
|
||||
{"explicit host and port", false, socksTestDomain("App.OPERATOR.test.", 80), 1, "1.1.1.1:80"},
|
||||
{"unknown host disabled", false, socksTestDomain("new.operator.test", 80), 2, ""},
|
||||
{"unknown host on HTTP port enabled", true, socksTestDomain("new.operator.test", 80), 1, "1.1.1.1:80"},
|
||||
{"unknown host on HTTPS port enabled", true, socksTestDomain("new.operator.test", 443), 1, "1.1.1.1:443"},
|
||||
{"unlisted port remains denied", true, socksTestDomain("new.operator.test", 8080), 2, ""},
|
||||
{"mixed DNS is denied", true, socksTestDomain("mixed.operator.test", 443), 2, ""},
|
||||
{"public IPv4", true, []byte{5, 1, 0, 1, 1, 1, 1, 1, 0, 80}, 1, "1.1.1.1:80"},
|
||||
{"loopback IPv4", true, []byte{5, 1, 0, 1, 127, 0, 0, 1, 0, 80}, 2, ""},
|
||||
{"public IPv6", true, append(append([]byte{5, 1, 0, 4}, ipv6[:]...), 1, 187), 1, "[2606:4700::1111]:443"},
|
||||
{"IPv4-mapped IPv6", true, append(append([]byte{5, 1, 0, 4}, mapped[:]...), 1, 187), 2, ""},
|
||||
{"disabling takes effect", false, socksTestDomain("new.operator.test", 443), 2, ""},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
enabled.Store(tc.allow)
|
||||
routes = routes[:0]
|
||||
c, done := socksTestPipe(t, context.Background(), p, creds, nil)
|
||||
socksTestAuthenticate(t, c, "node-42", creds.Password(42), 0)
|
||||
socksTestWrite(t, c, tc.packet)
|
||||
socksTestExpectReply(t, c, tc.status)
|
||||
forwardTestReceive(t, done)
|
||||
if tc.dial == "" {
|
||||
if len(routes) != 0 {
|
||||
t.Fatalf("denied destination reached dialer: %v", routes)
|
||||
}
|
||||
} else if want := "peer42.fixture:443 -> " + tc.dial; len(routes) != 1 || routes[0] != want {
|
||||
t.Fatalf("routes = %v; want [%s]", routes, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSOCKSUpstreamCIDRRestriction(t *testing.T) {
|
||||
creds := socksTestCredentials(t)
|
||||
policy := newRouteTestPolicy(t, routeTestConfig())
|
||||
var upstreamLookups, sockets atomic.Int32
|
||||
policy.resolveIP = func(_ context.Context, name string) ([]netip.Addr, error) {
|
||||
if name == "peer42.fixture." {
|
||||
upstreamLookups.Add(1)
|
||||
}
|
||||
return []netip.Addr{netip.MustParseAddr("1.1.1.1")}, nil
|
||||
}
|
||||
policy.openTCP = func(context.Context, string, string) (net.Conn, error) {
|
||||
sockets.Add(1)
|
||||
return nil, errors.New("unexpected physical dial")
|
||||
}
|
||||
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
p := NewForwardProxy(forwardTestStore{ready: forwardTestReady}, policy, dialer.NewDispatcher(log, policy.DialUpstream), nil)
|
||||
c, done := socksTestPipe(t, context.Background(), p, creds, nil)
|
||||
socksTestAuthenticate(t, c, "node-42", creds.Password(42), 0)
|
||||
socksTestWrite(t, c, socksTestDomain("app.operator.test", 80))
|
||||
socksTestExpectReply(t, c, 1)
|
||||
forwardTestReceive(t, done)
|
||||
if got, opened := upstreamLookups.Load(), sockets.Load(); got != 1 || opened != 0 {
|
||||
t.Fatalf("upstream DNS lookups = %d, sockets = %d; want 1, 0", got, opened)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSOCKSSharedUserBudgetReleased(t *testing.T) {
|
||||
creds := socksTestCredentials(t)
|
||||
p := NewForwardProxy(forwardTestStore{}, NewRoutePolicy(Config{}), nil, nil)
|
||||
p.users = make(chan struct{}, 1)
|
||||
released := make(chan struct{}, 1)
|
||||
c, done := socksTestPipe(t, context.Background(), p, creds, released)
|
||||
socksTestAuthenticate(t, c, "node-42", creds.Password(42), 0)
|
||||
forwardTestReceive(t, released)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
p.ServeProxy(w, httptest.NewRequest(http.MethodGet, "http://app.operator.test/", nil), 42)
|
||||
if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
|
||||
t.Fatalf("HTTP did not share the saturated SOCKS budget: %d", w.Code)
|
||||
}
|
||||
second, secondDone := socksTestPipe(t, context.Background(), p, creds, released)
|
||||
socksTestAuthenticate(t, second, "node-42", creds.Password(42), 1)
|
||||
forwardTestReceive(t, secondDone)
|
||||
select {
|
||||
case <-released:
|
||||
t.Fatal("saturated connection was admitted")
|
||||
default:
|
||||
}
|
||||
|
||||
socksTestWrite(t, c, []byte{5, 1, 0, 2})
|
||||
socksTestExpectReply(t, c, 8)
|
||||
forwardTestReceive(t, done)
|
||||
|
||||
third, thirdDone := socksTestPipe(t, context.Background(), p, creds, released)
|
||||
socksTestAuthenticate(t, third, "node-42", creds.Password(42), 0)
|
||||
forwardTestReceive(t, released)
|
||||
socksTestWrite(t, third, socksTestDomain("app.operator.test", 80))
|
||||
socksTestExpectReply(t, third, 1) // Correct credentials, no current ready node.
|
||||
forwardTestReceive(t, thirdDone)
|
||||
}
|
||||
|
||||
func socksTestTCPPair(t *testing.T) (client, server *net.TCPConn) {
|
||||
t.Helper()
|
||||
listener, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
client, _ = forwardTestTCP(t, listener.Addr().String())
|
||||
accepted, err := listener.Accept()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = accepted.Close() })
|
||||
server = accepted.(*net.TCPConn)
|
||||
if err := server.SetDeadline(time.Now().Add(forwardTestDeadline)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return client, server
|
||||
}
|
||||
|
||||
func TestSOCKSTCPConnectEarlyBytesAndHalfClose(t *testing.T) {
|
||||
creds := socksTestCredentials(t)
|
||||
client, server := socksTestTCPPair(t)
|
||||
tunnel, peer := socksTestTCPPair(t)
|
||||
p := newForwardTestProxy(forwardTestStore{ready: forwardTestReady}, func(context.Context, *upstream.Upstream, string) (net.Conn, error) {
|
||||
return tunnel, nil
|
||||
}, nil, "1.1.1.1:443")
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
p.ServeSOCKS(context.Background(), server, creds)
|
||||
}()
|
||||
socksTestAuthenticate(t, client, "node-42", creds.Password(42), 0)
|
||||
const payload = "early tunnel data\x00\xff"
|
||||
socksTestWrite(t, client, append(socksTestDomain("app.operator.test", 443), payload...))
|
||||
if err := client.CloseWrite(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
socksTestExpectReply(t, client, 0)
|
||||
if got, err := io.ReadAll(peer); err != nil || string(got) != payload {
|
||||
t.Fatalf("peer read %q, %v", got, err)
|
||||
}
|
||||
const response = "received FIN before replying"
|
||||
socksTestWrite(t, peer, []byte(response))
|
||||
if err := peer.CloseWrite(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := io.ReadAll(client); err != nil || string(got) != response {
|
||||
t.Fatalf("client read %q, %v", got, err)
|
||||
}
|
||||
forwardTestReceive(t, done)
|
||||
if len(p.users) != 0 {
|
||||
t.Fatal("relay did not release user slot")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSOCKSStopAndHandshakeDeadline(t *testing.T) {
|
||||
creds := socksTestCredentials(t)
|
||||
t.Run("stalled handshake", func(t *testing.T) {
|
||||
p := NewForwardProxy(forwardTestStore{}, NewRoutePolicy(Config{}), nil, nil)
|
||||
p.timing.setup = 25 * time.Millisecond
|
||||
client, done := socksTestPipe(t, context.Background(), p, creds, nil)
|
||||
socksTestEOF(t, client)
|
||||
forwardTestReceive(t, done)
|
||||
})
|
||||
t.Run("caller cancellation while awaiting credentials", func(t *testing.T) {
|
||||
p := NewForwardProxy(forwardTestStore{}, NewRoutePolicy(Config{}), nil, nil)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
client, done := socksTestPipe(t, ctx, p, creds, nil)
|
||||
socksTestWrite(t, client, []byte{5, 1, 2})
|
||||
socksTestExpect(t, client, 5, 2)
|
||||
cancel()
|
||||
socksTestEOF(t, client)
|
||||
forwardTestReceive(t, done)
|
||||
})
|
||||
t.Run("shutdown drains tunnel and handshake", func(t *testing.T) {
|
||||
tunnel, peer := net.Pipe()
|
||||
defer peer.Close()
|
||||
if err := peer.SetDeadline(time.Now().Add(forwardTestDeadline)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := newForwardTestProxy(forwardTestStore{ready: forwardTestReady}, func(context.Context, *upstream.Upstream, string) (net.Conn, error) {
|
||||
return tunnel, nil
|
||||
}, nil, "1.1.1.1:443")
|
||||
client, done := socksTestPipe(t, context.Background(), p, creds, nil)
|
||||
socksTestAuthenticate(t, client, "node-42", creds.Password(42), 0)
|
||||
socksTestWrite(t, client, socksTestDomain("app.operator.test", 443))
|
||||
socksTestExpectReply(t, client, 0)
|
||||
stalled, stalledDone := socksTestPipe(t, context.Background(), p, creds, nil)
|
||||
socksTestWrite(t, stalled, []byte{5, 1, 2})
|
||||
socksTestExpect(t, stalled, 5, 2)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), forwardTestDeadline)
|
||||
defer cancel()
|
||||
if err := p.Shutdown(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
socksTestEOF(t, client)
|
||||
socksTestEOF(t, peer)
|
||||
socksTestEOF(t, stalled)
|
||||
forwardTestReceive(t, done)
|
||||
forwardTestReceive(t, stalledDone)
|
||||
if len(p.users) != 0 {
|
||||
t.Fatal("shutdown did not release user slot")
|
||||
}
|
||||
|
||||
rejected, rejectedDone := socksTestPipe(t, context.Background(), p, creds, nil)
|
||||
socksTestEOF(t, rejected)
|
||||
forwardTestReceive(t, rejectedDone)
|
||||
})
|
||||
}
|
||||
@@ -22,6 +22,9 @@ func assertRuntimeStarting(t *testing.T, run *runtimeTestInstance, cfg Config) {
|
||||
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)
|
||||
conn, _ := dialRuntimeWire(t, run.socks)
|
||||
defer conn.Close()
|
||||
assertRuntimeSOCKSClosed(t, conn)
|
||||
}
|
||||
|
||||
func assertRuntimeAPI(t *testing.T, api string, cfg Config) {
|
||||
|
||||
@@ -180,9 +180,11 @@ 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.
|
||||
-- only its runtime and health. The views expose no historical rows or unrelated settings.
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO settings (key, value) VALUES ('gateway_check_interval_minutes', '20')
|
||||
INSERT INTO settings (key, value) VALUES
|
||||
('gateway_check_interval_minutes', '20'),
|
||||
('gateway_allow_all_sites', 'false')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
CREATE OR REPLACE VIEW gateway_current_session WITH (security_barrier = true) AS
|
||||
@@ -193,7 +195,9 @@ 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
|
||||
sp.country, sp.exit_ip, sp.speed_mbps,
|
||||
COALESCE((SELECT value COLLATE "C" = 'true' FROM settings
|
||||
WHERE key = 'gateway_allow_all_sites'), false) AS allow_all_sites
|
||||
FROM check_sessions cs
|
||||
JOIN session_proxies sp ON sp.session_id = cs.id
|
||||
WHERE cs.is_current AND cs.status = 'completed';
|
||||
|
||||
@@ -249,7 +249,7 @@ dock 12 run "${common[@]}" --name "$gateway" --ip "$prefix.20" --cpus 0.50 --mem
|
||||
"$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'
|
||||
phase 'publishing four candidates and verifying exported HTTP, CONNECT and SOCKS 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
|
||||
|
||||
@@ -277,3 +277,8 @@ for i in "${!peers[@]}"; do start_peer "$i"; done
|
||||
fixture_run peers-ready
|
||||
restart_gateway
|
||||
fixture_run snapshot
|
||||
|
||||
phase 'checking immediate withdrawal of a healthy node without failing over'
|
||||
psql_admin -q -c 'DELETE FROM session_proxies WHERE session_id = 1 AND proxy_id = 1' \
|
||||
>/dev/null 2>&1 || die 'cannot remove the synthetic node membership'
|
||||
fixture_run removed-route
|
||||
@@ -17,6 +17,13 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type proxyMode string
|
||||
|
||||
const (
|
||||
httpProxy proxyMode = "http"
|
||||
socksProxy proxyMode = "socks5h"
|
||||
)
|
||||
|
||||
type catalogPayload struct {
|
||||
SessionID *int64 `json:"session_id"`
|
||||
FinishedAt time.Time `json:"session_finished_at"`
|
||||
@@ -40,7 +47,7 @@ type catalogItem struct {
|
||||
CheckedAt time.Time `json:"checked_at"`
|
||||
}
|
||||
|
||||
func (c checkClient) checkReadyCatalog(ctx context.Context) ([]string, error) {
|
||||
func (c checkClient) checkReadyCatalog(ctx context.Context, mode proxyMode) ([]string, error) {
|
||||
all := []int{0, 1, 2, 3}
|
||||
for _, selection := range []struct {
|
||||
query url.Values
|
||||
@@ -49,14 +56,14 @@ func (c checkClient) checkReadyCatalog(ctx context.Context) ([]string, error) {
|
||||
{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 {
|
||||
if _, err := c.checkCatalog(ctx, mode, 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)
|
||||
selected, err := c.checkCatalog(ctx, mode, query, []int{i}, true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s selection: %w", peer.protocol, err)
|
||||
}
|
||||
@@ -65,12 +72,12 @@ func (c checkClient) checkReadyCatalog(ctx context.Context) ([]string, error) {
|
||||
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)
|
||||
func (c checkClient) checkCatalog(ctx context.Context, mode proxyMode, filter url.Values, ids []int, hasSession bool) ([]string, error) {
|
||||
result, err := c.readCatalog(ctx, mode, filter, ids, hasSession)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := c.catalogResponse(ctx, filter, "csv", "text/csv; charset=utf-8")
|
||||
data, err := c.catalogResponse(ctx, mode, filter, "csv", "text/csv; charset=utf-8")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -78,7 +85,7 @@ func (c checkClient) checkCatalog(ctx context.Context, filter url.Values, ids []
|
||||
return nil, err
|
||||
}
|
||||
for _, format := range []string{"txt", "proxy-url-list-txt"} {
|
||||
data, err := c.catalogResponse(ctx, filter, format, "text/plain; charset=utf-8")
|
||||
data, err := c.catalogResponse(ctx, mode, filter, format, "text/plain; charset=utf-8")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -93,7 +100,7 @@ func (c checkClient) checkCatalog(ctx context.Context, filter url.Values, ids []
|
||||
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 {
|
||||
} else if u, err := c.parseLink(mode, ids[i], line); err != nil || u.String() != item.URL {
|
||||
return nil, errors.New("proxy URL list differs from JSON selection")
|
||||
}
|
||||
}
|
||||
@@ -119,11 +126,14 @@ func textRecords(data []byte, want int) ([]string, error) {
|
||||
return lines, nil
|
||||
}
|
||||
|
||||
func (c checkClient) catalogResponse(ctx context.Context, filter url.Values, format, mediaType string) ([]byte, error) {
|
||||
func (c checkClient) catalogResponse(ctx context.Context, mode proxyMode, filter url.Values, format, mediaType string) ([]byte, error) {
|
||||
query := url.Values{"format": {format}}
|
||||
for key, values := range filter {
|
||||
query[key] = values
|
||||
}
|
||||
if mode == socksProxy {
|
||||
query.Set("proxy_type", "socks5")
|
||||
}
|
||||
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)
|
||||
@@ -131,9 +141,9 @@ func (c checkClient) catalogResponse(ctx context.Context, filter url.Values, for
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func (c checkClient) readCatalog(ctx context.Context, filter url.Values, ids []int, hasSession bool) (catalogPayload, error) {
|
||||
func (c checkClient) readCatalog(ctx context.Context, mode proxyMode, filter url.Values, ids []int, hasSession bool) (catalogPayload, error) {
|
||||
var result catalogPayload
|
||||
body, err := c.catalogResponse(ctx, filter, "json", "application/json")
|
||||
body, err := c.catalogResponse(ctx, mode, filter, "json", "application/json")
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
@@ -147,12 +157,12 @@ func (c checkClient) readCatalog(ctx context.Context, filter url.Values, ids []i
|
||||
}
|
||||
for pos, i := range ids {
|
||||
item := result.Items[pos]
|
||||
u, err := c.parseLink(i, item.URL)
|
||||
u, err := c.parseLink(mode, 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 ||
|
||||
if item.ID != strconv.Itoa(i+1) || item.Host != c.ip(gatewayIP) || strconv.Itoa(item.Port) != u.Port() ||
|
||||
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) {
|
||||
@@ -162,9 +172,13 @@ func (c checkClient) readCatalog(ctx context.Context, filter url.Values, ids []i
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c checkClient) parseLink(i int, link string) (*url.URL, error) {
|
||||
func (c checkClient) parseLink(mode proxyMode, i int, link string) (*url.URL, error) {
|
||||
port := proxyPort
|
||||
if mode == socksProxy {
|
||||
port = socksPort
|
||||
}
|
||||
u, err := url.Parse(link)
|
||||
if err != nil || u.Scheme != "http" || u.Host != c.addr(gatewayIP, proxyPort) ||
|
||||
if err != nil || u.Scheme != string(mode) || u.Host != c.addr(gatewayIP, port) ||
|
||||
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)
|
||||
|
||||
@@ -39,6 +39,7 @@ type statusPayload struct {
|
||||
type baseline struct {
|
||||
LastSuccess time.Time `json:"last_success"`
|
||||
URLs []string `json:"urls"`
|
||||
SOCKSURLs []string `json:"socks_urls"`
|
||||
}
|
||||
|
||||
func (f fixture) verify(ctx context.Context, mode string) error {
|
||||
@@ -64,8 +65,12 @@ func (f fixture) verify(ctx context.Context, mode string) error {
|
||||
if _, err := c.wait(ctx, 0, 0, time.Time{}); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := c.checkCatalog(ctx, nil, nil, false)
|
||||
return err
|
||||
for _, mode := range []proxyMode{httpProxy, socksProxy} {
|
||||
if _, err := c.checkCatalog(ctx, mode, nil, nil, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const snapshotFile = "links.json"
|
||||
@@ -73,7 +78,8 @@ func (f fixture) verify(ctx context.Context, mode string) error {
|
||||
data, err := f.read(snapshotFile)
|
||||
switch {
|
||||
case err == nil:
|
||||
if json.Unmarshal(data, &previous) != nil || len(previous.URLs) != len(peers) || previous.LastSuccess.IsZero() {
|
||||
if json.Unmarshal(data, &previous) != nil || len(previous.URLs) != len(peers) ||
|
||||
len(previous.SOCKSURLs) != len(peers) || previous.LastSuccess.IsZero() {
|
||||
return errors.New("invalid fixture link baseline")
|
||||
}
|
||||
case errors.Is(err, os.ErrNotExist) && mode == "verify":
|
||||
@@ -86,43 +92,68 @@ func (f fixture) verify(ctx context.Context, mode string) error {
|
||||
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)
|
||||
if err := c.checkSOCKSRejection(ctx, 0, previous.SOCKSURLs[0], socksGeneralFailure); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.checkReadyRoutes(ctx, 1, previous.URLs[1], previous.SOCKSURLs[1])
|
||||
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 _, mode := range []proxyMode{httpProxy, socksProxy} {
|
||||
if _, err := c.checkCatalog(ctx, mode, 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
|
||||
}
|
||||
if err := c.checkSOCKSRejection(ctx, i, previous.SOCKSURLs[i], socksGeneralFailure); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
case "removed-route":
|
||||
for _, mode := range []proxyMode{httpProxy, socksProxy} {
|
||||
if _, err := c.checkCatalog(ctx, mode, nil, []int{1, 2, 3}, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := c.checkRoute(ctx, 0, previous.URLs[0], http.StatusServiceUnavailable); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.checkSOCKSRejection(ctx, 0, previous.SOCKSURLs[0], socksGeneralFailure); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.checkReadyRoutes(ctx, 1, previous.URLs[1], previous.SOCKSURLs[1])
|
||||
}
|
||||
|
||||
lastSuccess, err := c.wait(ctx, len(peers), len(peers), previous.LastSuccess)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
links, err := c.checkReadyCatalog(ctx)
|
||||
links, err := c.checkReadyCatalog(ctx, httpProxy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if previous.URLs != nil && !slices.Equal(links, previous.URLs) {
|
||||
socksLinks, err := c.checkReadyCatalog(ctx, socksProxy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if previous.URLs != nil && (!slices.Equal(links, previous.URLs) || !slices.Equal(socksLinks, previous.SOCKSURLs)) {
|
||||
return errors.New("exported links changed after restart")
|
||||
}
|
||||
if err := c.checkAuth(ctx, links[0]); err != nil {
|
||||
if err := c.checkAuth(ctx, links[0], socksLinks[0]); err != nil {
|
||||
return err
|
||||
}
|
||||
for i, link := range links {
|
||||
if err := c.checkRoute(ctx, i, link, http.StatusOK); err != nil {
|
||||
if err := c.checkReadyRoutes(ctx, i, link, socksLinks[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if previous.URLs == nil {
|
||||
data, err := json.Marshal(baseline{LastSuccess: lastSuccess, URLs: links})
|
||||
data, err := json.Marshal(baseline{LastSuccess: lastSuccess, URLs: links, SOCKSURLs: socksLinks})
|
||||
if err != nil {
|
||||
return errors.New("encode fixture link baseline")
|
||||
}
|
||||
@@ -181,7 +212,7 @@ func (c checkClient) wait(ctx context.Context, candidates, ready int, after time
|
||||
}
|
||||
}
|
||||
|
||||
func (c checkClient) checkAuth(ctx context.Context, link string) error {
|
||||
func (c checkClient) checkAuth(ctx context.Context, link, socksLink 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")
|
||||
}
|
||||
@@ -191,7 +222,7 @@ func (c checkClient) checkAuth(ctx context.Context, link string) error {
|
||||
return errors.New("catalog did not reject absent/invalid bearer credentials")
|
||||
}
|
||||
}
|
||||
u, err := c.parseLink(0, link)
|
||||
u, err := c.parseLink(httpProxy, 0, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -201,47 +232,118 @@ func (c checkClient) checkAuth(ctx context.Context, link string) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
u, err = c.parseLink(socksProxy, 0, socksLink)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
username := u.User.Username()
|
||||
u.User = nil
|
||||
if err := c.runSOCKSRejection(ctx, 0, u, "no acceptable authentication methods"); err != nil {
|
||||
return err
|
||||
}
|
||||
u.User = url.UserPassword(username, "invalid-fixture-password")
|
||||
return c.runSOCKSRejection(ctx, 0, u, "username/password authentication failed")
|
||||
}
|
||||
|
||||
func (c checkClient) checkRoute(ctx context.Context, i int, link string, want int) error {
|
||||
u, err := c.parseLink(i, link)
|
||||
u, err := c.parseLink(httpProxy, 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)
|
||||
func (c checkClient) checkReadyRoutes(ctx context.Context, i int, link, socksLink string) error {
|
||||
httpURL, err := c.parseLink(httpProxy, i, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
socksURL, err := c.parseLink(socksProxy, i, socksLink)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if httpURL.User.String() != socksURL.User.String() {
|
||||
return errors.New("HTTP and SOCKS exports disagree on node credentials")
|
||||
}
|
||||
if err := c.runRoute(ctx, i, httpURL, http.StatusOK); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.runRoute(ctx, i, socksURL, http.StatusOK)
|
||||
}
|
||||
|
||||
const socksGeneralFailure = "unknown error general SOCKS server failure"
|
||||
|
||||
func (c checkClient) checkSOCKSRejection(ctx context.Context, i int, link, want string) error {
|
||||
u, err := c.parseLink(socksProxy, i, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.runSOCKSRejection(ctx, i, u, want)
|
||||
}
|
||||
|
||||
func (c checkClient) runSOCKSRejection(ctx context.Context, i int, proxyURL *url.URL, want string) error {
|
||||
tr := c.proxyTransport(proxyURL)
|
||||
defer tr.CloseIdleConnections()
|
||||
client := &http.Client{Transport: tr, Timeout: 8 * time.Second, CheckRedirect: noRedirect}
|
||||
for _, target := range []url.URL{fixtureOriginURL("http"), fixtureOriginURL("https")} {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil)
|
||||
if err != nil {
|
||||
return errors.New("construct fixture origin request")
|
||||
}
|
||||
res, err := client.Do(req)
|
||||
if res != nil {
|
||||
res.Body.Close()
|
||||
}
|
||||
var op *net.OpError
|
||||
if !errors.As(err, &op) || op.Op != "socks connect" || op.Err.Error() != want {
|
||||
return fmt.Errorf("%s %s fixture SOCKS request did not reject with %q", peers[i].protocol, target.Scheme, want)
|
||||
}
|
||||
}
|
||||
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{
|
||||
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 via %s: expected status %d and matching origin proof when successful (got %d)",
|
||||
peers[i].protocol, scheme, proxyURL.Scheme, want, got)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c checkClient) proxyTransport(proxyURL *url.URL) *http.Transport {
|
||||
return &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 {
|
||||
}
|
||||
}
|
||||
|
||||
func fixtureOriginURL(scheme string) url.URL {
|
||||
port := httpPort
|
||||
if scheme == "https" {
|
||||
port = httpsPort
|
||||
}
|
||||
return url.URL{Scheme: scheme, Host: net.JoinHostPort(originName, port), Path: "/echo"}
|
||||
}
|
||||
|
||||
func (c checkClient) exchange(ctx context.Context, i int, scheme string, proxyURL *url.URL, checkEcho bool) (int, error) {
|
||||
connect := proxyURL.Scheme == string(httpProxy) && scheme == "https"
|
||||
var connectStatus chan int
|
||||
tr := c.proxyTransport(proxyURL)
|
||||
if connect {
|
||||
connectStatus = make(chan int, 1)
|
||||
tr.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[:])
|
||||
@@ -249,8 +351,9 @@ func (c checkClient) exchange(ctx context.Context, i int, scheme string, proxyUR
|
||||
if checkEcho {
|
||||
challenge = make([]byte, challengeSize)
|
||||
rand.Read(challenge)
|
||||
copy(challenge, nonce)
|
||||
}
|
||||
u := url.URL{Scheme: scheme, Host: net.JoinHostPort(originName, port), Path: "/echo"}
|
||||
u := fixtureOriginURL(scheme)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(challenge))
|
||||
if err != nil {
|
||||
return 0, errors.New("construct fixture origin request")
|
||||
@@ -259,7 +362,7 @@ func (c checkClient) exchange(ctx context.Context, i int, scheme string, proxyUR
|
||||
req.Header.Set(routeHeader, c.peerIP(i))
|
||||
req.Header.Set("Authorization", "Fixture "+nonce)
|
||||
code, header, body, err := doRequest(client, req)
|
||||
if scheme == "https" {
|
||||
if connect {
|
||||
select {
|
||||
case status := <-connectStatus:
|
||||
if status != http.StatusOK && code == 0 {
|
||||
@@ -268,7 +371,7 @@ func (c checkClient) exchange(ctx context.Context, i int, scheme string, proxyUR
|
||||
default:
|
||||
return code, errors.New("no CONNECT acknowledgement")
|
||||
}
|
||||
} else if code == http.StatusProxyAuthRequired && header.Get("Proxy-Authenticate") != `Basic realm="http-gateway"` {
|
||||
} else if proxyURL.Scheme == string(httpProxy) && 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) ||
|
||||
|
||||
@@ -69,12 +69,13 @@ VALUES (1, %d, %s, '%s', '%s', %d, '%s', '%s', '%s', %d);
|
||||
rand.Read(apiSecret[:])
|
||||
rand.Read(nodeSecret[:])
|
||||
env := fmt.Sprintf(`GATEWAY_PUBLIC_PROXY_ADDR=%s
|
||||
GATEWAY_SOCKS_PORT=%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[:]),
|
||||
`, f.addr(gatewayIP, proxyPort), socksPort, 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)
|
||||
|
||||
@@ -21,6 +21,7 @@ const (
|
||||
httpsPort = "18443"
|
||||
proxyPort = "8081"
|
||||
apiPort = "8082"
|
||||
socksPort = "1080"
|
||||
databaseIP = 4
|
||||
originIP = 10
|
||||
gatewayIP = 20
|
||||
@@ -53,7 +54,7 @@ func main() {
|
||||
|
||||
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>")
|
||||
return errors.New("usage: imagefixture <generate|origin|peers-ready|empty|verify|snapshot|failed-route|down|removed-route|privileges> <fixture-dir>")
|
||||
}
|
||||
prefix := os.Getenv("GATEWAY_FIXTURE_PREFIX")
|
||||
octet, err := strconv.Atoi(strings.TrimPrefix(prefix, "11.254."))
|
||||
@@ -71,7 +72,7 @@ func run() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
|
||||
defer cancel()
|
||||
return f.waitPeers(ctx)
|
||||
case "empty", "verify", "snapshot", "failed-route", "down", "privileges":
|
||||
case "empty", "verify", "snapshot", "failed-route", "down", "removed-route", "privileges":
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 55*time.Second)
|
||||
defer cancel()
|
||||
if mode == "privileges" {
|
||||
@@ -141,7 +142,7 @@ func (f fixture) clientDial(ctx context.Context, network, addr string) (net.Conn
|
||||
return nil, errors.New("unexpected fixture network")
|
||||
}
|
||||
switch addr {
|
||||
case f.addr(gatewayIP, apiPort), f.addr(gatewayIP, proxyPort), f.addr(databaseIP, "5432"):
|
||||
case f.addr(gatewayIP, apiPort), f.addr(gatewayIP, proxyPort), f.addr(gatewayIP, socksPort), f.addr(databaseIP, "5432"):
|
||||
default:
|
||||
return nil, errors.New("refusing connection outside the smoke fixture")
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user