diff --git a/.env.example b/.env.example index 9d16ce6..f27e833 100644 --- a/.env.example +++ b/.env.example @@ -17,5 +17,5 @@ LOG_LEVEL=info WEB_PORT=8088 # --- Image tagging (used by CI / registry pushes) --- -# REGISTRY=git.qomar.pw/omar +# REGISTRY=git.eeee.moe/omar # TAG=latest diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index c140ef2..85c4c05 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -8,9 +8,9 @@ on: workflow_dispatch: env: - REGISTRY: git.qomar.pw - # git.qomar.pw/omar/zhguchiy_perchik — images are namespaced under the repo. - IMAGE_BASE: git.qomar.pw/${{ github.repository }} + REGISTRY: git.eeee.moe + # git.eeee.moe/omar/zhguchiy_perchik — images are namespaced under the repo. + IMAGE_BASE: git.eeee.moe/${{ github.repository }} jobs: # Fast validation on every push/PR: Go vet + tests + build, and the frontend diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index cb4d199..fe47ec3 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -15,7 +15,7 @@ subscriptions. | `frontend` | React + Vite + TS + Tailwind + shadcn/ui + recharts | SPA panel, built to static | | `edge` | nginx | Serves frontend static, routes `/api` and `/sub` to `api` | -Single Go module (`git.qomar.pw/omar/zhguchiy_perchik`) with two binaries +Single Go module (`git.eeee.moe/omar/zhguchiy_perchik`) with two binaries sharing `internal/` packages (dialers, upstream parser + canonicalization, geoip, fetcher, db, subs). Dialers, geoip, fetcher and the upstream parser are reused from `tessero-checker`; the session model, DB layer, canonicalization, diff --git a/README.md b/README.md index 6b62d31..5b419cf 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,38 @@ transaction flips the `is_current` pointer. Per-canonical history (uptime, consecutive failures) is kept even while a proxy is currently invalid, but only working proxies from the current session are ever shown or served. +## Operations + +**Check failures.** A failed or cancelled check session does not replace the +current snapshot. A proxy is not marked working if its exit IP cannot be +verified or it fails a configured latency or speed check. Subscription PATCHes +preserve omitted fields, including disabled state, expiry and filters. Send an +explicit `null` to clear an expiry or other nullable limit. + +**HTTPS probes.** Exit IP and speed probes use certificate-verified HTTPS and +do not follow redirects. Exit IP discovery requires a successful response +containing a single public IP. The speed test requires HTTP 200 with a +complete, uncompressed body between 256 KiB and 10 MiB. The old default HTTP +speed URL is migrated to the HTTPS Selectel endpoint, with Cloudflare as a +fallback. Other HTTP or malformed overrides are ignored; replace them in +**Settings → Speed test** with a working HTTPS endpoint. + +**Logging and rotation.** Treat `/sub/` URLs like passwords. Serve the +panel and feeds over HTTPS outside local development. The API logs registered +route templates, not request paths. The bundled nginx access log omits +request targets and headers (including `Referer`), and its error log is +discarded. Apply the same policy to any outer reverse proxy, CDN or collector. +Updating the application does not sanitize historical logs. If a secret may +have appeared in them, restrict access to those logs and rotate it: + +- **Subscription URL**: revoke a leaked link by disabling or deleting its + subscription. Create a replacement with the same filters and update clients. +- **Source or Telegram token**: revoke it with its issuer and update the source + URL or **Telegram notifications** token in **Settings**. +- **Admin credentials**: set a new `ADMIN_PASSWORD` and random `SESSION_SECRET` + in `.env`, then run `docker compose up -d --force-recreate api`. Rotating the + signing secret invalidates existing sessions. + ## Development Backend: diff --git a/cmd/api/main.go b/cmd/api/main.go index a6a20e3..ae34eee 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -12,8 +12,8 @@ import ( "syscall" "time" - "git.qomar.pw/omar/zhguchiy_perchik/internal/api" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/api" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" ) func main() { diff --git a/cmd/checker/main.go b/cmd/checker/main.go index 7759d52..242ff48 100644 --- a/cmd/checker/main.go +++ b/cmd/checker/main.go @@ -11,11 +11,11 @@ import ( "syscall" "time" - "git.qomar.pw/omar/zhguchiy_perchik/internal/checker" - "git.qomar.pw/omar/zhguchiy_perchik/internal/config" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" - "git.qomar.pw/omar/zhguchiy_perchik/internal/geoip" - "git.qomar.pw/omar/zhguchiy_perchik/internal/worker" + "git.eeee.moe/omar/zhguchiy_perchik/internal/checker" + "git.eeee.moe/omar/zhguchiy_perchik/internal/config" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/geoip" + "git.eeee.moe/omar/zhguchiy_perchik/internal/worker" ) func main() { diff --git a/deploy/nginx.conf b/deploy/nginx.conf index 17436cf..fb1fc40 100644 --- a/deploy/nginx.conf +++ b/deploy/nginx.conf @@ -4,12 +4,21 @@ map $http_upgrade $connection_upgrade { '' close; } +# Do not log request targets or headers on any route. A Referer on an +# unrelated request can carry a subscription URL just as its own path can. +log_format request_metrics '$remote_addr [$time_local] $status $body_bytes_sent $request_time'; + server { listen 80; server_name _; root /usr/share/nginx/html; index index.html; + access_log /var/log/nginx/access.log request_metrics; + # Error logging includes raw request lines and headers, even for errors + # raised before location matching. Discard it at the server level. + error_log /dev/null; + # gzip for text assets. gzip on; gzip_types text/plain text/css application/javascript application/json image/svg+xml; @@ -33,6 +42,7 @@ server { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + add_header Referrer-Policy no-referrer always; } location = /healthz { proxy_pass http://api:8080; diff --git a/docker-compose.yml b/docker-compose.yml index e5e1e9b..2c7bf2d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -26,7 +26,7 @@ services: retries: 10 checker: - image: ${REGISTRY:-git.qomar.pw/omar/zhguchiy_perchik}/checker:${TAG:-latest} + image: ${REGISTRY:-git.eeee.moe/omar/zhguchiy_perchik}/checker:${TAG:-latest} restart: unless-stopped environment: DB_DSN: postgres://${POSTGRES_USER:-perchik}:${POSTGRES_PASSWORD:-perchik}@postgres:5432/${POSTGRES_DB:-perchik}?sslmode=disable @@ -36,7 +36,7 @@ services: condition: service_healthy api: - image: ${REGISTRY:-git.qomar.pw/omar/zhguchiy_perchik}/api:${TAG:-latest} + image: ${REGISTRY:-git.eeee.moe/omar/zhguchiy_perchik}/api:${TAG:-latest} restart: unless-stopped environment: DB_DSN: postgres://${POSTGRES_USER:-perchik}:${POSTGRES_PASSWORD:-perchik}@postgres:5432/${POSTGRES_DB:-perchik}?sslmode=disable @@ -49,7 +49,7 @@ services: condition: service_healthy web: - image: ${REGISTRY:-git.qomar.pw/omar/zhguchiy_perchik}/web:${TAG:-latest} + image: ${REGISTRY:-git.eeee.moe/omar/zhguchiy_perchik}/web:${TAG:-latest} restart: unless-stopped ports: - "${WEB_PORT:-8088}:80" diff --git a/go.mod b/go.mod index ec266d0..d6971fc 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module git.qomar.pw/omar/zhguchiy_perchik +module git.eeee.moe/omar/zhguchiy_perchik go 1.26.2 diff --git a/internal/api/handlers_proxies.go b/internal/api/handlers_proxies.go index 3b14dfc..20f7fbf 100644 --- a/internal/api/handlers_proxies.go +++ b/internal/api/handlers_proxies.go @@ -5,8 +5,8 @@ import ( "strconv" "strings" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" - "git.qomar.pw/omar/zhguchiy_perchik/internal/subs" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/subs" ) func (s *Server) handleListProxies(w http.ResponseWriter, r *http.Request) { diff --git a/internal/api/handlers_sessions.go b/internal/api/handlers_sessions.go index ab33cf5..dcec98d 100644 --- a/internal/api/handlers_sessions.go +++ b/internal/api/handlers_sessions.go @@ -3,7 +3,7 @@ package api import ( "net/http" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" ) // handleListSessions returns the check-session history (newest first). diff --git a/internal/api/handlers_settings.go b/internal/api/handlers_settings.go index bdfcd95..c084aae 100644 --- a/internal/api/handlers_settings.go +++ b/internal/api/handlers_settings.go @@ -3,7 +3,7 @@ package api import ( "net/http" - "git.qomar.pw/omar/zhguchiy_perchik/internal/config" + "git.eeee.moe/omar/zhguchiy_perchik/internal/config" ) // editableKeys is the whitelist of settings the admin may read and write. diff --git a/internal/api/handlers_sources.go b/internal/api/handlers_sources.go index 6d194f2..3a72a55 100644 --- a/internal/api/handlers_sources.go +++ b/internal/api/handlers_sources.go @@ -4,7 +4,7 @@ import ( "net/http" "strings" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" ) func (s *Server) handleListSources(w http.ResponseWriter, r *http.Request) { diff --git a/internal/api/handlers_sub.go b/internal/api/handlers_sub.go index 97fbb6f..620c778 100644 --- a/internal/api/handlers_sub.go +++ b/internal/api/handlers_sub.go @@ -4,8 +4,8 @@ import ( "net/http" "time" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" - "git.qomar.pw/omar/zhguchiy_perchik/internal/subs" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/subs" ) // handleSub serves a subscription dynamically: every request re-evaluates the diff --git a/internal/api/handlers_subscriptions.go b/internal/api/handlers_subscriptions.go index 52bba09..c2f4a9e 100644 --- a/internal/api/handlers_subscriptions.go +++ b/internal/api/handlers_subscriptions.go @@ -3,11 +3,13 @@ package api import ( "crypto/rand" "encoding/hex" + "encoding/json" + "errors" "net/http" "time" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" - "git.qomar.pw/omar/zhguchiy_perchik/internal/subs" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/subs" ) func (s *Server) handleListSubscriptions(w http.ResponseWriter, r *http.Request) { @@ -22,80 +24,113 @@ func (s *Server) handleListSubscriptions(w http.ResponseWriter, r *http.Request) writeJSON(w, http.StatusOK, map[string]any{"items": subs}) } +type subField[T any] struct { + value T + set bool +} + +func (f *subField[T]) UnmarshalJSON(data []byte) error { + if string(data) == "null" { + return errors.New("field cannot be null") + } + return f.decode(data) +} + +func (f *subField[T]) decode(data []byte) error { + if err := json.Unmarshal(data, &f.value); err != nil { + return err + } + f.set = true + return nil +} + +func (f *subField[T]) apply(dst *T) { + if f.set { + *dst = f.value + } +} + +// A present null clears a nullable field; an omitted field leaves it alone. +type nullableSubField[T any] struct{ subField[*T] } + +func (f *nullableSubField[T]) UnmarshalJSON(data []byte) error { + return f.decode(data) +} + type subReq struct { - Name string `json:"name"` - Enabled *bool `json:"enabled"` - Format string `json:"format"` - FilterProtocols []string `json:"filter_protocols"` - FilterCountries []string `json:"filter_countries"` - FilterSources []string `json:"filter_sources"` - URLSearch []string `json:"url_search"` - MaxLatencyMs *int `json:"max_latency_ms"` - MinSpeedMbps *float64 `json:"min_speed_mbps"` - LimitN *int `json:"limit_n"` - UniqueIPs *bool `json:"unique_ips"` - UniqueIPsMetric string `json:"unique_ips_metric"` - UniqueIPsScope string `json:"unique_ips_scope"` - UniqueSubnetV4 int `json:"unique_subnet_v4"` - UniqueSubnetV6 int `json:"unique_subnet_v6"` - SortBy []string `json:"sort_by"` - ExpiresAt *time.Time `json:"expires_at"` + Name subField[string] `json:"name"` + Enabled subField[bool] `json:"enabled"` + Format subField[string] `json:"format"` + FilterProtocols subField[[]string] `json:"filter_protocols"` + FilterCountries subField[[]string] `json:"filter_countries"` + FilterSources subField[[]string] `json:"filter_sources"` + URLSearch subField[[]string] `json:"url_search"` + MaxLatencyMs nullableSubField[int] `json:"max_latency_ms"` + MinSpeedMbps nullableSubField[float64] `json:"min_speed_mbps"` + LimitN nullableSubField[int] `json:"limit_n"` + UniqueIPs subField[bool] `json:"unique_ips"` + UniqueIPsMetric subField[string] `json:"unique_ips_metric"` + UniqueIPsScope subField[string] `json:"unique_ips_scope"` + UniqueSubnetV4 subField[int] `json:"unique_subnet_v4"` + UniqueSubnetV6 subField[int] `json:"unique_subnet_v6"` + SortBy subField[[]string] `json:"sort_by"` + ExpiresAt nullableSubField[time.Time] `json:"expires_at"` } var validFormats = map[string]struct{}{"plain": {}, "base64": {}, "clash": {}, "singbox": {}} -func (r subReq) apply(s *db.Subscription) { - s.Name = r.Name - if r.Enabled != nil { - s.Enabled = *r.Enabled +func (r *subReq) apply(s *db.Subscription) { + r.Name.apply(&s.Name) + r.Enabled.apply(&s.Enabled) + if r.Format.set { + s.Format = r.Format.value + if _, ok := validFormats[s.Format]; !ok { + s.Format = "plain" + } } - s.Format = r.Format - if _, ok := validFormats[s.Format]; !ok { - s.Format = "plain" + r.FilterProtocols.apply(&s.FilterProtocols) + r.FilterCountries.apply(&s.FilterCountries) + r.FilterSources.apply(&s.FilterSources) + r.URLSearch.apply(&s.URLSearch) + r.MaxLatencyMs.apply(&s.MaxLatencyMs) + r.MinSpeedMbps.apply(&s.MinSpeedMbps) + r.LimitN.apply(&s.LimitN) + r.UniqueIPs.apply(&s.UniqueIPs) + if r.UniqueIPsMetric.set || r.UniqueIPsScope.set || r.UniqueSubnetV4.set || r.UniqueSubnetV6.set { + // Persist normalized values from this edit without rewriting omitted fields. + norm := subs.Unique{ + Metric: r.UniqueIPsMetric.value, Scope: r.UniqueIPsScope.value, + SubnetV4: r.UniqueSubnetV4.value, SubnetV6: r.UniqueSubnetV6.value, + }.Normalized() + if r.UniqueIPsMetric.set { + s.UniqueIPsMetric = norm.Metric + } + if r.UniqueIPsScope.set { + s.UniqueIPsScope = norm.Scope + } + if r.UniqueSubnetV4.set { + s.UniqueSubnetV4 = norm.SubnetV4 + } + if r.UniqueSubnetV6.set { + s.UniqueSubnetV6 = norm.SubnetV6 + } } - s.FilterProtocols = nonNil(r.FilterProtocols) - s.FilterCountries = nonNil(r.FilterCountries) - s.FilterSources = nonNil(r.FilterSources) - s.URLSearch = nonNil(r.URLSearch) - s.MaxLatencyMs = r.MaxLatencyMs - s.MinSpeedMbps = r.MinSpeedMbps - s.LimitN = r.LimitN - if r.UniqueIPs != nil { - s.UniqueIPs = *r.UniqueIPs - } - s.UniqueIPsMetric = r.UniqueIPsMetric - if s.UniqueIPsMetric != subs.MetricLatency { - s.UniqueIPsMetric = subs.MetricSpeed - } - s.UniqueIPsScope = r.UniqueIPsScope - if s.UniqueIPsScope != subs.ScopeSubnet { - s.UniqueIPsScope = subs.ScopeIP - } - // Persist already-normalized prefix lengths so what the panel shows on the - // next edit is exactly what the subscription serves. - norm := subs.Unique{SubnetV4: r.UniqueSubnetV4, SubnetV6: r.UniqueSubnetV6}.Normalized() - s.UniqueSubnetV4 = norm.SubnetV4 - s.UniqueSubnetV6 = norm.SubnetV6 - s.SortBy = nonNil(r.SortBy) - s.ExpiresAt = r.ExpiresAt -} - -func nonNil(v []string) []string { - if v == nil { - return []string{} - } - return v + r.SortBy.apply(&s.SortBy) + r.ExpiresAt.apply(&s.ExpiresAt) } func (s *Server) handleCreateSubscription(w http.ResponseWriter, r *http.Request) { - var req subReq - if err := decodeJSON(r, &req); err != nil { + var req *subReq + if err := decodeJSON(r, &req); err != nil || req == nil { writeErr(w, http.StatusBadRequest, "bad request") return } sub := &db.Subscription{ Token: newToken(), Enabled: true, Format: "plain", + FilterProtocols: []string{}, FilterCountries: []string{}, FilterSources: []string{}, + URLSearch: []string{}, SortBy: []string{}, UniqueIPsMetric: subs.MetricSpeed, UniqueIPsScope: subs.ScopeIP, + UniqueSubnetV4: subs.DefaultSubnetV4, UniqueSubnetV6: subs.DefaultSubnetV6, } req.apply(sub) created, err := s.db.CreateSubscription(r.Context(), sub) @@ -112,17 +147,12 @@ func (s *Server) handleUpdateSubscription(w http.ResponseWriter, r *http.Request writeErr(w, http.StatusBadRequest, "bad id") return } - var req subReq - if err := decodeJSON(r, &req); err != nil { + var req *subReq + if err := decodeJSON(r, &req); err != nil || req == nil { writeErr(w, http.StatusBadRequest, "bad request") return } - sub := &db.Subscription{ - ID: id, Enabled: true, - UniqueIPsMetric: subs.MetricSpeed, UniqueIPsScope: subs.ScopeIP, - } - req.apply(sub) - updated, err := s.db.UpdateSubscription(r.Context(), sub) + updated, err := s.db.UpdateSubscription(r.Context(), id, req.apply) if err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return diff --git a/internal/api/handlers_subscriptions_test.go b/internal/api/handlers_subscriptions_test.go new file mode 100644 index 0000000..dc36f46 --- /dev/null +++ b/internal/api/handlers_subscriptions_test.go @@ -0,0 +1,109 @@ +package api + +import ( + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" + + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" +) + +func subscriptionWithRestrictions() db.Subscription { + expires := time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC) + latency, speed, limit := 100, 12.5, 3 + return db.Subscription{ + ID: 1, Token: "test-token", Name: "Restricted", Enabled: false, Format: "clash", + FilterProtocols: []string{"vless"}, FilterCountries: []string{"DE"}, + FilterSources: []string{"source"}, URLSearch: []string{"example"}, + MaxLatencyMs: &latency, MinSpeedMbps: &speed, LimitN: &limit, + UniqueIPs: true, UniqueIPsMetric: "latency", UniqueIPsScope: "subnet", + UniqueSubnetV4: 22, UniqueSubnetV6: 56, SortBy: []string{"latency:asc"}, + ExpiresAt: &expires, RequestCount: 4, LastRequestedAt: &expires, CreatedAt: expires, + } +} + +func applySubscriptionRequest(t *testing.T, body string, sub *db.Subscription) { + t.Helper() + r := httptest.NewRequest(http.MethodPatch, "/api/v1/subscriptions/1", strings.NewReader(body)) + var req *subReq + if err := decodeJSON(r, &req); err != nil || req == nil { + t.Fatalf("decode subscription request: %v", err) + } + req.apply(sub) +} + +func TestSubscriptionPatchPreservesRestrictions(t *testing.T) { + sub := subscriptionWithRestrictions() + want := subscriptionWithRestrictions() + want.Name = "Renamed" + + applySubscriptionRequest(t, `{"name":"Renamed"}`, &sub) + + if !reflect.DeepEqual(sub, want) { + t.Fatalf("rename changed unrelated fields: got %+v, want %+v", sub, want) + } +} + +func TestSubscriptionPatchClearsNullableFields(t *testing.T) { + sub := subscriptionWithRestrictions() + want := subscriptionWithRestrictions() + want.MaxLatencyMs, want.MinSpeedMbps, want.LimitN, want.ExpiresAt = nil, nil, nil, nil + + applySubscriptionRequest(t, `{"max_latency_ms":null,"min_speed_mbps":null,"limit_n":null,"expires_at":null}`, &sub) + + if !reflect.DeepEqual(sub, want) { + t.Fatalf("nullable patch got %+v, want %+v", sub, want) + } +} + +func TestSubscriptionPatchAppliesExplicitValues(t *testing.T) { + sub := subscriptionWithRestrictions() + applySubscriptionRequest(t, `{"enabled":true,"unique_ips":false,"filter_countries":[],"limit_n":0,"unique_subnet_v4":0}`, &sub) + + if !sub.Enabled || sub.UniqueIPs || sub.FilterCountries == nil || len(sub.FilterCountries) != 0 || + sub.LimitN == nil || *sub.LimitN != 0 || sub.UniqueSubnetV4 != 24 || sub.UniqueSubnetV6 != 56 { + t.Fatalf("explicit patch got %+v", sub) + } +} + +func TestSubscriptionRequestAcceptsFullPanelPayload(t *testing.T) { + sub := subscriptionWithRestrictions() + applySubscriptionRequest(t, `{ + "name":"Panel", "enabled":true, "format":"singbox", + "filter_protocols":["trojan"], "filter_countries":[], "filter_sources":["second"], "url_search":[], + "max_latency_ms":250, "min_speed_mbps":8.5, "limit_n":null, + "unique_ips":false, "unique_ips_metric":"speed", "unique_ips_scope":"ip", + "unique_subnet_v4":25, "unique_subnet_v6":64, "sort_by":[], "expires_at":null + }`, &sub) + + latency, speed := 250, 8.5 + want := subscriptionWithRestrictions() + want.Name, want.Enabled, want.Format = "Panel", true, "singbox" + want.FilterProtocols, want.FilterCountries = []string{"trojan"}, []string{} + want.FilterSources, want.URLSearch = []string{"second"}, []string{} + want.MaxLatencyMs, want.MinSpeedMbps, want.LimitN = &latency, &speed, nil + want.UniqueIPs, want.UniqueIPsMetric, want.UniqueIPsScope = false, "speed", "ip" + want.UniqueSubnetV4, want.UniqueSubnetV6, want.SortBy = 25, 64, []string{} + want.ExpiresAt = nil + if !reflect.DeepEqual(sub, want) { + t.Fatalf("panel payload got %+v, want %+v", sub, want) + } +} + +func TestSubscriptionPatchRejectsNullNonNullableFields(t *testing.T) { + s := &Server{} + for _, body := range []string{`null`, `{"enabled":null}`, `{"filter_countries":null}`} { + t.Run(body, func(t *testing.T) { + r := httptest.NewRequest(http.MethodPatch, "/api/v1/subscriptions/1", strings.NewReader(body)) + r.SetPathValue("id", "1") + w := httptest.NewRecorder() + s.handleUpdateSubscription(w, r) + if w.Code != http.StatusBadRequest { + t.Fatalf("PATCH status = %d, want 400", w.Code) + } + }) + } +} diff --git a/internal/api/helpers.go b/internal/api/helpers.go index 5d81490..2a2742c 100644 --- a/internal/api/helpers.go +++ b/internal/api/helpers.go @@ -6,7 +6,7 @@ import ( "strconv" "strings" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" ) func writeJSON(w http.ResponseWriter, status int, v any) { diff --git a/internal/api/server.go b/internal/api/server.go index 7dd8276..f05f58a 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -8,10 +8,9 @@ import ( "log/slog" "net" "net/http" - "strings" "time" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" ) // Config holds the API server dependencies and secrets. @@ -109,8 +108,13 @@ func logRequests(log *slog.Logger, next http.Handler) http.Handler { start := time.Now() sw := &statusWriter{ResponseWriter: w, status: http.StatusOK} next.ServeHTTP(sw, r) - if !strings.HasPrefix(r.URL.Path, "/healthz") { - log.Debug("http", "method", r.Method, "path", r.URL.Path, + route := r.Pattern + // ServeMux can report a concrete redirect path for CONNECT. + if route == "" || r.Method == http.MethodConnect { + route = "unmatched" + } + if route != "GET /healthz" { + log.Debug("http", "method", r.Method, "route", route, "status", sw.status, "ms", time.Since(start).Milliseconds()) } }) diff --git a/internal/api/server_test.go b/internal/api/server_test.go new file mode 100644 index 0000000..99555b3 --- /dev/null +++ b/internal/api/server_test.go @@ -0,0 +1,71 @@ +package api + +import ( + "bytes" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestRequestLogsUseRouteTemplates(t *testing.T) { + const pathSecret = "example-path-secret" + const querySecret = "example-query-secret" + const refererSecret = "example-referer-secret" + + mux := http.NewServeMux() + handler := func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) } + mux.HandleFunc("GET /sub/{token}", handler) + mux.HandleFunc("PATCH /api/v1/subscriptions/{id}", handler) + mux.HandleFunc("GET /healthz", handler) + + for _, tt := range []struct { + name, method, path, route string + status int + }{ + {"subscription", http.MethodGet, "/sub/" + pathSecret, "GET /sub/{token}", http.StatusNoContent}, + {"admin", http.MethodPatch, "/api/v1/subscriptions/" + pathSecret, "PATCH /api/v1/subscriptions/{id}", http.StatusNoContent}, + {"unmatched subscription", http.MethodGet, "/sub/" + pathSecret + "/extra", "unmatched", http.StatusNotFound}, + {"wrong method", http.MethodPost, "/sub/" + pathSecret, "unmatched", http.StatusMethodNotAllowed}, + {"unmatched path", http.MethodGet, "/other/" + pathSecret, "unmatched", http.StatusNotFound}, + {"canonical redirect", http.MethodGet, "/sub//" + pathSecret, "GET /sub/{token}", http.StatusTemporaryRedirect}, + {"health check", http.MethodGet, "/healthz", "", http.StatusNoContent}, + } { + t.Run(tt.name, func(t *testing.T) { + var logs bytes.Buffer + logger := slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})) + req := httptest.NewRequest(tt.method, tt.path+"?tag="+querySecret, nil) + req.Header.Set("Referer", "https://example.invalid/sub/"+refererSecret) + res := httptest.NewRecorder() + logRequests(logger, mux).ServeHTTP(res, req) + + if res.Code != tt.status { + t.Fatalf("response status = %d, want %d", res.Code, tt.status) + } + if tt.route == "" { + if logs.Len() != 0 { + t.Fatalf("health check logged: %s", &logs) + } + return + } + logged := logs.String() + for _, secret := range []string{pathSecret, querySecret, refererSecret} { + if strings.Contains(logged, secret) { + t.Fatalf("request data in log: %s", logged) + } + } + var entry struct { + Route string `json:"route"` + Status int `json:"status"` + } + if err := json.Unmarshal(logs.Bytes(), &entry); err != nil { + t.Fatalf("decode request log: %v", err) + } + if entry.Route != tt.route || entry.Status != tt.status { + t.Errorf("logged route/status = %q/%d, want %q/%d", entry.Route, entry.Status, tt.route, tt.status) + } + }) + } +} diff --git a/internal/checker/checker.go b/internal/checker/checker.go index d151184..9329f13 100644 --- a/internal/checker/checker.go +++ b/internal/checker/checker.go @@ -6,17 +6,21 @@ package checker import ( "context" "crypto/tls" + "errors" "fmt" "io" "log/slog" "net" "net/http" + "net/netip" + "slices" "strings" "time" - "git.qomar.pw/omar/zhguchiy_perchik/internal/dialer" - "git.qomar.pw/omar/zhguchiy_perchik/internal/geoip" - "git.qomar.pw/omar/zhguchiy_perchik/internal/upstream" + "git.eeee.moe/omar/zhguchiy_perchik/internal/config" + "git.eeee.moe/omar/zhguchiy_perchik/internal/dialer" + "git.eeee.moe/omar/zhguchiy_perchik/internal/geoip" + "git.eeee.moe/omar/zhguchiy_perchik/internal/upstream" ) // Config holds the tunable validity thresholds for one check pass. @@ -33,10 +37,10 @@ type Config struct { // DefaultExitIPAPIs is the hardcoded fallback chain for exit-IP discovery. Not // admin-configurable by design — a reliable echo is required for every check. var DefaultExitIPAPIs = []string{ - "http://ifconfig.me/ip", - "http://api.ipify.org", - "http://icanhazip.com", - "http://ipinfo.io/ip", + "https://ifconfig.me/ip", + "https://api.ipify.org", + "https://icanhazip.com", + "https://ipinfo.io/ip", } // Result is the per-proxy outcome reported to the worker. @@ -52,7 +56,7 @@ type Result struct { // Checker owns the dialer dispatcher and geoip resolver shared across all // concurrent per-proxy checks. type Checker struct { - dispatch *dialer.Dispatcher + dispatch dialer.Dialer geo *geoip.Resolver log *slog.Logger } @@ -66,51 +70,42 @@ func New(geo *geoip.Resolver, log *slog.Logger) *Checker { } } -// proxyHTTPClient builds an http.Client whose transport tunnels through the -// proxy: DialContext opens the protocol tunnel, TLS (for https targets) rides on -// top. Keep-alives are disabled so each probe is an independent connection. -func (c *Checker) proxyHTTPClient(up *upstream.Upstream, dialTO, totalTO time.Duration) *http.Client { - tr := &http.Transport{ - DialContext: func(ctx context.Context, _, address string) (net.Conn, error) { - return c.dialTunnel(ctx, up, address, dialTO, totalTO) - }, - TLSHandshakeTimeout: dialTO, - ResponseHeaderTimeout: totalTO, - ExpectContinueTimeout: time.Second, - ForceAttemptHTTP2: false, - TLSClientConfig: &tls.Config{InsecureSkipVerify: false}, //nolint:gosec // target certs, not proxy - DisableKeepAlives: true, - } - return &http.Client{ - Transport: tr, - Timeout: totalTO, - CheckRedirect: func(*http.Request, []*http.Request) error { - return http.ErrUseLastResponse +// proxyTransport tunnels HTTPS probes, verifying the target's certificate +// separately from the proxy handshake. +func (c *Checker) proxyTransport(ctx context.Context, up *upstream.Upstream, dialTO time.Duration) *http.Transport { + return &http.Transport{ + DialContext: func(_ context.Context, _, address string) (net.Conn, error) { + // net/http detaches the dial context from the request to permit reuse. + // These dials are never reused and must stop with the probe. + return c.dialTunnel(ctx, up, address, dialTO) }, + TLSHandshakeTimeout: dialTO, + TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12}, + DisableKeepAlives: true, + DisableCompression: true, + MaxResponseHeaderBytes: 64 << 10, } } -// dialTunnel opens the proxy tunnel with a hard watchdog. The reused protocol -// dialers do blocking socket I/O during the handshake without always honoring -// the context, so a proxy that accepts TCP but stalls the handshake would hang -// the worker forever. We run the dial in a goroutine and abandon it once dialTO -// elapses; on success we set an absolute deadline on the connection so a stalled -// read/write on the tunnel can never block the worker either. -func (c *Checker) dialTunnel(ctx context.Context, up *upstream.Upstream, address string, dialTO, totalTO time.Duration) (net.Conn, error) { +// dialTunnel bounds the handshake even if a dialer ignores cancellation. An +// unbuffered handoff leaves the dial goroutine responsible for late sockets. +func (c *Checker) dialTunnel(ctx context.Context, up *upstream.Upstream, address string, dialTO time.Duration) (net.Conn, error) { dctx, cancel := context.WithTimeout(ctx, dialTO) defer cancel() + if err := dctx.Err(); err != nil { + return nil, err + } type result struct { conn net.Conn err error } - ch := make(chan result, 1) + ch := make(chan result) go func() { conn, err := c.dispatch.Dial(dctx, up, address) select { case ch <- result{conn, err}: - default: - // The watchdog already gave up — don't leak the socket. + case <-dctx.Done(): if conn != nil { _ = conn.Close() } @@ -119,12 +114,27 @@ func (c *Checker) dialTunnel(ctx context.Context, up *upstream.Upstream, address select { case <-dctx.Done(): - return nil, fmt.Errorf("dial timeout after %s", dialTO) + return nil, dctx.Err() case r := <-ch: - if r.conn != nil { - _ = r.conn.SetDeadline(time.Now().Add(totalTO)) + err := dctx.Err() + if err == nil { + err = r.err } - return r.conn, r.err + if err == nil && r.conn == nil { + return nil, errors.New("dialer returned no connection") + } + if err == nil { + if deadline, ok := ctx.Deadline(); ok { + err = r.conn.SetDeadline(deadline) + } + } + if err != nil { + if r.conn != nil { + _ = r.conn.Close() + } + return nil, err + } + return r.conn, nil } } @@ -142,12 +152,12 @@ func (c *Checker) Check(ctx context.Context, canonicalURL string, cfg Config) Re if cfg.SpeedTestEnabled { mbps, serr := c.speedTest(ctx, up, cfg) - res.SpeedMbps = mbps if serr != nil { res.Passed = false res.FailReason = "speed: " + truncErr(serr) return res } + res.SpeedMbps = mbps if cfg.MinSpeedMbps > 0 && mbps < cfg.MinSpeedMbps { res.Passed = false res.FailReason = fmt.Sprintf("speed %.2fMbps < %.2fMbps", mbps, cfg.MinSpeedMbps) @@ -163,7 +173,6 @@ func (c *Checker) Check(ctx context.Context, canonicalURL string, cfg Config) Re // the latency gate. Sets Country from the geoip resolver. func (c *Checker) ping(ctx context.Context, up *upstream.Upstream, cfg Config) Result { var res Result - client := c.proxyHTTPClient(up, cfg.DialTimeout, cfg.DialTimeout) apis := cfg.ExitIPAPIs if len(apis) == 0 { @@ -172,27 +181,16 @@ func (c *Checker) ping(ctx context.Context, up *upstream.Upstream, cfg Config) R var lastErr string for _, api := range apis { - start := time.Now() - req, _ := http.NewRequestWithContext(ctx, http.MethodGet, api, nil) - req.Header.Set("User-Agent", "curl/8.0") - resp, err := client.Do(req) - latency := int(time.Since(start).Milliseconds()) + if err := ctx.Err(); err != nil { + lastErr = truncErr(err) + break + } + probeCtx, cancel := context.WithTimeout(ctx, cfg.DialTimeout) + transport := c.proxyTransport(probeCtx, up, cfg.DialTimeout) + ip, latency, err := probeExitIP(probeCtx, transport, api) + cancel() if err != nil { lastErr = truncErr(err) - if ctx.Err() != nil { - break - } - continue - } - body, _ := io.ReadAll(io.LimitReader(resp.Body, 4*1024)) - resp.Body.Close() - - ip := strings.TrimSpace(string(body)) - if net.ParseIP(ip) == nil { - ip = extractIP(string(body)) - } - if ip == "" { - lastErr = "invalid exit-ip response" continue } res.LatencyMs = latency @@ -215,100 +213,165 @@ func (c *Checker) ping(ctx context.Context, up *upstream.Upstream, cfg Config) R return res } -// DefaultSpeedTestURLs are proxy-friendly fallbacks tried in addition to the -// admin-configured URL. Cloudflare's endpoint frequently returns HTTP 429 -// through shared proxy exit IPs, so plain-HTTP CDN mirrors come first and -// Cloudflare is the last resort. +const ( + maxExitIPBodyBytes = 128 + minSpeedBodyBytes = 256 << 10 + maxSpeedBodyBytes = 10 << 20 +) + +// DefaultSpeedTestURLs are tried after the configured endpoint. Both serve +// bounded samples directly over HTTPS. var DefaultSpeedTestURLs = []string{ - "http://cachefly.cachefly.net/10mb.test", - "http://speedtest.tele2.net/10MB.zip", - "http://ipv4.download.thinkbroadband.com/10MB.zip", + config.DefaultSpeedTestURL, "https://speed.cloudflare.com/__down?bytes=10000000", } -// speedTest measures throughput through the proxy. It tries the configured URL -// then the fallbacks: a host-level failure (dial error, HTTP 429/non-200, empty -// body) moves to the next URL, but a completed download — even a slow one — is -// taken as the proxy's real speed and returned as-is (the proxy is the -// bottleneck, so trying other hosts wouldn't help). +// speedTest uses the first complete sample, including when it is slow. All +// attempts share the download time budget. func (c *Checker) speedTest(ctx context.Context, up *upstream.Upstream, cfg Config) (float64, error) { + ctx, cancel := context.WithTimeout(ctx, cfg.SpeedTestTimeout) + defer cancel() + transport := c.proxyTransport(ctx, up, cfg.DialTimeout) var lastErr error - for _, url := range speedTestURLs(cfg.SpeedTestURL) { - mbps, retryable, err := c.speedTestOne(ctx, up, url, cfg) + for _, rawURL := range speedTestURLs(cfg.SpeedTestURL) { + if err := ctx.Err(); err != nil { + return 0, err + } + mbps, err := probeSpeed(ctx, transport, rawURL) if err == nil { return mbps, nil } lastErr = err - if !retryable || ctx.Err() != nil { - return 0, err - } } if lastErr == nil { - lastErr = fmt.Errorf("no speedtest url") + lastErr = errors.New("no HTTPS speed test endpoint configured") } return 0, lastErr } -// speedTestOne downloads url through the proxy. retryable=true means the failure -// is host-side (worth trying another URL); retryable=false means we got a usable -// measurement or a proxy-side stall. -func (c *Checker) speedTestOne(ctx context.Context, up *upstream.Upstream, url string, cfg Config) (mbps float64, retryable bool, err error) { - client := c.proxyHTTPClient(up, cfg.DialTimeout, cfg.SpeedTestTimeout) - req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) - if err != nil { - return 0, false, err - } - req.Header.Set("User-Agent", "curl/8.0") - - start := time.Now() - resp, err := client.Do(req) - if err != nil { - return 0, true, err // dial/connection failure → try next host - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) - return 0, true, fmt.Errorf("status %d", resp.StatusCode) // 429 etc → try next host - } - n, _ := io.Copy(io.Discard, resp.Body) - elapsed := time.Since(start).Seconds() - if n <= 0 || elapsed <= 0 { - return 0, true, fmt.Errorf("empty body") // nothing downloaded → try next host - } - return float64(n) * 8 / 1024 / 1024 / elapsed, false, nil -} - -// speedTestURLs returns the configured URL first, then the fallbacks, de-duped. func speedTestURLs(primary string) []string { - seen := make(map[string]struct{}) out := make([]string, 0, len(DefaultSpeedTestURLs)+1) - add := func(u string) { - if u == "" { - return - } - if _, ok := seen[u]; ok { - return - } - seen[u] = struct{}{} - out = append(out, u) + if primary = strings.TrimSpace(primary); primary != "" { + out = append(out, primary) } - add(primary) - for _, u := range DefaultSpeedTestURLs { - add(u) + for _, endpoint := range DefaultSpeedTestURLs { + if !slices.Contains(out, endpoint) { + out = append(out, endpoint) + } } return out } -func extractIP(s string) string { - for _, tok := range strings.FieldsFunc(s, func(r rune) bool { - return r == ',' || r == ' ' || r == '"' || r == ':' || - r == '\n' || r == '\r' || r == '{' || r == '}' - }) { - if net.ParseIP(tok) != nil { - return tok +func probeExitIP(ctx context.Context, transport http.RoundTripper, rawURL string) (string, int, error) { + resp, startedAt, err := getProbe(ctx, transport, rawURL) + if err != nil { + return "", 0, err + } + latency := int(time.Since(startedAt).Milliseconds()) + defer resp.Body.Close() + if resp.ContentLength > maxExitIPBodyBytes { + return "", 0, errors.New("exit-IP response too large") + } + body, err := io.ReadAll(io.LimitReader(resp.Body, maxExitIPBodyBytes+1)) + if err != nil { + return "", 0, err + } + if len(body) > maxExitIPBodyBytes { + return "", 0, errors.New("exit-IP response too large") + } + ip, err := netip.ParseAddr(strings.Trim(string(body), " \t\r\n")) + if err != nil || ip.Zone() != "" || !isPublicExitIP(ip.Unmap()) { + return "", 0, errors.New("invalid public exit-IP response") + } + return ip.Unmap().String(), latency, nil +} + +// These IANA special-purpose blocks are not filtered by IsGlobalUnicast and +// IsPrivate. For IPv6, restrict to the current global unicast allocation first. +var ipv6GlobalUnicast = netip.MustParsePrefix("2000::/3") + +var specialExitIPPrefixes = [...]netip.Prefix{ + netip.MustParsePrefix("0.0.0.0/8"), + netip.MustParsePrefix("100.64.0.0/10"), + netip.MustParsePrefix("192.0.0.0/24"), + netip.MustParsePrefix("192.0.2.0/24"), + netip.MustParsePrefix("192.31.196.0/24"), + netip.MustParsePrefix("192.52.193.0/24"), + netip.MustParsePrefix("192.88.99.0/24"), + netip.MustParsePrefix("192.175.48.0/24"), + netip.MustParsePrefix("198.18.0.0/15"), + netip.MustParsePrefix("198.51.100.0/24"), + netip.MustParsePrefix("203.0.113.0/24"), + netip.MustParsePrefix("240.0.0.0/4"), + netip.MustParsePrefix("2001::/23"), + netip.MustParsePrefix("2001:db8::/32"), + netip.MustParsePrefix("2002::/16"), + netip.MustParsePrefix("2620:4f:8000::/48"), + netip.MustParsePrefix("3fff::/20"), +} + +func isPublicExitIP(ip netip.Addr) bool { + if !ip.IsGlobalUnicast() || ip.IsPrivate() || (ip.Is6() && !ipv6GlobalUnicast.Contains(ip)) { + return false + } + for _, prefix := range specialExitIPPrefixes { + if prefix.Contains(ip) { + return false } } - return "" + return true +} + +func probeSpeed(ctx context.Context, transport http.RoundTripper, rawURL string) (float64, error) { + resp, startedAt, err := getProbe(ctx, transport, rawURL) + if err != nil { + return 0, err + } + defer resp.Body.Close() + if resp.ContentLength >= 0 && (resp.ContentLength < minSpeedBodyBytes || resp.ContentLength > maxSpeedBodyBytes) { + return 0, fmt.Errorf("speed test body size out of bounds: %d bytes", resp.ContentLength) + } + n, err := io.Copy(io.Discard, io.LimitReader(resp.Body, maxSpeedBodyBytes+1)) + if err != nil { + return 0, err + } + if n < minSpeedBodyBytes || n > maxSpeedBodyBytes { + return 0, fmt.Errorf("speed test body size out of bounds: %d bytes", n) + } + elapsed := time.Since(startedAt).Seconds() + if elapsed <= 0 { + return 0, errors.New("no speed test duration") + } + return float64(n) * 8 / (1 << 20) / elapsed, nil +} + +func getProbe(ctx context.Context, transport http.RoundTripper, rawURL string) (*http.Response, time.Time, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil || req.URL.Scheme != "https" || req.URL.Hostname() == "" || req.URL.User != nil { + return nil, time.Time{}, errors.New("invalid HTTPS probe URL") + } + req.Header.Set("User-Agent", "curl/8.0") + req.Header.Set("Accept-Encoding", "identity") + startedAt := time.Now() + // RoundTrip sends exactly one request, including on redirect responses. + resp, err := transport.RoundTrip(req) + if err != nil { + return nil, time.Time{}, err + } + encodings := resp.Header.Values("Content-Encoding") + switch { + case resp.StatusCode != http.StatusOK: + err = fmt.Errorf("status %d", resp.StatusCode) + case len(encodings) > 1 || (len(encodings) == 1 && !strings.EqualFold(encodings[0], "identity")): + err = errors.New("unexpected probe content encoding") + case resp.ProtoMajor == 1 && resp.ContentLength < 0 && !slices.Contains(resp.TransferEncoding, "chunked"): + // A close-delimited response cannot distinguish EOF from interruption. + err = errors.New("unframed probe response") + default: + return resp, startedAt, nil + } + resp.Body.Close() + return nil, time.Time{}, err } func truncErr(err error) string { diff --git a/internal/checker/checker_test.go b/internal/checker/checker_test.go new file mode 100644 index 0000000..9776665 --- /dev/null +++ b/internal/checker/checker_test.go @@ -0,0 +1,274 @@ +package checker + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "slices" + "strconv" + "strings" + "sync" + "testing" + "testing/synctest" + "time" + + "git.eeee.moe/omar/zhguchiy_perchik/internal/config" + "git.eeee.moe/omar/zhguchiy_perchik/internal/upstream" +) + +func TestProbeExitIPAcceptsOnlySinglePublicAddress(t *testing.T) { + for _, tc := range []struct { + name string + body string + want string + }{ + {name: "IPv4", body: " 8.8.8.8\r\n", want: "8.8.8.8"}, + {name: "IPv6", body: "2606:4700:0000::1111\n", want: "2606:4700::1111"}, + {name: "mapped IPv4", body: "::ffff:8.8.8.8", want: "8.8.8.8"}, + {name: "JSON", body: `{"ip":"8.8.8.8"}`}, + {name: "multiple addresses", body: "8.8.8.8\n1.1.1.1"}, + {name: "zoned address", body: "2606:4700::1111%eth0"}, + {name: "private", body: "10.0.0.1"}, + {name: "shared", body: "100.64.0.1"}, + {name: "mapped loopback", body: "::ffff:127.0.0.1"}, + {name: "link local", body: "169.254.0.1"}, + {name: "multicast", body: "224.0.0.1"}, + {name: "benchmark", body: "198.18.0.1"}, + {name: "documentation IPv4", body: "203.0.113.1"}, + {name: "documentation IPv6", body: "3fff::1"}, + {name: "unique local", body: "fd00::1"}, + {name: "translation", body: "64:ff9b::808:808"}, + {name: "6to4", body: "2002:808:808::1"}, + {name: "oversized", body: "8.8.8.8" + strings.Repeat(" ", maxExitIPBodyBytes)}, + } { + t.Run(tc.name, func(t *testing.T) { + transport := roundTripFunc(func(*http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + ProtoMajor: 1, + ContentLength: -1, + TransferEncoding: []string{"chunked"}, + Body: io.NopCloser(strings.NewReader(tc.body)), + }, nil + }) + got, _, err := probeExitIP(t.Context(), transport, "https://probe.example/ip") + if got != tc.want || (err != nil) != (tc.want == "") { + t.Fatalf("exit IP = %q, error = %v; want %q", got, err, tc.want) + } + }) + } +} + +func TestProbeRejectsHTTPRedirectAndIncompleteExitIP(t *testing.T) { + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/redirect": + w.Header().Set("Location", "/must-not-follow") + w.WriteHeader(http.StatusFound) + case "/truncated": + w.Header().Set("Content-Length", "20") + case "/unavailable": + w.WriteHeader(http.StatusServiceUnavailable) + case "/must-not-follow", "/http": + t.Error("unexpected request to " + r.URL.Path) + } + _, _ = io.WriteString(w, "8.8.8.8\n") + })) + defer server.Close() + transport := server.Client().Transport + + ip, _, err := probeExitIP(t.Context(), transport, server.URL+"/ok") + if err != nil || ip != "8.8.8.8" { + t.Fatalf("complete HTTPS exit IP = %q, %v", ip, err) + } + for _, path := range []string{"/redirect", "/truncated", "/unavailable"} { + if ip, _, err := probeExitIP(t.Context(), transport, server.URL+path); err == nil || ip != "" { + t.Errorf("exit IP from %s = %q, %v; want error", path, ip, err) + } + } + insecureURL := "http://" + strings.TrimPrefix(server.URL, "https://") + "/http" + noRequest := roundTripFunc(func(*http.Request) (*http.Response, error) { + t.Error("insecure endpoint was contacted") + return nil, errors.New("unexpected request") + }) + if ip, _, err := probeExitIP(t.Context(), noRequest, insecureURL); err == nil || ip != "" { + t.Errorf("HTTP exit IP = %q, %v; want error", ip, err) + } + if speed, err := probeSpeed(t.Context(), noRequest, insecureURL); err == nil || speed != 0 { + t.Errorf("HTTP speed = %g, %v; want error and zero", speed, err) + } +} + +func TestProbeSpeedRequiresCompleteSufficientSample(t *testing.T) { + sample := strings.Repeat("x", minSpeedBodyBytes) + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Accept-Encoding") != "identity" { + t.Error("speed request did not request identity encoding") + } + switch r.URL.Path { + case "/complete": + w.Header().Set("Content-Length", strconv.Itoa(len(sample))) + case "/chunked": + w.(http.Flusher).Flush() + case "/truncated": + w.Header().Set("Content-Length", strconv.Itoa(len(sample)+1)) + case "/short": + _, _ = io.WriteString(w, "too short") + return + case "/encoded": + w.Header().Set("Content-Encoding", "gzip") + case "/unavailable": + w.WriteHeader(http.StatusServiceUnavailable) + } + _, _ = io.WriteString(w, sample) + })) + defer server.Close() + transport := server.Client().Transport + for _, path := range []string{"/complete", "/chunked"} { + if speed, err := probeSpeed(t.Context(), transport, server.URL+path); err != nil || speed <= 0 { + t.Errorf("speed from %s = %g, %v; want positive result", path, speed, err) + } + } + for _, path := range []string{"/truncated", "/short", "/encoded", "/unavailable"} { + if speed, err := probeSpeed(t.Context(), transport, server.URL+path); err == nil || speed != 0 { + t.Errorf("speed from %s = %g, %v; want error and zero", path, speed, err) + } + } +} + +func TestProbeSpeedBoundsUnknownLength(t *testing.T) { + body := &io.LimitedReader{R: zeroReader{}, N: maxSpeedBodyBytes + 1024} + transport := roundTripFunc(func(*http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + ProtoMajor: 1, + ContentLength: -1, + TransferEncoding: []string{"chunked"}, + Body: io.NopCloser(body), + }, nil + }) + if speed, err := probeSpeed(t.Context(), transport, "https://probe.example/download"); err == nil || speed != 0 { + t.Fatalf("oversized speed = %g, %v; want error and zero", speed, err) + } + if body.N != 1023 { + t.Errorf("read %d bytes, want %d", maxSpeedBodyBytes+1024-body.N, maxSpeedBodyBytes+1) + } +} + +func TestSpeedProbeDefaultsReplaceLegacySetting(t *testing.T) { + settings := config.FromMap(map[string]string{config.KeySpeedTestURL: "http://cachefly.cachefly.net/10mb.test"}) + if settings.SpeedTestURL != config.DefaultSpeedTestURL { + t.Fatalf("persisted legacy URL became %q, want %q", settings.SpeedTestURL, config.DefaultSpeedTestURL) + } + if got := speedTestURLs(settings.SpeedTestURL); !slices.Equal(got, DefaultSpeedTestURLs) { + t.Errorf("defaults = %v, want %v without duplicates", got, DefaultSpeedTestURLs) + } + for _, endpoint := range DefaultSpeedTestURLs { + if !strings.HasPrefix(endpoint, "https://") { + t.Errorf("insecure default speed URL %q", endpoint) + } + } + const custom = "https://probe.example/download" + settings = config.FromMap(map[string]string{config.KeySpeedTestURL: custom}) + if got := speedTestURLs(settings.SpeedTestURL); len(got) == 0 || got[0] != custom { + t.Errorf("custom URL is not first: %v", got) + } +} + +func TestDialTunnelClosesLateConnection(t *testing.T) { + for _, tc := range []struct { + name string + want error + }{ + {name: "timeout", want: context.DeadlineExceeded}, + {name: "parent cancellation", want: context.Canceled}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + local, peer := net.Pipe() + defer peer.Close() + conn := &trackedConn{Conn: local, closed: make(chan struct{})} + release := make(chan struct{}) + c := &Checker{dispatch: probeDialFunc(func(context.Context, *upstream.Upstream, string) (net.Conn, error) { + if tc.want == context.Canceled { + cancel() + } + <-release + return conn, nil + })} + got, err := c.dialTunnel(ctx, nil, "probe.example:443", time.Second) + close(release) + if got != nil || !errors.Is(err, tc.want) { + t.Errorf("dial = %v, %v; want %v", got, err, tc.want) + } + synctest.Wait() + select { + case <-conn.closed: + default: + t.Error("late connection was not closed") + } + }) + }) + } +} + +func TestDialTunnelTransfersOwnershipOnSuccess(t *testing.T) { + local, peer := net.Pipe() + defer peer.Close() + conn := &trackedConn{Conn: local, closed: make(chan struct{})} + dialContexts := make(chan context.Context, 1) + c := &Checker{dispatch: probeDialFunc(func(ctx context.Context, _ *upstream.Upstream, _ string) (net.Conn, error) { + dialContexts <- ctx + return conn, nil + })} + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + got, err := c.dialTunnel(ctx, nil, "probe.example:443", time.Second) + if err != nil || got != conn { + t.Fatalf("dial = %v, %v; want transferred connection", got, err) + } + defer got.Close() + if err := (<-dialContexts).Err(); !errors.Is(err, context.Canceled) { + t.Errorf("handshake context remains active: %v", err) + } + select { + case <-conn.closed: + t.Error("successful connection was closed before the caller was done") + default: + } +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +type zeroReader struct{} + +func (zeroReader) Read(p []byte) (int, error) { + clear(p) + return len(p), nil +} + +type probeDialFunc func(context.Context, *upstream.Upstream, string) (net.Conn, error) + +func (f probeDialFunc) Dial(ctx context.Context, up *upstream.Upstream, address string) (net.Conn, error) { + return f(ctx, up, address) +} + +type trackedConn struct { + net.Conn + closed chan struct{} + once sync.Once +} + +func (c *trackedConn) Close() error { + c.once.Do(func() { close(c.closed) }) + return c.Conn.Close() +} diff --git a/internal/config/config.go b/internal/config/config.go index 4cede5e..65245c8 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -25,6 +25,11 @@ const ( KeyTelegramNotifyFinish = "telegram_notify_finish" ) +// DefaultSpeedTestURL is the bounded HTTPS sample used for new installations. +const DefaultSpeedTestURL = "https://speedtest.selectel.ru/10MB" + +const legacySpeedTestURL = "http://cachefly.cachefly.net/10mb.test" + // Settings is the parsed, typed view of the settings table. type Settings struct { CheckIntervalHours float64 @@ -51,7 +56,7 @@ func Default() Settings { MaxLatencyMs: 1000, MinSpeedMbps: 3, SpeedTestEnabled: true, - SpeedTestURL: "http://cachefly.cachefly.net/10mb.test", + SpeedTestURL: DefaultSpeedTestURL, GeoIPDBURL: "https://cdn.jsdelivr.net/npm/@ip-location-db/geolite2-geo-whois-asn-country-mmdb/geolite2-geo-whois-asn-country.mmdb", AutoEnabled: true, TelegramNotifyFinish: true, @@ -76,7 +81,9 @@ func FromMap(m map[string]string) Settings { case KeySpeedTestEnabled: s.SpeedTestEnabled = parseBool(v, s.SpeedTestEnabled) case KeySpeedTestURL: - s.SpeedTestURL = v + if v != legacySpeedTestURL { + s.SpeedTestURL = v + } case KeyGeoIPDBURL: if v != "" { s.GeoIPDBURL = v diff --git a/internal/db/proxies.go b/internal/db/proxies.go index 44b9923..6e040cf 100644 --- a/internal/db/proxies.go +++ b/internal/db/proxies.go @@ -17,7 +17,7 @@ func (d *DB) EnsureProxy(ctx context.Context, canonicalURL, protocol, host strin // MarkProxyPass records a successful check on the history row. func (d *DB) MarkProxyPass(ctx context.Context, id int64, latencyMs int, speedMbps float64, country, exitIP string) error { - _, err := d.pool.Exec(ctx, + tag, err := d.pool.Exec(ctx, `UPDATE proxies SET last_alive = now(), consecutive_failures = 0, @@ -30,19 +30,19 @@ func (d *DB) MarkProxyPass(ctx context.Context, id int64, latencyMs int, speedMb updated_at = now() WHERE id = $1`, id, latencyMs, speedMbps, country, exitIP) - return err + return requireOneRow(tag, err) } // MarkProxyFail records a failed check on the history row. func (d *DB) MarkProxyFail(ctx context.Context, id int64) error { - _, err := d.pool.Exec(ctx, + tag, err := d.pool.Exec(ctx, `UPDATE proxies SET consecutive_failures = consecutive_failures + 1, total_checks = total_checks + 1, updated_at = now() WHERE id = $1`, id) - return err + return requireOneRow(tag, err) } // ProxyRef is a minimal reference used when rechecking a selection. diff --git a/internal/db/schema.sql b/internal/db/schema.sql index e68843c..53c6da0 100644 --- a/internal/db/schema.sql +++ b/internal/db/schema.sql @@ -178,7 +178,7 @@ INSERT INTO settings (key, value) VALUES ('max_latency_ms', '1000'), ('min_speed_mbps', '3'), ('speedtest_enabled', 'true'), - ('speedtest_url', 'http://cachefly.cachefly.net/10mb.test'), + ('speedtest_url', 'https://speedtest.selectel.ru/10MB'), ('geoip_db_url', 'https://cdn.jsdelivr.net/npm/@ip-location-db/geolite2-geo-whois-asn-country-mmdb/geolite2-geo-whois-asn-country.mmdb'), ('auto_enabled', 'true'), ('telegram_bot_token', ''), @@ -186,3 +186,7 @@ INSERT INTO settings (key, value) VALUES ('telegram_notify_start', 'false'), ('telegram_notify_finish', 'true') ON CONFLICT (key) DO NOTHING; + +-- Replace the old built-in HTTP URL without changing custom settings. +UPDATE settings SET value = 'https://speedtest.selectel.ru/10MB', updated_at = now() +WHERE key = 'speedtest_url' AND value = 'http://cachefly.cachefly.net/10mb.test'; diff --git a/internal/db/sessions.go b/internal/db/sessions.go index 8a04002..3149076 100644 --- a/internal/db/sessions.go +++ b/internal/db/sessions.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" ) // argf formats a single positional-parameter fragment, e.g. argf(" AND x=$%d", 3). @@ -17,38 +18,57 @@ func searchClause(idx int) string { return fmt.Sprintf(` AND (sp.canonical_url ILIKE $%d OR sp.host ILIKE $%d OR sp.exit_ip ILIKE $%d)`, idx, idx, idx) } +// ErrSessionCancelled indicates that the operator cancelled a session before publication. +var ErrSessionCancelled = errors.New("cancelled by operator") + +var errSessionIncomplete = errors.New("session is incomplete") + +func requireOneRow(tag pgconn.CommandTag, err error) error { + if err != nil { + return err + } + if tag.RowsAffected() != 1 { + return errors.New("expected one row to be written") + } + return nil +} + // CreateSession opens a new running session and returns its id. +// Unwritten progress counters use -1 internally so an untouched row cannot +// be published as a deliberately staged empty snapshot. func (d *DB) CreateSession(ctx context.Context, triggerKind string) (int64, error) { var id int64 err := d.pool.QueryRow(ctx, - `INSERT INTO check_sessions (status, trigger_kind) VALUES ('running', $1) RETURNING id`, + `INSERT INTO check_sessions (status, trigger_kind, progress_total, progress_done) + VALUES ('running', $1, -1, -1) RETURNING id`, triggerKind).Scan(&id) return id, err } // SetSessionTotals records the import accounting for a session. func (d *DB) SetSessionTotals(ctx context.Context, id int64, totalRaw, uniqueCandidates, collapsed, progressTotal int) error { - _, err := d.pool.Exec(ctx, + tag, err := d.pool.Exec(ctx, `UPDATE check_sessions SET total_raw_lines = $2, unique_candidates = $3, collapsed = $4, progress_total = $5 - WHERE id = $1`, + WHERE id = $1 AND status = 'running' AND NOT is_current`, id, totalRaw, uniqueCandidates, collapsed, progressTotal) - return err + return requireOneRow(tag, err) } // UpdateSessionProgress updates the live progress + running valid/invalid tally. func (d *DB) UpdateSessionProgress(ctx context.Context, id int64, done, valid, invalid int) error { - _, err := d.pool.Exec(ctx, - `UPDATE check_sessions SET progress_done = $2, valid = $3, invalid = $4 WHERE id = $1`, + tag, err := d.pool.Exec(ctx, + `UPDATE check_sessions SET progress_done = $2, valid = $3, invalid = $4 + WHERE id = $1 AND status = 'running' AND NOT is_current`, id, done, valid, invalid) - return err + return requireOneRow(tag, err) } // AddSessionProxy records a working proxy for the session (denormalized // metrics). On conflict it refreshes the metrics but keeps the original is_new // flag — this lets "recheck selected" update a proxy in the current session. func (d *DB) AddSessionProxy(ctx context.Context, sp *SessionProxy, sessionID int64) error { - _, err := d.pool.Exec(ctx, + tag, err := d.pool.Exec(ctx, `INSERT INTO session_proxies (session_id, proxy_id, canonical_url, protocol, host, port, source_name, latency_ms, speed_mbps, country, exit_ip, is_new) @@ -60,7 +80,7 @@ func (d *DB) AddSessionProxy(ctx context.Context, sp *SessionProxy, sessionID in exit_ip = EXCLUDED.exit_ip`, sessionID, sp.ProxyID, sp.CanonicalURL, sp.Protocol, sp.Host, sp.Port, sp.SourceName, sp.LatencyMs, sp.SpeedMbps, sp.Country, sp.ExitIP, sp.IsNew) - return err + return requireOneRow(tag, err) } // CurrentSessionProxyIDs returns the proxy ids present in the current session @@ -91,7 +111,7 @@ func (d *DB) BumpProtocolStat(ctx context.Context, sessionID int64, protocol str if passed { pass, fail = 1, 0 } - _, err := d.pool.Exec(ctx, + tag, err := d.pool.Exec(ctx, `INSERT INTO session_protocol_stats (session_id, protocol, checked, passed, failed) VALUES ($1, $2, 1, $3, $4) ON CONFLICT (session_id, protocol) DO UPDATE SET @@ -99,35 +119,31 @@ func (d *DB) BumpProtocolStat(ctx context.Context, sessionID int64, protocol str passed = session_protocol_stats.passed + $3, failed = session_protocol_stats.failed + $4`, sessionID, protocol, pass, fail) - return err + return requireOneRow(tag, err) } // UpsertSourceStat records/updates a source's contribution to a session. func (d *DB) UpsertSourceStat(ctx context.Context, sessionID int64, sourceName string, rawLines, uniqueCandidates int) error { - _, err := d.pool.Exec(ctx, + tag, err := d.pool.Exec(ctx, `INSERT INTO session_source_stats (session_id, source_name, raw_lines, unique_candidates, passed) VALUES ($1, $2, $3, $4, 0) ON CONFLICT (session_id, source_name) DO UPDATE SET raw_lines = session_source_stats.raw_lines + $3, unique_candidates = session_source_stats.unique_candidates + $4`, sessionID, sourceName, rawLines, uniqueCandidates) - return err + return requireOneRow(tag, err) } // BumpSourcePassed increments a source's passed count for a session. func (d *DB) BumpSourcePassed(ctx context.Context, sessionID int64, sourceName string) error { - _, err := d.pool.Exec(ctx, - `INSERT INTO session_source_stats (session_id, source_name, raw_lines, unique_candidates, passed) - VALUES ($1, $2, 0, 0, 1) - ON CONFLICT (session_id, source_name) DO UPDATE SET - passed = session_source_stats.passed + 1`, + tag, err := d.pool.Exec(ctx, + `UPDATE session_source_stats SET passed = passed + 1 WHERE session_id = $1 AND source_name = $2`, sessionID, sourceName) - return err + return requireOneRow(tag, err) } -// CompleteSession finalizes a session and atomically makes it the current one: -// the previous current session is unset and this one set, in a single tx so the -// panel/subscriptions switch over only on successful completion. +// CompleteSession verifies the staged results and atomically replaces the +// current session. All fetches, checks, and result writes happen before this. func (d *DB) CompleteSession(ctx context.Context, id int64, durationMs int64) error { tx, err := d.pool.Begin(ctx) if err != nil { @@ -135,15 +151,54 @@ func (d *DB) CompleteSession(ctx context.Context, id int64, durationMs int64) er } defer tx.Rollback(ctx) //nolint:errcheck // no-op after commit - if _, err := tx.Exec(ctx, - `UPDATE check_sessions SET is_current = false WHERE is_current AND id <> $1`, id); err != nil { + // Serialize with RequestCancel. A cancel that wins this lock must prevent + // publication, even if the worker has not polled for it yet. + var status string + var cancelled, current bool + if err := tx.QueryRow(ctx, `SELECT status, cancel_requested, is_current + FROM check_sessions WHERE id = $1 FOR UPDATE`, id).Scan(&status, &cancelled, ¤t); err != nil { return err } - if _, err := tx.Exec(ctx, - `UPDATE check_sessions - SET status = 'completed', is_current = true, finished_at = now(), duration_ms = $2 - WHERE id = $1`, - id, durationMs); err != nil { + if cancelled { + return ErrSessionCancelled + } + if status != "running" || current { + return errSessionIncomplete + } + var complete bool + if err := tx.QueryRow(ctx, `SELECT + cs.progress_total = cs.unique_candidates + AND cs.progress_done = cs.progress_total + AND cs.progress_done = cs.valid::bigint + cs.invalid + AND cs.valid >= 0 AND cs.invalid >= 0 + AND cs.collapsed >= 0 AND cs.total_raw_lines = cs.unique_candidates::bigint + cs.collapsed + AND cs.valid = (SELECT count(*) FROM session_proxies WHERE session_id = cs.id) + AND (cs.progress_done, cs.valid, cs.invalid) = ( + SELECT coalesce(sum(checked), 0), coalesce(sum(passed), 0), coalesce(sum(failed), 0) + FROM session_protocol_stats WHERE session_id = cs.id) + AND (cs.total_raw_lines, cs.unique_candidates, cs.valid) = ( + SELECT coalesce(sum(raw_lines), 0), coalesce(sum(unique_candidates), 0), coalesce(sum(passed), 0) + FROM session_source_stats WHERE session_id = cs.id) + FROM check_sessions cs WHERE cs.id = $1`, id).Scan(&complete); err != nil { + return err + } + if !complete { + return errSessionIncomplete + } + + var previous int64 + err = tx.QueryRow(ctx, `SELECT id FROM check_sessions WHERE is_current FOR UPDATE`).Scan(&previous) + switch { + case err == nil: + if err := requireOneRow(tx.Exec(ctx, `UPDATE check_sessions SET is_current = false WHERE id = $1`, previous)); err != nil { + return err + } + case !errors.Is(err, pgx.ErrNoRows): + return err + } + if err := requireOneRow(tx.Exec(ctx, `UPDATE check_sessions + SET status = 'completed', is_current = true, finished_at = now(), duration_ms = $2 + WHERE id = $1`, id, durationMs)); err != nil { return err } return tx.Commit(ctx) @@ -151,12 +206,12 @@ func (d *DB) CompleteSession(ctx context.Context, id int64, durationMs int64) er // FailSession marks a session cancelled/failed without touching the current pointer. func (d *DB) FailSession(ctx context.Context, id int64, status, errMsg string, durationMs int64) error { - _, err := d.pool.Exec(ctx, + tag, err := d.pool.Exec(ctx, `UPDATE check_sessions SET status = $2, finished_at = now(), duration_ms = $3, error = $4 - WHERE id = $1`, + WHERE id = $1 AND status = 'running' AND NOT is_current`, id, status, durationMs, errMsg) - return err + return requireOneRow(tag, err) } // FailStaleRunningSessions marks any sessions still in 'running' as failed. A @@ -172,9 +227,9 @@ func (d *DB) FailStaleRunningSessions(ctx context.Context) error { // RequestCancel sets the cancel flag on a running session. func (d *DB) RequestCancel(ctx context.Context, id int64) error { - _, err := d.pool.Exec(ctx, + tag, err := d.pool.Exec(ctx, `UPDATE check_sessions SET cancel_requested = true WHERE id = $1 AND status = 'running'`, id) - return err + return requireOneRow(tag, err) } // IsCancelRequested reports whether cancel was requested for a session. @@ -204,7 +259,7 @@ func (d *DB) GetSessionByID(ctx context.Context, id int64) (*Session, error) { const sessionCols = `id, status, trigger_kind, is_current, cancel_requested, started_at, finished_at, duration_ms, total_raw_lines, unique_candidates, collapsed, - progress_total, progress_done, valid, invalid, error` + greatest(progress_total, 0), greatest(progress_done, 0), valid, invalid, error` func (d *DB) scanSession(ctx context.Context, query string, args ...any) (*Session, error) { var s Session diff --git a/internal/db/sources.go b/internal/db/sources.go index 8d913e1..c9a0d08 100644 --- a/internal/db/sources.go +++ b/internal/db/sources.go @@ -68,8 +68,8 @@ func (d *DB) DeleteSource(ctx context.Context, id int64) error { // UpdateSourceFetchStats records the outcome of the last fetch of a source. func (d *DB) UpdateSourceFetchStats(ctx context.Context, id int64, lineCount int, errStr string) error { - _, err := d.pool.Exec(ctx, + tag, err := d.pool.Exec(ctx, `UPDATE sources SET last_fetched_at = now(), last_line_count = $2, last_error = $3 WHERE id = $1`, id, lineCount, errStr) - return err + return requireOneRow(tag, err) } diff --git a/internal/db/subscriptions.go b/internal/db/subscriptions.go index 2f51228..840bc72 100644 --- a/internal/db/subscriptions.go +++ b/internal/db/subscriptions.go @@ -66,19 +66,32 @@ func (d *DB) CreateSubscription(ctx context.Context, s *Subscription) (*Subscrip return scanSub(row) } -// UpdateSubscription updates an editable subscription's fields. -func (d *DB) UpdateSubscription(ctx context.Context, s *Subscription) (*Subscription, error) { - row := d.pool.QueryRow(ctx, - `UPDATE subscriptions SET - name=$2, enabled=$3, format=$4, filter_protocols=$5, filter_countries=$6, filter_sources=$7, - url_search=$8, max_latency_ms=$9, min_speed_mbps=$10, limit_n=$11, unique_ips=$12, unique_ips_metric=$13, - unique_ips_scope=$14, unique_subnet_v4=$15, unique_subnet_v6=$16, - sort_by=$17, expires_at=$18 - WHERE id=$1 RETURNING `+subCols, - s.ID, s.Name, s.Enabled, s.Format, s.FilterProtocols, s.FilterCountries, s.FilterSources, - s.URLSearch, s.MaxLatencyMs, s.MinSpeedMbps, s.LimitN, s.UniqueIPs, s.UniqueIPsMetric, - s.UniqueIPsScope, s.UniqueSubnetV4, s.UniqueSubnetV6, s.SortBy, s.ExpiresAt) - return scanSub(row) +// UpdateSubscription applies an edit to the latest stored subscription, or +// returns nil if it no longer exists. The row stays locked until the edit commits. +func (d *DB) UpdateSubscription(ctx context.Context, id int64, apply func(*Subscription)) (*Subscription, error) { + var updated *Subscription + err := pgx.BeginTxFunc(ctx, d.pool, pgx.TxOptions{IsoLevel: pgx.ReadCommitted}, func(tx pgx.Tx) error { + s, err := scanSub(tx.QueryRow(ctx, `SELECT `+subCols+` FROM subscriptions WHERE id = $1 FOR UPDATE`, id)) + if err != nil || s == nil { + return err + } + apply(s) + updated, err = scanSub(tx.QueryRow(ctx, + `UPDATE subscriptions SET + name=$2, enabled=$3, format=$4, filter_protocols=$5, filter_countries=$6, filter_sources=$7, + url_search=$8, max_latency_ms=$9, min_speed_mbps=$10, limit_n=$11, unique_ips=$12, unique_ips_metric=$13, + unique_ips_scope=$14, unique_subnet_v4=$15, unique_subnet_v6=$16, + sort_by=$17, expires_at=$18 + WHERE id=$1 RETURNING `+subCols, + id, s.Name, s.Enabled, s.Format, s.FilterProtocols, s.FilterCountries, s.FilterSources, + s.URLSearch, s.MaxLatencyMs, s.MinSpeedMbps, s.LimitN, s.UniqueIPs, s.UniqueIPsMetric, + s.UniqueIPsScope, s.UniqueSubnetV4, s.UniqueSubnetV6, s.SortBy, s.ExpiresAt)) + return err + }) + if err != nil { + return nil, err + } + return updated, nil } // DeleteSubscription removes a subscription. diff --git a/internal/db/subscriptions_test.go b/internal/db/subscriptions_test.go new file mode 100644 index 0000000..6d1cfb7 --- /dev/null +++ b/internal/db/subscriptions_test.go @@ -0,0 +1,98 @@ +package db + +import ( + "context" + "crypto/rand" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +func TestUpdateSubscriptionMergesConcurrentEdits(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("set TEST_DATABASE_URL to a PostgreSQL test database") + } + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + admin, err := pgx.Connect(ctx, dsn) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = admin.Close(context.Background()) }) + schema := "subscription_patch_" + strings.ToLower(rand.Text()) + quoted := pgx.Identifier{schema}.Sanitize() + if _, err := admin.Exec(ctx, "CREATE SCHEMA "+quoted); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := admin.Exec(cleanupCtx, "DROP SCHEMA IF EXISTS "+quoted+" CASCADE"); err != nil { + t.Errorf("drop test schema: %v", err) + } + }) + cfg, err := pgxpool.ParseConfig(dsn) + if err != nil { + t.Fatal(err) + } + cfg.ConnConfig.RuntimeParams["search_path"] = schema + cfg.MaxConns = 2 + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatal(err) + } + d := &DB{pool: pool} + t.Cleanup(d.Close) + if err := d.ApplySchema(ctx); err != nil { + t.Fatal(err) + } + + expires := time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC) + limit := 5 + created, err := d.CreateSubscription(ctx, &Subscription{ + Token: "test-token", Name: "Original", Enabled: false, Format: "plain", + FilterProtocols: []string{}, FilterCountries: []string{"DE"}, FilterSources: []string{}, URLSearch: []string{}, + LimitN: &limit, UniqueIPsMetric: "speed", UniqueIPsScope: "ip", UniqueSubnetV4: 24, UniqueSubnetV6: 48, + SortBy: []string{}, ExpiresAt: &expires, + }) + if err != nil || created == nil { + t.Fatalf("create test subscription: %v", err) + } + + edits := []func(*Subscription){ + func(s *Subscription) { s.Name = "Renamed" }, + func(s *Subscription) { s.LimitN = nil }, + } + start := make(chan struct{}) + results := make(chan error, len(edits)) + for _, edit := range edits { + go func() { + <-start + _, err := d.UpdateSubscription(ctx, created.ID, edit) + results <- err + }() + } + close(start) + for range edits { + if err := <-results; err != nil { + t.Errorf("update subscription: %v", err) + } + } + if t.Failed() { + return + } + + got, err := d.GetSubscriptionByToken(ctx, created.Token) + if err != nil || got == nil { + t.Fatalf("get edited subscription: %v", err) + } + if got.Name != "Renamed" || got.LimitN != nil || got.Enabled || got.ExpiresAt == nil || !expires.Equal(*got.ExpiresAt) || + len(got.FilterCountries) != 1 || got.FilterCountries[0] != "DE" { + t.Fatalf("concurrent edits did not merge or reset a restriction: %+v", got) + } +} diff --git a/internal/dialer/dialer.go b/internal/dialer/dialer.go index 05c243a..2b9fadb 100644 --- a/internal/dialer/dialer.go +++ b/internal/dialer/dialer.go @@ -6,11 +6,11 @@ import ( "log/slog" "net" - "git.qomar.pw/omar/zhguchiy_perchik/internal/dialer/shadowsocks" - "git.qomar.pw/omar/zhguchiy_perchik/internal/dialer/trojan" - "git.qomar.pw/omar/zhguchiy_perchik/internal/dialer/vless" - "git.qomar.pw/omar/zhguchiy_perchik/internal/dialer/vmess" - "git.qomar.pw/omar/zhguchiy_perchik/internal/upstream" + "git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/shadowsocks" + "git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/trojan" + "git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/vless" + "git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/vmess" + "git.eeee.moe/omar/zhguchiy_perchik/internal/upstream" ) // Dialer establishes a tunneled TCP connection to dest via the given upstream. diff --git a/internal/dialer/shadowsocks/dialer.go b/internal/dialer/shadowsocks/dialer.go index 7ec5d14..12b28d5 100644 --- a/internal/dialer/shadowsocks/dialer.go +++ b/internal/dialer/shadowsocks/dialer.go @@ -7,7 +7,7 @@ import ( "net" "time" - "git.qomar.pw/omar/zhguchiy_perchik/internal/upstream" + "git.eeee.moe/omar/zhguchiy_perchik/internal/upstream" ) type Dialer struct { diff --git a/internal/dialer/transport/grpc.go b/internal/dialer/transport/grpc.go index 688d892..80e1546 100644 --- a/internal/dialer/transport/grpc.go +++ b/internal/dialer/transport/grpc.go @@ -5,196 +5,358 @@ import ( "context" "crypto/tls" "encoding/binary" + "errors" "fmt" "io" + "mime" "net" "net/http" "net/url" + "slices" + "strconv" + "strings" "sync" "time" "golang.org/x/net/http2" + "golang.org/x/net/idna" +) + +const ( + grpcHeaderSize = 5 + grpcDataTag = 0x0a // Hunk.data: field 1, length-delimited + maxGRPCMessageSize = 4 << 20 // gRPC's default receive limit ) type GRPCConn struct { - response *http.Response - request *http.Request - rt http.RoundTripper // *http2.Transport or *http2.ClientConn - writer *io.PipeWriter - once sync.Once - closed bool - err error - remain int - br *bufio.Reader - mu sync.Mutex + conn net.Conn + client *http2.ClientConn + cancel context.CancelFunc + + // The request body may close before the response ends. Keep their + // pipes separate so deadlines and the two directions stay independent. + reader, readSink net.Conn + writer, writeSource net.Conn + + mu sync.Mutex + err error + done chan struct{} } -func (g *GRPCConn) initRequest() { - response, err := g.rt.RoundTrip(g.request) +func (g *GRPCConn) run(req *http.Request) { + response, err := g.client.RoundTrip(req) if err != nil { - g.err = err - g.writer.Close() + g.finish(fmt.Errorf("grpc: request: %w", err)) return } - g.mu.Lock() - defer g.mu.Unlock() - if !g.closed { - g.response = response - g.br = bufio.NewReader(response.Body) - } else { - response.Body.Close() + g.finish(g.receive(response)) + // The dedicated HTTP/2 connection is already closed, so closing the + // response body cannot block on a stalled write to the network. + _ = response.Body.Close() +} + +func (g *GRPCConn) receive(response *http.Response) error { + if response.StatusCode != http.StatusOK { + return fmt.Errorf("grpc: HTTP status %d", response.StatusCode) } + mediaType, _, err := mime.ParseMediaType(response.Header.Get("Content-Type")) + if err != nil || (mediaType != "application/grpc" && !strings.HasPrefix(mediaType, "application/grpc+")) { + return errors.New("grpc: unexpected content type") + } + if err := grpcStatusError(response.Header); err != nil { + return err + } + + reader := bufio.NewReader(response.Body) + for { + remaining, err := readGRPCPayloadLen(reader) + if err != nil { + if err == io.EOF { + if statusErr := grpcStatusError(response.Trailer); statusErr != nil { + return statusErr + } + } + return err + } + for remaining > 0 { + // Wait for some data, not a full buffer: peers can flush a + // message in several pieces. Backpressure stays on the stream. + if _, err := reader.Peek(1); err != nil { + return grpcRequiredBytesError(err) + } + size := min(reader.Buffered(), remaining) + chunk, _ := reader.Peek(size) + if _, err := g.readSink.Write(chunk); err != nil { + return err + } + _, _ = reader.Discard(size) + remaining -= size + } + } +} + +func readGRPCPayloadLen(reader *bufio.Reader) (int, error) { + var header [grpcHeaderSize]byte + if _, err := io.ReadFull(reader, header[:]); err != nil { + return 0, err + } + if header[0] != 0 { + return 0, errors.New("grpc: unsupported compression flag") + } + size := binary.BigEndian.Uint32(header[1:]) + if size > maxGRPCMessageSize { + return 0, errors.New("grpc: message exceeds receive limit") + } + if size == 0 { + return 0, nil // protobuf omits an empty bytes field + } + tag, err := reader.ReadByte() + if err != nil { + return 0, grpcRequiredBytesError(err) + } + if tag != grpcDataTag { + return 0, errors.New("grpc: unexpected protobuf field") + } + + var length [binary.MaxVarintLen64]byte + for i := range min(int(size)-1, len(length)) { + b, err := reader.ReadByte() + if err != nil { + return 0, grpcRequiredBytesError(err) + } + length[i] = b + if b < 0x80 { + payload, n := binary.Uvarint(length[:i+1]) + if n <= 0 || payload != uint64(int(size)-1-n) { + return 0, errors.New("grpc: protobuf payload length does not match the frame") + } + return int(payload), nil + } + } + return 0, errors.New("grpc: incomplete protobuf payload length") +} + +func grpcRequiredBytesError(err error) error { + if err == io.EOF { + return io.ErrUnexpectedEOF + } + return err +} + +func grpcStatusError(header http.Header) error { + status := header.Get("Grpc-Status") + if status == "" { + return nil + } + code, err := strconv.ParseUint(status, 10, 8) + if err != nil || code > 16 { + return errors.New("grpc: invalid status code") + } + if code != 0 { + return fmt.Errorf("grpc: status code %d", code) + } + return nil +} + +type grpcRequestBody struct { + io.ReadCloser +} + +func (body grpcRequestBody) Read(p []byte) (int, error) { + // HTTP/2 supplies a DATA frame buffer. Frame a bounded chunk of the + // tunnel byte stream in place, including after a partial caller write. + const prefixSize = grpcHeaderSize + 1 + 2 + const maxChunk = 1<<14 - 1 // fits in two protobuf varint bytes + if len(p) <= prefixSize { + return 0, io.ErrShortBuffer + } + n, err := body.ReadCloser.Read(p[prefixSize:min(len(p), prefixSize+maxChunk)]) + if n == 0 { + return 0, err + } + p[0] = 0 + p[grpcHeaderSize] = grpcDataTag + lengthSize := binary.PutUvarint(p[grpcHeaderSize+1:], uint64(n)) + headerSize := grpcHeaderSize + 1 + lengthSize + if headerSize != prefixSize { + copy(p[headerSize:], p[prefixSize:prefixSize+n]) + } + binary.BigEndian.PutUint32(p[1:grpcHeaderSize], uint32(1+lengthSize+n)) + return headerSize + n, err } func (g *GRPCConn) Read(b []byte) (int, error) { - g.once.Do(g.initRequest) - if g.err != nil { - return 0, g.err + if len(b) == 0 { + return 0, nil } - - g.mu.Lock() - defer g.mu.Unlock() - - if g.remain > 0 { - size := g.remain - if len(b) < size { - size = len(b) - } - n, err := io.ReadFull(g.br, b[:size]) - g.remain -= n - return n, err - } - - if g.response == nil { - return 0, io.ErrClosedPipe - } - - // Read gRPC frame header: 1 byte compressed flag + 4 bytes length - header := make([]byte, 5) - if _, err := io.ReadFull(g.br, header); err != nil { - return 0, err - } - - // Skip protobuf field 1 tag byte (0x0A = field 1, wire type 2) - if _, err := g.br.ReadByte(); err != nil { - return 0, err - } - - // Read the actual payload length as varint - uLen, err := binary.ReadUvarint(g.br) - if err != nil { - return 0, err - } - - size := int(uLen) - n := size - if len(b) < size { - n = len(b) - } - - read, err := io.ReadFull(g.br, b[:n]) - if read < size { - g.remain = size - read - } - return read, err + n, err := g.reader.Read(b) + return n, g.streamError(err, false) } func (g *GRPCConn) Write(b []byte) (int, error) { - // Protobuf field tag 0x0A (field 1, wire type 2 = length-delimited) + varint length - protoHeader := make([]byte, 1+binary.MaxVarintLen64) - protoHeader[0] = 0x0A - varintSize := binary.PutUvarint(protoHeader[1:], uint64(len(b))) + if len(b) == 0 { + return 0, nil + } + n, err := g.writer.Write(b) + return n, g.streamError(err, true) +} - payloadLen := 1 + varintSize + len(b) +func (g *GRPCConn) streamError(err error, writing bool) error { + if err != io.ErrClosedPipe && err != io.EOF { + return err + } + g.mu.Lock() + terminal := g.err + g.mu.Unlock() + if terminal == nil || (writing && terminal == io.EOF) { + return net.ErrClosed + } + return terminal +} - // gRPC frame header: 1 byte compressed (0) + 4 bytes big-endian length - grpcHeader := make([]byte, 5) - binary.BigEndian.PutUint32(grpcHeader[1:5], uint32(payloadLen)) +func (g *GRPCConn) finish(err error) { + g.mu.Lock() + if g.err != nil { + g.mu.Unlock() + <-g.done + return + } + g.err = err + g.mu.Unlock() - buf := append(grpcHeader, protoHeader[:1+varintSize]...) - buf = append(buf, b...) - - _, err := g.writer.Write(buf) - return len(b), err + _ = g.readSink.Close() + _ = g.writeSource.Close() + g.cancel() + // TLS wrappers may try to send a close notification. Interrupt the + // underlying socket first so that Close works with an unresponsive peer. + if tlsConn, ok := g.conn.(interface{ NetConn() net.Conn }); ok { + _ = tlsConn.NetConn().Close() + } + _ = g.client.Close() + close(g.done) } func (g *GRPCConn) Close() error { - g.mu.Lock() - g.closed = true - if g.response != nil { - g.response.Body.Close() - } - g.mu.Unlock() - return g.writer.Close() + g.finish(net.ErrClosed) + return nil } -func (g *GRPCConn) LocalAddr() net.Addr { return &net.TCPAddr{IP: net.IPv4zero, Port: 0} } -func (g *GRPCConn) RemoteAddr() net.Addr { return &net.TCPAddr{IP: net.IPv4zero, Port: 0} } -func (g *GRPCConn) SetDeadline(t time.Time) error { return nil } -func (g *GRPCConn) SetReadDeadline(t time.Time) error { return nil } -func (g *GRPCConn) SetWriteDeadline(t time.Time) error { return nil } +func (g *GRPCConn) LocalAddr() net.Addr { return g.conn.LocalAddr() } +func (g *GRPCConn) RemoteAddr() net.Addr { return g.conn.RemoteAddr() } + +func (g *GRPCConn) SetDeadline(t time.Time) error { + readErr := g.SetReadDeadline(t) + writeErr := g.SetWriteDeadline(t) + if readErr != nil { + return readErr + } + return writeErr +} + +func (g *GRPCConn) SetReadDeadline(t time.Time) error { return g.reader.SetReadDeadline(t) } +func (g *GRPCConn) SetWriteDeadline(t time.Time) error { return g.writer.SetWriteDeadline(t) } // DialGRPC establishes a gRPC tunnel, creating a new TLS connection internally. // Used for standard TLS (non-Reality) transports. func DialGRPC(ctx context.Context, addr string, serviceName string, tlsConfig *tls.Config) (net.Conn, error) { - if serviceName == "" { - serviceName = "GunService" + host, port, err := net.SplitHostPort(addr) + if err != nil { + host = strings.TrimPrefix(strings.TrimSuffix(addr, "]"), "[") } - - t := &http2.Transport{ - TLSClientConfig: tlsConfig, - AllowHTTP: false, - DisableCompression: true, + if port == "" { + port = "443" } - - reader, writer := io.Pipe() - conn := &GRPCConn{ - request: newGRPCRequest(addr, serviceName, reader), - rt: t, - writer: writer, + if ascii, err := idna.ToASCII(host); err == nil { + host = ascii } - go conn.once.Do(conn.initRequest) - return conn, nil + config := new(tls.Config) + if tlsConfig != nil { + config = tlsConfig.Clone() + } + if !slices.Contains(config.NextProtos, http2.NextProtoTLS) { + config.NextProtos = append([]string{http2.NextProtoTLS}, config.NextProtos...) + } + dialer := tls.Dialer{Config: config} + conn, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort(host, port)) + if err != nil { + return nil, fmt.Errorf("grpc: TLS dial: %w", err) + } + if state := conn.(*tls.Conn).ConnectionState(); state.NegotiatedProtocol != http2.NextProtoTLS { + closeGRPCSetupConn(conn) + return nil, errors.New("grpc: TLS did not negotiate HTTP/2") + } + return DialGRPCOverConn(ctx, conn, addr, serviceName) } -// DialGRPCOverConn establishes a gRPC tunnel over an already-established connection. -// The conn must already be at the application layer (e.g., after a Reality or TLS handshake). -// http2.Transport.NewClientConn skips the ALPN check for non-*tls.Conn types, -// so passing a *utls.UConn from a Reality handshake works correctly. +// DialGRPCOverConn establishes a gRPC tunnel over an already-established +// application-layer connection and takes ownership of it, including on error. func DialGRPCOverConn(ctx context.Context, conn net.Conn, addr string, serviceName string) (net.Conn, error) { + if err := ctx.Err(); err != nil { + closeGRPCSetupConn(conn) + return nil, err + } if serviceName == "" { serviceName = "GunService" } - t := &http2.Transport{ - AllowHTTP: false, - DisableCompression: true, + // NewClientConn writes the HTTP/2 preface synchronously and has no + // context argument. Closing the socket interrupts that write on cancel. + closed := make(chan struct{}) + stop := context.AfterFunc(ctx, func() { + closeGRPCSetupConn(conn) + close(closed) + }) + t := http2.Transport{DisableCompression: true} + client, err := t.NewClientConn(conn) + if !stop() { + <-closed + if client != nil { + _ = client.Close() + } + return nil, ctx.Err() } - - h2conn, err := t.NewClientConn(conn) if err != nil { + // NewClientConn closes the connection if the preface write fails. return nil, fmt.Errorf("grpc: h2 client conn: %w", err) } - reader, writer := io.Pipe() - grpcConn := &GRPCConn{ - request: newGRPCRequest(addr, serviceName, reader), - rt: h2conn, - writer: writer, + // Response headers can depend on an initial tunnel write. Start the + // request asynchronously, independent of the completed dial context. + requestCtx, cancel := context.WithCancel(context.Background()) + reader, readSink := net.Pipe() + writer, writeSource := net.Pipe() + g := &GRPCConn{ + conn: conn, + client: client, + cancel: cancel, + reader: reader, + readSink: readSink, + writer: writer, + writeSource: writeSource, + done: make(chan struct{}), } - go grpcConn.once.Do(grpcConn.initRequest) - return grpcConn, nil + req := newGRPCRequest(addr, serviceName, grpcRequestBody{writeSource}) + go g.run(req.WithContext(requestCtx)) + return g, nil +} + +func closeGRPCSetupConn(conn net.Conn) { + if tlsConn, ok := conn.(interface{ NetConn() net.Conn }); ok { + conn = tlsConn.NetConn() + } + _ = conn.Close() } func newGRPCRequest(addr, serviceName string, body io.ReadCloser) *http.Request { return &http.Request{ - Method: http.MethodPost, - Body: body, + Method: http.MethodPost, + Body: body, + ContentLength: -1, URL: &url.URL{ Scheme: "https", Host: addr, - Path: fmt.Sprintf("/%s/Tun", serviceName), + Path: "/" + serviceName + "/Tun", }, Proto: "HTTP/2", ProtoMajor: 2, diff --git a/internal/dialer/transport/grpc_test.go b/internal/dialer/transport/grpc_test.go new file mode 100644 index 0000000..3e840cd --- /dev/null +++ b/internal/dialer/transport/grpc_test.go @@ -0,0 +1,284 @@ +package transport + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "testing" + "time" + + "golang.org/x/net/http2" +) + +const grpcTestTimeout = 3 * time.Second + +func TestGRPCTLSRoundTripAfterDialCancellation(t *testing.T) { + first := []byte("initial tunnel data") + second := bytes.Repeat([]byte("b"), 300) + wantRequest := append(grpcTestFrame(first), grpcTestFrame(second)...) + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/Tunnel/Tun" || r.ProtoMajor != 2 { + t.Errorf("unexpected gRPC request path or protocol: %s %s", r.URL.Path, r.Proto) + return + } + got := make([]byte, len(wantRequest)) + if _, err := io.ReadFull(r.Body, got); err != nil || !bytes.Equal(got, wantRequest) { + t.Errorf("request frames did not match: %v", err) + return + } + + w.Header().Set("Content-Type", "application/grpc+proto") + w.Header().Set("Trailer", "Grpc-Status") + frame := grpcTestFrame(second) + for _, chunk := range [][]byte{make([]byte, 5), grpcTestFrame(nil), grpcTestFrame(first), frame[:3], frame[3:]} { + if _, err := w.Write(chunk); err != nil { + t.Errorf("writing gRPC response: %v", err) + return + } + w.(http.Flusher).Flush() + } + w.Header().Set("Grpc-Status", "0") + })) + server.EnableHTTP2 = true + server.StartTLS() + t.Cleanup(server.Close) + + ctx, cancel := context.WithTimeout(t.Context(), grpcTestTimeout) + tlsConfig := server.Client().Transport.(*http.Transport).TLSClientConfig + conn, err := DialGRPC(ctx, server.Listener.Addr().String(), "Tunnel", tlsConfig) + cancel() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + if err := conn.SetDeadline(time.Now().Add(grpcTestTimeout)); err != nil { + t.Fatal(err) + } + for _, payload := range [][]byte{first, second} { + if n, err := conn.Write(payload); n != len(payload) || err != nil { + t.Fatalf("initial write = %d, %v; want %d, nil", n, err, len(payload)) + } + } + want := append(bytes.Clone(first), second...) + got := make([]byte, len(want)) + for off := 0; off < len(got); { + size := min(11, len(got)-off) + if _, err := io.ReadFull(conn, got[off:off+size]); err != nil { + t.Fatal(err) + } + off += size + } + if !bytes.Equal(got, want) { + t.Fatal("response did not match the tunnel bytes") + } + if n, err := conn.Read(got[:1]); n != 0 || err != io.EOF { + t.Fatalf("final read = %d, %v; want EOF", n, err) + } +} + +func TestGRPCCloseWhileWaitingForHeaders(t *testing.T) { + started, stopped := make(chan struct{}), make(chan struct{}) + conn, peerClosed := grpcTestDialOverPipe(t, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/GunService/Tun" { + t.Errorf("default service path = %q", r.URL.Path) + } + close(started) + <-r.Context().Done() + close(stopped) + })) + grpcTestWait(t, started) + + readErr := make(chan error, 1) + go func() { + var b [1]byte + _, err := conn.Read(b[:]) + readErr <- err + }() + closeErr := make(chan error, 1) + go func() { closeErr <- conn.Close() }() + if err := grpcTestWait(t, closeErr); err != nil { + t.Fatal(err) + } + if err := grpcTestWait(t, readErr); !errors.Is(err, net.ErrClosed) { + t.Fatalf("read after close: %v", err) + } + grpcTestWait(t, stopped) + grpcTestWait(t, peerClosed) +} + +func TestGRPCCancelDuringHTTP2Preface(t *testing.T) { + client, server := net.Pipe() + defer client.Close() + defer server.Close() + writing := make(chan struct{}, 1) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + result := make(chan error, 1) + go func() { + conn, err := DialGRPCOverConn(ctx, grpcTestSetupConn{Conn: client, writing: writing}, "tunnel.test", "") + if conn != nil { + _ = conn.Close() + } + result <- err + }() + grpcTestWait(t, writing) + cancel() + if err := grpcTestWait(t, result); !errors.Is(err, context.Canceled) { + t.Fatalf("dial returned %v; want context cancellation", err) + } + if err := server.SetReadDeadline(time.Now().Add(grpcTestTimeout)); err != nil && !errors.Is(err, io.ErrClosedPipe) { + t.Fatal(err) + } + var b [1]byte + if n, err := server.Read(b[:]); n != 0 || err != io.EOF { + t.Fatalf("underlying peer read = %d, %v; want EOF", n, err) + } +} + +func TestGRPCDeadlinesCanBeReset(t *testing.T) { + respond := make(chan struct{}) + payload := []byte("hello") + conn, _ := grpcTestDialOverPipe(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + want := grpcTestFrame(payload) + got := make([]byte, len(want)) + if _, err := io.ReadFull(r.Body, got); err != nil || !bytes.Equal(got, want) { + t.Errorf("reading valid request frame: %v", err) + return + } + select { + case <-respond: + case <-r.Context().Done(): + return + } + w.Header().Set("Content-Type", "application/grpc") + _, _ = w.Write(grpcTestFrame(payload)) + })) + if err := conn.SetDeadline(time.Now().Add(-time.Second)); err != nil { + t.Fatal(err) + } + if n, err := conn.Write(payload); n != 0 || !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("expired write = %d, %v", n, err) + } + if err := conn.SetWriteDeadline(time.Now().Add(grpcTestTimeout)); err != nil { + t.Fatal(err) + } + if n, err := conn.Write(payload); n != len(payload) || err != nil { + t.Fatalf("write after reset = %d, %v", n, err) + } + got := make([]byte, len(payload)) + if n, err := conn.Read(got); n != 0 || !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("expired read = %d, %v", n, err) + } + if err := conn.SetReadDeadline(time.Now().Add(30 * time.Millisecond)); err != nil { + t.Fatal(err) + } + if n, err := conn.Read(got); n != 0 || !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("read while waiting for headers = %d, %v", n, err) + } + if err := conn.SetReadDeadline(time.Now().Add(grpcTestTimeout)); err != nil { + t.Fatal(err) + } + close(respond) + if _, err := io.ReadFull(conn, got); err != nil || !bytes.Equal(got, payload) { + t.Fatalf("read after reset = %q, %v", got, err) + } +} + +func TestGRPCWriteDeadlineWhileFlowControlled(t *testing.T) { + started := make(chan struct{}) + conn, _ := grpcTestDialOverPipe(t, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + close(started) + <-r.Context().Done() + })) + grpcTestWait(t, started) + if err := conn.SetWriteDeadline(time.Now().Add(30 * time.Millisecond)); err != nil { + t.Fatal(err) + } + payload := make([]byte, 128<<10) + if n, err := conn.Write(payload); n >= len(payload) || !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("flow-controlled write = %d, %v; want a timeout", n, err) + } +} + +func TestGRPCRejectsTruncatedResponse(t *testing.T) { + payload := []byte("response") + conn, _ := grpcTestDialOverPipe(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/grpc") + w.Header().Set("Trailer", "Grpc-Status") + frame := grpcTestFrame(payload) + _, _ = w.Write(frame[:len(frame)-1]) + w.Header().Set("Grpc-Status", "0") + })) + if err := conn.SetReadDeadline(time.Now().Add(grpcTestTimeout)); err != nil { + t.Fatal(err) + } + got, err := io.ReadAll(conn) + if !errors.Is(err, io.ErrUnexpectedEOF) || !bytes.Equal(got, payload[:len(payload)-1]) { + t.Fatalf("truncated response = %q, %v; want payload prefix and unexpected EOF", got, err) + } +} + +func grpcTestDialOverPipe(t *testing.T, handler http.Handler) (net.Conn, <-chan struct{}) { + t.Helper() + client, peer := net.Pipe() + server := http2.Server{MaxUploadBufferPerStream: 65535} + closed := make(chan struct{}) + go func() { + defer close(closed) + server.ServeConn(peer, &http2.ServeConnOpts{Handler: handler}) + }() + ctx, cancel := context.WithTimeout(t.Context(), grpcTestTimeout) + defer cancel() + conn, err := DialGRPCOverConn(ctx, client, "tunnel.test", "") + t.Cleanup(func() { + _ = peer.Close() + _ = client.Close() + if conn != nil { + _ = conn.Close() + } + }) + if err != nil { + t.Fatal(err) + } + return conn, closed +} + +func grpcTestFrame(payload []byte) []byte { + frame := make([]byte, 5, 16+len(payload)) + frame = append(frame, 0x0a) + frame = binary.AppendUvarint(frame, uint64(len(payload))) + frame = append(frame, payload...) + binary.BigEndian.PutUint32(frame[1:], uint32(len(frame)-5)) + return frame +} + +func grpcTestWait[T any](t *testing.T, ch <-chan T) T { + t.Helper() + select { + case v := <-ch: + return v + case <-time.After(grpcTestTimeout): + t.Fatal("timed out waiting for gRPC stream") + var zero T + return zero + } +} + +type grpcTestSetupConn struct { + net.Conn + writing chan struct{} +} + +func (c grpcTestSetupConn) Write(p []byte) (int, error) { + select { + case c.writing <- struct{}{}: + default: + } + return c.Conn.Write(p) +} diff --git a/internal/dialer/transport/ws.go b/internal/dialer/transport/ws.go index b2c0e09..ca3cd33 100644 --- a/internal/dialer/transport/ws.go +++ b/internal/dialer/transport/ws.go @@ -2,7 +2,7 @@ package transport import ( "context" - cryptotls "crypto/tls" + "crypto/tls" "fmt" "io" "net" @@ -53,16 +53,16 @@ func (c *WSConn) SetDeadline(t time.Time) error { return c.Conn.SetWriteDeadline(t) } -func DialWS(ctx context.Context, network, addr string, path string, host string, tls bool) (net.Conn, error) { +func DialWS(ctx context.Context, addr, path, host string, tlsConfig *tls.Config) (net.Conn, error) { scheme := "ws" - if tls { + if tlsConfig != nil { scheme = "wss" } u := url.URL{Scheme: scheme, Host: addr, Path: path} dialer := &websocket.Dialer{ HandshakeTimeout: 10 * time.Second, - TLSClientConfig: &cryptotls.Config{InsecureSkipVerify: true}, + TLSClientConfig: tlsConfig, } header := http.Header{} diff --git a/internal/dialer/transport/ws_test.go b/internal/dialer/transport/ws_test.go new file mode 100644 index 0000000..511cb29 --- /dev/null +++ b/internal/dialer/transport/ws_test.go @@ -0,0 +1,140 @@ +package transport_test + +import ( + "context" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "errors" + "fmt" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gorilla/websocket" + + "git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/transport" + "git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/trojan" + "git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/vless" + "git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/vmess" + "git.eeee.moe/omar/zhguchiy_perchik/internal/upstream" +) + +func TestDialWSVerifiesTLSAndSeparatesSNIFromHost(t *testing.T) { + type requestNames struct{ host, sni string } + requests := make(chan requestNames, 4) + upgrader := websocket.Upgrader{} + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ws, err := upgrader.Upgrade(w, r, nil) + if err != nil { + t.Errorf("upgrade: %v", err) + return + } + defer ws.Close() + requests <- requestNames{r.Host, r.TLS.ServerName} + })) + t.Cleanup(server.Close) + + addr := strings.TrimPrefix(server.URL, "https://") + roots := x509.NewCertPool() + roots.AddCert(server.Certificate()) + const host = "route.example.invalid" + + for _, tc := range []struct { + name, sni string + roots *x509.CertPool + wantErr error + }{ + {name: "explicit SNI", sni: "example.com", roots: roots}, + {name: "endpoint SNI fallback", roots: roots}, + {name: "wrong certificate name", sni: "wrong.invalid", roots: roots, wantErr: x509.HostnameError{}}, + {name: "untrusted certificate", sni: "example.com", roots: x509.NewCertPool(), wantErr: x509.UnknownAuthorityError{}}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + conn, err := transport.DialWS(ctx, addr, "/tunnel", host, &tls.Config{ + ServerName: tc.sni, + RootCAs: tc.roots, + MinVersion: tls.VersionTLS12, + }) + if conn != nil { + defer conn.Close() + } + switch tc.wantErr.(type) { + case x509.HostnameError: + var want x509.HostnameError + if conn != nil || !errors.As(err, &want) { + t.Fatalf("expected hostname verification failure, got %v", err) + } + case x509.UnknownAuthorityError: + var want x509.UnknownAuthorityError + if conn != nil || !errors.As(err, &want) { + t.Fatalf("expected certificate trust failure, got %v", err) + } + default: + if err != nil { + t.Fatal(err) + } + select { + case got := <-requests: + if want := (requestNames{host, tc.sni}); got != want { + t.Errorf("request names = %+v, want %+v", got, want) + } + case <-ctx.Done(): + t.Fatal("WebSocket request not observed") + } + } + }) + } +} + +func TestProxyDialersRejectUntrustedCertificates(t *testing.T) { + server := httptest.NewTLSServer(http.NotFoundHandler()) + t.Cleanup(server.Close) + addr := strings.TrimPrefix(server.URL, "https://") + host, port, err := net.SplitHostPort(addr) + if err != nil { + t.Fatal(err) + } + const id = "12345678-1234-4234-8234-123456789abc" + for _, tc := range []struct { + name string + link func(string) string + dial func(context.Context, *upstream.Upstream, string) (net.Conn, error) + }{ + {"vless", func(network string) string { + return "vless://" + id + "@" + addr + "?security=tls&type=" + network + "&allowInsecure=1" + }, (&vless.Dialer{}).Dial}, + {"trojan", func(network string) string { + return "trojan://password@" + addr + "?type=" + network + "&allowInsecure=1" + }, (&trojan.Dialer{}).Dial}, + {"vmess", func(network string) string { + data := fmt.Sprintf(`{"add":%q,"port":%q,"id":%q,"net":%q,"tls":"tls","allowInsecure":true}`, host, port, id, network) + return "vmess://" + base64.StdEncoding.EncodeToString([]byte(data)) + }, (&vmess.Dialer{}).Dial}, + } { + for _, network := range []string{"tcp", "ws"} { + t.Run(tc.name+"/"+network, func(t *testing.T) { + _, up, err := upstream.Canonicalize(tc.link(network)) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + conn, err := tc.dial(ctx, up, "destination.example:443") + if conn != nil { + conn.Close() + t.Fatal("dial succeeded with an untrusted certificate") + } + var want x509.UnknownAuthorityError + if !errors.As(err, &want) { + t.Fatalf("expected certificate trust failure, got %v", err) + } + }) + } + } +} diff --git a/internal/dialer/trojan/dialer.go b/internal/dialer/trojan/dialer.go index 8408aa0..6b22c46 100644 --- a/internal/dialer/trojan/dialer.go +++ b/internal/dialer/trojan/dialer.go @@ -10,8 +10,8 @@ import ( "net" "time" - "git.qomar.pw/omar/zhguchiy_perchik/internal/dialer/transport" - "git.qomar.pw/omar/zhguchiy_perchik/internal/upstream" + "git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/transport" + "git.eeee.moe/omar/zhguchiy_perchik/internal/upstream" ) type Dialer struct { @@ -29,31 +29,32 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) ( timeout = 10 * time.Second } - var conn net.Conn - var err error - - // 1. Establish underlay connection - switch up.Transport { - case "ws": + var tlsConfig *tls.Config + if up.Trojan.Security != "none" { sni := up.Trojan.SNI if sni == "" { sni = up.Host } - conn, err = transport.DialWS(ctx, "tcp", up.Address(), up.Path, sni, up.Trojan.Security == "tls") - case "grpc": - tlsConfig := &tls.Config{ - ServerName: up.Trojan.SNI, - InsecureSkipVerify: true, + tlsConfig = &tls.Config{ServerName: sni, MinVersion: tls.VersionTLS12} + } + + var conn net.Conn + var err error + + // 1. Establish underlay connection + switch { + case up.Transport == "ws": + host := up.Header["Host"] + if host == "" && tlsConfig != nil { + host = tlsConfig.ServerName } + conn, err = transport.DialWS(ctx, up.Address(), up.Path, host, tlsConfig) + case up.Transport == "grpc" && tlsConfig != nil: conn, err = transport.DialGRPC(ctx, up.Address(), up.ServiceName, tlsConfig) - default: + case up.Transport == "" || up.Transport == "tcp" || up.Transport == "raw" || up.Transport == "grpc": dialer := net.Dialer{Timeout: timeout} conn, err = dialer.DialContext(ctx, "tcp", up.Address()) - if err == nil && up.Trojan.Security != "none" { - tlsConfig := &tls.Config{ - ServerName: up.Trojan.SNI, - InsecureSkipVerify: true, - } + if err == nil && tlsConfig != nil { tlsConn := tls.Client(conn, tlsConfig) if err = tlsConn.HandshakeContext(ctx); err != nil { conn.Close() @@ -61,6 +62,16 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) ( } conn = tlsConn } + if err == nil && up.Transport == "grpc" { + grpcConn, grpcErr := transport.DialGRPCOverConn(ctx, conn, up.Address(), up.ServiceName) + if grpcErr != nil { + conn.Close() + return nil, fmt.Errorf("trojan: connect: %w", grpcErr) + } + conn = grpcConn + } + default: + return nil, fmt.Errorf("trojan: unsupported transport") } if err != nil { diff --git a/internal/dialer/vless/dialer.go b/internal/dialer/vless/dialer.go index 9e36d39..19f5a87 100644 --- a/internal/dialer/vless/dialer.go +++ b/internal/dialer/vless/dialer.go @@ -8,8 +8,8 @@ import ( "net" "time" - "git.qomar.pw/omar/zhguchiy_perchik/internal/dialer/transport" - "git.qomar.pw/omar/zhguchiy_perchik/internal/upstream" + "git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/transport" + "git.eeee.moe/omar/zhguchiy_perchik/internal/upstream" ) type Dialer struct { @@ -32,26 +32,36 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) ( timeout = 10 * time.Second } + sni := up.VLESS.SNI + if sni == "" { + sni = up.Host + } + var tlsConfig *tls.Config + if up.VLESS.Security == "tls" { + tlsConfig = &tls.Config{ServerName: sni, MinVersion: tls.VersionTLS12} + } + var c net.Conn var err error switch up.Transport { case "ws": - sni := up.VLESS.SNI - if sni == "" { - sni = up.Host + host := up.Header["Host"] + if host == "" && (tlsConfig != nil || up.VLESS.Security == "reality") { + host = sni } - // Use wss:// only when security is explicitly "tls"; empty/"none" → plain ws://. - c, err = transport.DialWS(ctx, "tcp", up.Address(), up.Path, sni, up.VLESS.Security == "tls") + c, err = transport.DialWS(ctx, up.Address(), up.Path, host, tlsConfig) case "grpc": // gRPC requires the security layer to be established BEFORE HTTP/2. // Dial raw TCP, apply Reality/TLS, then put gRPC on top. - c, err = d.dialGRPC(ctx, up, timeout) + c, err = d.dialGRPC(ctx, up, timeout, sni, tlsConfig) - default: + case "", "tcp", "raw": dialer := net.Dialer{Timeout: timeout} c, err = dialer.DialContext(ctx, "tcp", up.Address()) + default: + return nil, fmt.Errorf("vless: unsupported transport") } if err != nil { @@ -66,10 +76,10 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) ( if up.Transport != "grpc" { if up.VLESS.Security == "reality" { if d.Log != nil { - d.Log.Debug("vless starting reality handshake", "sni", up.VLESS.SNI) + d.Log.Debug("vless starting reality handshake", "sni", sni) } // Use a separate var so we keep the original c reference for Close() on error. - tlsConn, realityErr := StreamRealityConn(ctx, c, up.VLESS) + tlsConn, realityErr := streamRealityConn(ctx, c, up.VLESS, sni) if realityErr != nil { c.Close() return nil, fmt.Errorf("vless: reality handshake: %w", realityErr) @@ -78,11 +88,7 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) ( if d.Log != nil { d.Log.Debug("vless reality handshake success") } - } else if up.VLESS.Security == "tls" && up.Transport != "ws" { - tlsConfig := &tls.Config{ - ServerName: up.VLESS.SNI, - InsecureSkipVerify: true, - } + } else if tlsConfig != nil && up.Transport != "ws" { tlsConn := tls.Client(c, tlsConfig) if err = tlsConn.HandshakeContext(ctx); err != nil { c.Close() @@ -102,7 +108,7 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) ( } // dialGRPC handles the gRPC transport: TCP → security → HTTP/2. -func (d *Dialer) dialGRPC(ctx context.Context, up *upstream.Upstream, timeout time.Duration) (net.Conn, error) { +func (d *Dialer) dialGRPC(ctx context.Context, up *upstream.Upstream, timeout time.Duration, sni string, tlsConfig *tls.Config) (net.Conn, error) { rawDialer := net.Dialer{Timeout: timeout} raw, err := rawDialer.DialContext(ctx, "tcp", up.Address()) if err != nil { @@ -113,9 +119,9 @@ func (d *Dialer) dialGRPC(ctx context.Context, up *upstream.Upstream, timeout ti switch up.VLESS.Security { case "reality": if d.Log != nil { - d.Log.Debug("vless grpc starting reality handshake", "sni", up.VLESS.SNI) + d.Log.Debug("vless grpc starting reality handshake", "sni", sni) } - underlying, err = StreamRealityConn(ctx, raw, up.VLESS) + underlying, err = streamRealityConn(ctx, raw, up.VLESS, sni) if err != nil { raw.Close() return nil, fmt.Errorf("reality handshake: %w", err) @@ -124,12 +130,8 @@ func (d *Dialer) dialGRPC(ctx context.Context, up *upstream.Upstream, timeout ti d.Log.Debug("vless grpc reality handshake success") } case "tls": - tlsCfg := &tls.Config{ - ServerName: up.VLESS.SNI, - InsecureSkipVerify: true, - NextProtos: []string{"h2"}, - } - tlsConn := tls.Client(raw, tlsCfg) + tlsConfig.NextProtos = []string{"h2"} + tlsConn := tls.Client(raw, tlsConfig) if err = tlsConn.HandshakeContext(ctx); err != nil { raw.Close() return nil, fmt.Errorf("tls handshake: %w", err) diff --git a/internal/dialer/vless/reality.go b/internal/dialer/vless/reality.go index 7b700b5..de8f91d 100644 --- a/internal/dialer/vless/reality.go +++ b/internal/dialer/vless/reality.go @@ -5,7 +5,12 @@ import ( "crypto/aes" "crypto/cipher" "crypto/ecdh" + "crypto/ed25519" + "crypto/hkdf" + "crypto/hmac" "crypto/sha256" + "crypto/sha512" + "crypto/x509" "encoding/base64" "encoding/binary" "encoding/hex" @@ -15,9 +20,8 @@ import ( "time" utls "github.com/refraction-networking/utls" - "golang.org/x/crypto/hkdf" - "git.qomar.pw/omar/zhguchiy_perchik/internal/upstream" + "git.eeee.moe/omar/zhguchiy_perchik/internal/upstream" ) var fingerprintMap = map[string]*utls.ClientHelloID{ @@ -33,7 +37,7 @@ var fingerprintMap = map[string]*utls.ClientHelloID{ "randomized": &utls.HelloRandomized, } -func StreamRealityConn(ctx context.Context, conn net.Conn, cfg *upstream.VLESSConfig) (net.Conn, error) { +func streamRealityConn(ctx context.Context, conn net.Conn, cfg *upstream.VLESSConfig, serverName string) (net.Conn, error) { if cfg.PublicKey == "" { return nil, errors.New("vless: Reality public key is required") } @@ -65,10 +69,15 @@ func StreamRealityConn(ctx context.Context, conn net.Conn, cfg *upstream.VLESSCo } } + var derivedKey []byte utlsConfig := &utls.Config{ - ServerName: cfg.SNI, - InsecureSkipVerify: true, + ServerName: serverName, + InsecureSkipVerify: true, //nolint:gosec // REALITY authenticates the peer with a keyed certificate proof, not Web PKI. + MinVersion: utls.VersionTLS13, SessionTicketsDisabled: true, + VerifyConnection: func(state utls.ConnectionState) error { + return verifyRealityPeer(state.PeerCertificates, derivedKey) + }, } uConn := utls.UClient(conn, utlsConfig, *fingerprint) @@ -116,8 +125,8 @@ func StreamRealityConn(ctx context.Context, conn net.Conn, cfg *upstream.VLESSCo return nil, fmt.Errorf("ecdh: %w", err) } - derivedKey := make([]byte, 32) - if _, err := hkdf.New(sha256.New, authKey, hello.Random[:20], []byte("REALITY")).Read(derivedKey); err != nil { + derivedKey, err = hkdf.Key(sha256.New, authKey, hello.Random[:20], "REALITY", 32) + if err != nil { return nil, fmt.Errorf("hkdf: %w", err) } @@ -147,6 +156,26 @@ func StreamRealityConn(ctx context.Context, conn net.Conn, cfg *upstream.VLESSCo return uConn, nil } +var errRealityPeerAuthentication = errors.New("vless: REALITY peer authentication failed") + +func verifyRealityPeer(certs []*x509.Certificate, authKey []byte) error { + if len(certs) == 0 || len(authKey) != 32 { + return errRealityPeerAuthentication + } + leaf := certs[0] + publicKey, ok := leaf.PublicKey.(ed25519.PublicKey) + if !ok { + return errRealityPeerAuthentication + } + proof := hmac.New(sha512.New, authKey) + proof.Write(publicKey) + var expected [sha512.Size]byte + if !hmac.Equal(leaf.Signature, proof.Sum(expected[:0])) { + return errRealityPeerAuthentication + } + return nil +} + func decodePublicKey(key string) ([]byte, error) { if decoded, err := base64.RawURLEncoding.DecodeString(key); err == nil && len(decoded) == 32 { return decoded, nil diff --git a/internal/dialer/vless/reality_test.go b/internal/dialer/vless/reality_test.go new file mode 100644 index 0000000..fdaf477 --- /dev/null +++ b/internal/dialer/vless/reality_test.go @@ -0,0 +1,87 @@ +package vless + +import ( + "bytes" + "context" + "crypto/ecdh" + "crypto/ed25519" + "crypto/hmac" + "crypto/rand" + "crypto/sha512" + "crypto/x509" + "encoding/base64" + "errors" + "math/big" + "net" + "net/http" + "net/http/httptest" + "testing" + "time" + + "git.eeee.moe/omar/zhguchiy_perchik/internal/upstream" +) + +func TestVerifyRealityPeerRequiresProof(t *testing.T) { + privateKey := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize)) + publicKey := privateKey.Public().(ed25519.PublicKey) + authKey := bytes.Repeat([]byte{2}, 32) + h := hmac.New(sha512.New, authKey) + h.Write(publicKey) + peer := &x509.Certificate{PublicKey: publicKey, Signature: h.Sum(nil)} + if err := verifyRealityPeer([]*x509.Certificate{peer}, authKey); err != nil { + t.Fatalf("valid REALITY proof rejected: %v", err) + } + if err := verifyRealityPeer([]*x509.Certificate{peer}, bytes.Repeat([]byte{3}, 32)); !errors.Is(err, errRealityPeerAuthentication) { + t.Fatalf("wrong REALITY key: %v", err) + } + if err := verifyRealityPeer(nil, authKey); !errors.Is(err, errRealityPeerAuthentication) { + t.Fatalf("missing peer certificate: %v", err) + } + + now := time.Unix(1_700_000_000, 0) + normal := &x509.Certificate{ + SerialNumber: big.NewInt(1), + NotBefore: now.Add(-time.Hour), + NotAfter: now.Add(time.Hour), + DNSNames: []string{"cover.example"}, + } + der, err := x509.CreateCertificate(rand.Reader, normal, normal, publicKey, privateKey) + if err != nil { + t.Fatal(err) + } + cert, err := x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + roots := x509.NewCertPool() + roots.AddCert(cert) + if _, err := cert.Verify(x509.VerifyOptions{Roots: roots, DNSName: "cover.example", CurrentTime: now}); err != nil { + t.Fatalf("expected ordinary certificate to pass Web PKI verification: %v", err) + } + if err := verifyRealityPeer([]*x509.Certificate{cert}, authKey); !errors.Is(err, errRealityPeerAuthentication) { + t.Fatalf("trusted ordinary TLS certificate accepted as REALITY: %v", err) + } +} + +func TestStreamRealityConnRejectsOrdinaryTLSPeer(t *testing.T) { + server := httptest.NewTLSServer(http.NotFoundHandler()) + t.Cleanup(server.Close) + key, err := ecdh.X25519().NewPrivateKey(bytes.Repeat([]byte{4}, 32)) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + dialer := net.Dialer{} + raw, err := dialer.DialContext(ctx, "tcp", server.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer raw.Close() + conn, err := streamRealityConn(ctx, raw, &upstream.VLESSConfig{ + PublicKey: base64.RawURLEncoding.EncodeToString(key.PublicKey().Bytes()), + }, "example.com") + if conn != nil || !errors.Is(err, errRealityPeerAuthentication) { + t.Fatalf("ordinary TLS must fail at REALITY peer authentication, got %v", err) + } +} diff --git a/internal/dialer/vmess/dialer.go b/internal/dialer/vmess/dialer.go index b8e3aea..d6fcbae 100644 --- a/internal/dialer/vmess/dialer.go +++ b/internal/dialer/vmess/dialer.go @@ -9,8 +9,8 @@ import ( "runtime" "time" - "git.qomar.pw/omar/zhguchiy_perchik/internal/dialer/transport" - "git.qomar.pw/omar/zhguchiy_perchik/internal/upstream" + "git.eeee.moe/omar/zhguchiy_perchik/internal/dialer/transport" + "git.eeee.moe/omar/zhguchiy_perchik/internal/upstream" "github.com/gofrs/uuid" ) @@ -34,34 +34,31 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) ( timeout = 10 * time.Second } - var c net.Conn - var err error - - switch up.Transport { - case "ws": + var tlsConfig *tls.Config + if up.VMess.TLS { sni := up.VMess.ServerName if sni == "" { sni = up.Host } - c, err = transport.DialWS(ctx, "tcp", up.Address(), up.Path, sni, up.VMess.TLS) - case "grpc": - tlsConfig := &tls.Config{ - ServerName: up.VMess.ServerName, - InsecureSkipVerify: true, + tlsConfig = &tls.Config{ServerName: sni, MinVersion: tls.VersionTLS12} + } + + var c net.Conn + var err error + + switch { + case up.Transport == "ws": + host := up.Header["Host"] + if host == "" && tlsConfig != nil { + host = tlsConfig.ServerName } + c, err = transport.DialWS(ctx, up.Address(), up.Path, host, tlsConfig) + case up.Transport == "grpc" && tlsConfig != nil: c, err = transport.DialGRPC(ctx, up.Address(), up.ServiceName, tlsConfig) - default: + case up.Transport == "" || up.Transport == "tcp" || up.Transport == "raw" || up.Transport == "grpc": dialer := net.Dialer{Timeout: timeout} c, err = dialer.DialContext(ctx, "tcp", up.Address()) - if err == nil && up.VMess.TLS { - sni := up.VMess.ServerName - if sni == "" { - sni = up.Host - } - tlsConfig := &tls.Config{ - ServerName: sni, - InsecureSkipVerify: true, - } + if err == nil && tlsConfig != nil { tlsConn := tls.Client(c, tlsConfig) if err = tlsConn.HandshakeContext(ctx); err != nil { c.Close() @@ -69,6 +66,16 @@ func (d *Dialer) Dial(ctx context.Context, up *upstream.Upstream, dest string) ( } c = tlsConn } + if err == nil && up.Transport == "grpc" { + grpcConn, grpcErr := transport.DialGRPCOverConn(ctx, c, up.Address(), up.ServiceName) + if grpcErr != nil { + c.Close() + return nil, fmt.Errorf("vmess: connect: %w", grpcErr) + } + c = grpcConn + } + default: + return nil, fmt.Errorf("vmess: unsupported transport") } if err != nil { diff --git a/internal/fetcher/fetcher.go b/internal/fetcher/fetcher.go index 173a51d..d482900 100644 --- a/internal/fetcher/fetcher.go +++ b/internal/fetcher/fetcher.go @@ -4,6 +4,8 @@ import ( "bufio" "context" "encoding/base64" + "errors" + "fmt" "io" "log/slog" "net/http" @@ -11,11 +13,6 @@ import ( "time" ) -type Source struct { - URL string - Name string -} - // Source kinds control how a fetched body is decoded into proxy lines. const ( KindAuto = "auto" // try base64 first, fall back to plain lines @@ -23,110 +20,42 @@ const ( KindBase64 = "base64" // decode base64 (subscription), then split lines ) +const maxSourceBytes = 20 << 20 + +var errSourceTooLarge = errors.New("source body exceeds size limit") + // FetchSource downloads one source and decodes it according to kind. An empty -// kind is treated as "auto". Retries transient failures with backoff. +// kind is treated as "auto". Errors and retry logs omit the URL and body. func FetchSource(ctx context.Context, rawURL, kind string, log *slog.Logger) ([]string, error) { client := &http.Client{Timeout: 30 * time.Second} content, err := fetchRawWithRetry(ctx, client, rawURL, log) if err != nil { return nil, err } - return decodeByKind(content, kind), nil + return decodeByKind(content, kind) } -func decodeByKind(content, kind string) []string { +func decodeByKind(content, kind string) ([]string, error) { switch kind { case KindPlain: - return parseLines(content) case KindBase64: - if dec, err := tryBase64(content); err == nil { - content = dec - } - return parseLines(content) - default: // auto - if dec, err := tryBase64(content); err == nil { - content = dec - } - return parseLines(content) - } -} - -// FetchAll downloads all sources, retrying failed ones with exponential backoff. -// A failure of one source does not abort the others — it is logged and skipped. -func FetchAll(ctx context.Context, sources []Source, log *slog.Logger) ([]string, error) { - client := &http.Client{Timeout: 30 * time.Second} - seen := make(map[string]struct{}) - var result []string - - for _, src := range sources { - lines, err := fetchOneWithRetry(ctx, client, src.URL, log) + decoded, err := tryBase64(content) if err != nil { - if log != nil { - log.Warn("fetch source failed after retries", "url", src.URL, "err", err.Error()) - } - continue + return nil, errors.New("invalid base64 source body") } - for _, line := range lines { - if _, ok := seen[line]; !ok { - seen[line] = struct{}{} - result = append(result, line) - } - } - } - return result, nil -} - -// fetchOneWithRetry attempts to fetch a single source up to 3 times with backoff. -// Backoff: attempt 1 immediate, attempt 2 after 1s, attempt 3 after 2s. -func fetchOneWithRetry(ctx context.Context, client *http.Client, rawURL string, log *slog.Logger) ([]string, error) { - delays := []time.Duration{0, time.Second, 2 * time.Second} - var lastErr error - for attempt, delay := range delays { - if delay > 0 { - select { - case <-ctx.Done(): - return nil, ctx.Err() - case <-time.After(delay): - } - } - lines, err := fetchOne(ctx, client, rawURL) - if err == nil { - return lines, nil - } - if log != nil { - log.Debug("fetch attempt failed", "url", rawURL, "attempt", attempt+1, "err", err.Error()) - } - lastErr = err - } - return nil, lastErr -} - -func fetchOne(ctx context.Context, client *http.Client, rawURL string) ([]string, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) - if err != nil { - return nil, err - } - resp, err := client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20)) - if err != nil { - return nil, err - } - - content := string(body) - if decoded, err := tryBase64(content); err == nil { content = decoded + case "", KindAuto: + if decoded, err := tryBase64(content); err == nil { + content = decoded + } + default: + return nil, errors.New("invalid source kind") } - return parseLines(content), nil + return parseLines(content) } -// fetchRawWithRetry downloads a source body (undecoded) with backoff. func fetchRawWithRetry(ctx context.Context, client *http.Client, rawURL string, log *slog.Logger) (string, error) { - delays := []time.Duration{0, time.Second, 2 * time.Second} + delays := [...]time.Duration{0, time.Second, 2 * time.Second} var lastErr error for attempt, delay := range delays { if delay > 0 { @@ -136,45 +65,67 @@ func fetchRawWithRetry(ctx context.Context, client *http.Client, rawURL string, case <-time.After(delay): } } - content, err := fetchRaw(ctx, client, rawURL) + content, retry, err := fetchRaw(ctx, client, rawURL) if err == nil { return content, nil } + if !retry { + return "", err + } if log != nil { - log.Debug("fetch attempt failed", "url", rawURL, "attempt", attempt+1, "err", err.Error()) + log.Debug("source fetch attempt failed", "attempt", attempt+1, "reason", err.Error()) } lastErr = err } return "", lastErr } -func fetchRaw(ctx context.Context, client *http.Client, rawURL string) (string, error) { +func fetchRaw(ctx context.Context, client *http.Client, rawURL string) (string, bool, error) { + if err := ctx.Err(); err != nil { + return "", false, err + } req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) - if err != nil { - return "", err + if err != nil || (req.URL.Scheme != "http" && req.URL.Scheme != "https") || req.URL.Host == "" { + return "", false, errors.New("invalid source URL") } resp, err := client.Do(req) if err != nil { - return "", err + if ctx.Err() != nil { + return "", false, ctx.Err() + } + return "", true, errors.New("source request failed") } defer resp.Body.Close() - body, err := io.ReadAll(io.LimitReader(resp.Body, 20<<20)) - if err != nil { - return "", err + if resp.StatusCode < 200 || resp.StatusCode >= 300 || resp.StatusCode == http.StatusPartialContent { + retry := resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 + return "", retry, fmt.Errorf("source returned HTTP status %d", resp.StatusCode) } - return string(body), nil + if resp.ContentLength > maxSourceBytes { + return "", false, errSourceTooLarge + } + body, err := io.ReadAll(io.LimitReader(resp.Body, maxSourceBytes+1)) + if err != nil { + if ctx.Err() != nil { + return "", false, ctx.Err() + } + return "", true, errors.New("source body read failed") + } + if len(body) > maxSourceBytes { + return "", false, errSourceTooLarge + } + return string(body), false, nil } func tryBase64(s string) (string, error) { s = strings.TrimSpace(s) - if strings.Contains(s, "://") && strings.Contains(s, "\n") { + if strings.Contains(s, "://") { return "", io.ErrUnexpectedEOF } - for _, enc := range []encoding{ - {base64.StdEncoding}, - {base64.RawStdEncoding}, - {base64.URLEncoding}, - {base64.RawURLEncoding}, + for _, enc := range [...]*base64.Encoding{ + base64.StdEncoding, + base64.RawStdEncoding, + base64.URLEncoding, + base64.RawURLEncoding, } { if b, err := enc.DecodeString(s); err == nil { return string(b), nil @@ -183,19 +134,7 @@ func tryBase64(s string) (string, error) { return "", io.ErrUnexpectedEOF } -type encoding struct{ *base64.Encoding } - -// ParseContent extracts proxy URLs from arbitrary text. Tries base64 decoding -// (subscription format) and falls back to line-by-line parsing. Used by the -// admin upload endpoint to import a list pasted by a user. -func ParseContent(content string) []string { - if decoded, err := tryBase64(content); err == nil { - content = decoded - } - return parseLines(content) -} - -func parseLines(content string) []string { +func parseLines(content string) ([]string, error) { var lines []string scanner := bufio.NewScanner(strings.NewReader(content)) for scanner.Scan() { @@ -207,5 +146,8 @@ func parseLines(content string) []string { lines = append(lines, line) } } - return lines + if scanner.Err() != nil { + return nil, errors.New("source contains an excessively long line") + } + return lines, nil } diff --git a/internal/fetcher/fetcher_test.go b/internal/fetcher/fetcher_test.go new file mode 100644 index 0000000..30da053 --- /dev/null +++ b/internal/fetcher/fetcher_test.go @@ -0,0 +1,115 @@ +package fetcher + +import ( + "bytes" + "context" + "encoding/base64" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" +) + +func TestFetchSourceDistinguishesEmptyFromFailure(t *testing.T) { + const proxy = "http://user:proxy-test-token@proxy.invalid:8080" + tests := []struct { + name string + kind string + status int + body string + want []string + err string + }{ + {name: "empty", status: http.StatusNoContent}, + {name: "comments only", kind: KindPlain, status: http.StatusOK, body: "# comment\n"}, + {name: "plain", kind: KindPlain, status: http.StatusOK, body: proxy, want: []string{proxy}}, + {name: "base64", kind: KindBase64, status: http.StatusOK, body: base64.StdEncoding.EncodeToString([]byte(proxy)), want: []string{proxy}}, + {name: "invalid explicit base64", kind: KindBase64, status: http.StatusOK, body: proxy, err: "invalid base64 source body"}, + {name: "invalid kind", kind: "invalid", status: http.StatusOK, body: proxy, err: "invalid source kind"}, + {name: "failed status with valid body", status: http.StatusForbidden, body: proxy, err: "source returned HTTP status 403"}, + {name: "partial response", status: http.StatusPartialContent, body: proxy, err: "source returned HTTP status 206"}, + {name: "scanner failure after valid line", kind: KindPlain, status: http.StatusOK, body: proxy + "\n" + strings.Repeat("x", 64<<10), err: "source contains an excessively long line"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(tc.status) + if tc.body != "" { + _, _ = io.WriteString(w, tc.body) + } + })) + defer srv.Close() + lines, err := FetchSource(t.Context(), srv.URL, tc.kind, nil) + if tc.err != "" { + if err == nil || err.Error() != tc.err || lines != nil { + t.Fatalf("FetchSource = %d lines, %v; want no lines and %q", len(lines), err, tc.err) + } + } else if err != nil || !slices.Equal(lines, tc.want) { + t.Fatalf("FetchSource = %d lines, %v; want %d lines and no error", len(lines), err, len(tc.want)) + } + }) + } +} + +func TestFetchRawRejectsOversizeWithoutContentLength(t *testing.T) { + client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + ContentLength: -1, + Body: io.NopCloser(io.LimitReader(zeroReader{}, maxSourceBytes+1)), + }, nil + })} + body, retry, err := fetchRaw(t.Context(), client, "https://source.invalid/list") + if body != "" || retry || !errors.Is(err, errSourceTooLarge) { + t.Fatalf("fetchRaw = %d bytes, retry %v, %v; want oversize failure", len(body), retry, err) + } +} + +func TestFetchRetryLogsExcludeCredentials(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + const rawURL = "https://user:source-password@source.invalid/list?token=source-token" + client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + return nil, fmt.Errorf("transport failed for %s", rawURL) + })} + var logs bytes.Buffer + log := slog.New(slog.NewTextHandler(cancelWriter{&logs, cancel}, &slog.HandlerOptions{Level: slog.LevelDebug})) + _, err := fetchRawWithRetry(ctx, client, rawURL, log) + if !errors.Is(err, context.Canceled) { + t.Fatalf("fetchRawWithRetry error = %v; want context cancellation after first retry log", err) + } + if !strings.Contains(logs.String(), "source request failed") { + t.Fatal("missing safe fetch failure reason") + } + for _, secret := range []string{"source-password", "source-token", "source.invalid"} { + if strings.Contains(logs.String(), secret) || strings.Contains(err.Error(), secret) { + t.Fatal("fetch retry leaked source URL data") + } + } +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +type zeroReader struct{} + +func (zeroReader) Read(p []byte) (int, error) { + clear(p) + return len(p), nil +} + +type cancelWriter struct { + *bytes.Buffer + cancel context.CancelFunc +} + +func (w cancelWriter) Write(p []byte) (int, error) { + defer w.cancel() + return w.Buffer.Write(p) +} diff --git a/internal/notify/telegram.go b/internal/notify/telegram.go index 48e1d8a..fe529b3 100644 --- a/internal/notify/telegram.go +++ b/internal/notify/telegram.go @@ -3,6 +3,7 @@ package notify import ( "context" + "errors" "fmt" "net/http" "net/url" @@ -35,13 +36,21 @@ func (t *Telegram) Send(ctx context.Context, token, chatID, text string) error { req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode())) if err != nil { - return err + return errors.New("telegram: cannot build sendMessage request") } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") resp, err := t.client.Do(req) if err != nil { - return err + // Client errors can contain the bot token in the URL or wrapped cause. + switch { + case errors.Is(err, context.Canceled): + return fmt.Errorf("telegram: sendMessage request failed: %w", context.Canceled) + case errors.Is(err, context.DeadlineExceeded): + return fmt.Errorf("telegram: sendMessage request failed: %w", context.DeadlineExceeded) + default: + return errors.New("telegram: sendMessage request failed") + } } defer resp.Body.Close() if resp.StatusCode/100 != 2 { diff --git a/internal/notify/telegram_test.go b/internal/notify/telegram_test.go new file mode 100644 index 0000000..0ebb659 --- /dev/null +++ b/internal/notify/telegram_test.go @@ -0,0 +1,55 @@ +package notify + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "testing" +) + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +func TestTelegramSendSanitizesErrors(t *testing.T) { + const token = "example-bot-token" + const transportDetail = "example-transport-detail" + + for _, tt := range []struct { + name, token, message string + cause error + called bool + }{ + {"request", token + "%", "telegram: cannot build sendMessage request", nil, false}, + {"transport", token, "telegram: sendMessage request failed", nil, true}, + {"canceled", token, "telegram: sendMessage request failed: context canceled", context.Canceled, true}, + {"timeout", token, "telegram: sendMessage request failed: context deadline exceeded", context.DeadlineExceeded, true}, + } { + t.Run(tt.name, func(t *testing.T) { + var called bool + telegram := New() + telegram.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + called = true + if tt.cause != nil { + return nil, fmt.Errorf("%s: %s: %w", transportDetail, req.URL, tt.cause) + } + return nil, fmt.Errorf("%s: %s", transportDetail, req.URL) + }) + + err := telegram.Send(context.Background(), tt.token, "chat", "message") + if called != tt.called || err == nil { + t.Fatalf("transport called = %v, want %v; error = %v, want failure", called, tt.called, err) + } + if strings.Contains(err.Error(), token) || strings.Contains(err.Error(), transportDetail) { + t.Fatal("error includes sensitive request or transport detail") + } + if err.Error() != tt.message || (tt.cause != nil && !errors.Is(err, tt.cause)) { + t.Errorf("error = %v, want %q with cause %v", err, tt.message, tt.cause) + } + }) + } +} diff --git a/internal/subs/node.go b/internal/subs/node.go index 53ffb05..036f840 100644 --- a/internal/subs/node.go +++ b/internal/subs/node.go @@ -33,7 +33,6 @@ type node struct { PublicKey string // reality pbk ShortID string // reality sid Flow string - Insecure bool Network string // tcp | ws | grpc Path string @@ -43,18 +42,40 @@ type node struct { // parseNode decodes a canonical proxy URL into a node. name is the display label. func parseNode(canonical, name string) (*node, bool) { + var n *node + var ok bool switch { case strings.HasPrefix(canonical, "vless://"): - return parseVLESSNode(canonical, name) + n, ok = parseVLESSNode(canonical, name) case strings.HasPrefix(canonical, "trojan://"): - return parseTrojanNode(canonical, name) + n, ok = parseTrojanNode(canonical, name) case strings.HasPrefix(canonical, "ss://"): - return parseSSNode(canonical, name) + n, ok = parseSSNode(canonical, name) case strings.HasPrefix(canonical, "vmess://"): - return parseVMessNode(canonical, name) + n, ok = parseVMessNode(canonical, name) default: return nil, false } + if !ok { + return nil, false + } + switch n.Network { + case "tcp", "ws", "grpc": + default: + return nil, false + } + if n.TLS { + if n.SNI == "" { + n.SNI = n.Server + } + if n.Network == "ws" && n.Host == "" { + n.Host = n.SNI + } + } + if n.Reality && n.Fingerprint == "" { + n.Fingerprint = "chrome" + } + return n, true } func splitALPN(s string) []string { @@ -93,7 +114,6 @@ func parseVLESSNode(canonical, name string) (*node, bool) { PublicKey: q.Get("pbk"), ShortID: q.Get("sid"), Flow: q.Get("flow"), - Insecure: q.Get("allowInsecure") == "1" || q.Get("insecure") == "1", Network: normNet(q.Get("type")), Path: q.Get("path"), Host: q.Get("host"), @@ -120,7 +140,6 @@ func parseTrojanNode(canonical, name string) (*node, bool) { SNI: q.Get("sni"), ALPN: splitALPN(q.Get("alpn")), Fingerprint: q.Get("fp"), - Insecure: q.Get("allowInsecure") == "1", Network: normNet(q.Get("type")), Path: q.Get("path"), Host: q.Get("host"), @@ -175,7 +194,7 @@ func parseVMessNode(canonical, name string) (*node, bool) { AlterID: aid, Cipher: cipher, TLS: str(v["tls"]) == "tls", - SNI: firstNonEmpty(str(v["sni"]), str(v["host"])), + SNI: str(v["sni"]), ALPN: splitALPN(str(v["alpn"])), Network: normNet(str(v["net"])), Path: str(v["path"]), @@ -210,15 +229,6 @@ func str(v any) string { } } -func firstNonEmpty(vals ...string) string { - for _, v := range vals { - if v != "" { - return v - } - } - return "" -} - func decodeAnyBase64(s string) ([]byte, error) { s = strings.TrimSpace(s) for _, enc := range []*base64.Encoding{ diff --git a/internal/subs/pipeline.go b/internal/subs/pipeline.go index fd5be59..e5cf199 100644 --- a/internal/subs/pipeline.go +++ b/internal/subs/pipeline.go @@ -5,7 +5,7 @@ import ( "sort" "strings" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" ) // Uniqueness scopes. ScopeIP collapses proxies sharing one exit IP; ScopeSubnet diff --git a/internal/subs/render.go b/internal/subs/render.go index 1eccabb..221d968 100644 --- a/internal/subs/render.go +++ b/internal/subs/render.go @@ -7,7 +7,7 @@ import ( "net/url" "strings" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" "gopkg.in/yaml.v3" ) @@ -134,15 +134,16 @@ func clashProxy(n *node) map[string]any { applyClashTLS(m, n) applyClashTransport(m, n) case "trojan": + if !n.TLS { + // Clash's Trojan outbound always uses TLS. + return nil + } m["type"] = "trojan" m["password"] = n.Password m["udp"] = true if n.SNI != "" { m["sni"] = n.SNI } - if n.Insecure { - m["skip-cert-verify"] = true - } if len(n.ALPN) > 0 { m["alpn"] = n.ALPN } @@ -172,9 +173,6 @@ func applyClashTLS(m map[string]any, n *node) { if len(n.ALPN) > 0 { m["alpn"] = n.ALPN } - if n.Insecure { - m["skip-cert-verify"] = true - } if n.Reality { ro := map[string]any{"public-key": n.PublicKey} if n.ShortID != "" { @@ -277,7 +275,7 @@ func applySingboxTLS(ob map[string]any, n *node) { if !n.TLS { return } - tls := map[string]any{"enabled": true, "insecure": n.Insecure} + tls := map[string]any{"enabled": true} if n.SNI != "" { tls["server_name"] = n.SNI } diff --git a/internal/subs/subs_test.go b/internal/subs/subs_test.go index 83c1571..68392ea 100644 --- a/internal/subs/subs_test.go +++ b/internal/subs/subs_test.go @@ -5,7 +5,8 @@ import ( "strings" "testing" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/upstream" ) func TestCollapseScopeIP(t *testing.T) { @@ -222,3 +223,63 @@ func TestBuildLimitAfterCollapse(t *testing.T) { t.Errorf("want 2 collapsed lines, got %d newlines", n) } } + +func TestStructuredExportTLSIdentity(t *testing.T) { + const serverName = "proxy.example" + const wsHost = "route.example" + inputs := []struct { + name, link, wantSNI, wantHost string + }{ + {"distinct SNI and Host", "vless://id@" + serverName + ":443?security=tls&type=ws&sni=tls.example&host=" + wsHost + "&allowInsecure=1", "tls.example", wsHost}, + {"default Host", "trojan://pass@" + serverName + ":443?type=ws&sni=tls.example", "tls.example", "tls.example"}, + {"default SNI", "vmess://" + base64.StdEncoding.EncodeToString([]byte(`{"add":"proxy.example","port":"443","id":"u","net":"ws","tls":"tls","host":"route.example"}`)), serverName, wsHost}, + } + for _, tc := range inputs { + t.Run(tc.name, func(t *testing.T) { + canonical, _, err := upstream.Canonicalize(tc.link) + if err != nil { + t.Fatal(err) + } + n, ok := parseNode(canonical, tc.name) + if !ok { + t.Fatal("structured export rejected a canonical link") + } + clash := clashProxy(n) + clashSNI := clash["servername"] + if n.Protocol == "trojan" { + clashSNI = clash["sni"] + } + clashWS, _ := clash["ws-opts"].(map[string]any) + clashHeaders, _ := clashWS["headers"].(map[string]any) + clashHost := clashHeaders["Host"] + if clashSNI != tc.wantSNI || clashHost != tc.wantHost || clash["skip-cert-verify"] == true { + t.Errorf("Clash: got SNI=%v Host=%v skip-cert-verify=%v", clashSNI, clashHost, clash["skip-cert-verify"]) + } + singbox := singboxOutbound(n) + tls, _ := singbox["tls"].(map[string]any) + transport, _ := singbox["transport"].(map[string]any) + singboxHeaders, _ := transport["headers"].(map[string]any) + singboxHost := singboxHeaders["Host"] + if tls["server_name"] != tc.wantSNI || singboxHost != tc.wantHost || tls["insecure"] == true { + t.Errorf("sing-box: got SNI=%v Host=%v insecure=%v", tls["server_name"], singboxHost, tls["insecure"]) + } + }) + } +} + +func TestStructuredExportPreservesTrojanPlaintext(t *testing.T) { + canonical, _, err := upstream.Canonicalize("trojan://pass@proxy.example:443?security=none") + if err != nil { + t.Fatal(err) + } + n, ok := parseNode(canonical, "plaintext Trojan") + if !ok { + t.Fatal("canonical link not parsed") + } + if clashProxy(n) != nil { + t.Error("Clash must not advertise plaintext Trojan as TLS") + } + if ob := singboxOutbound(n); ob["type"] != "trojan" || ob["tls"] != nil { + t.Error("sing-box must preserve plaintext Trojan") + } +} diff --git a/internal/upstream/canonical.go b/internal/upstream/canonical.go index 0b48302..dee8f62 100644 --- a/internal/upstream/canonical.go +++ b/internal/upstream/canonical.go @@ -27,7 +27,7 @@ var wsFamily = map[string]bool{ // "different" proxies. This is safe because the resulting canonical URL is what // we actually re-check — anything stripped that mattered would simply fail the // check. Dropped: fp, packetEncoding, allowInsecure/insecure, spx, encryption, -// ed/eh/pcs/…; normalized: security=none→∅, type=tcp/raw→∅, headerType=none→∅; +// ed/eh/pcs/…; normalized: VLESS security=none→∅, type=tcp/raw→∅, headerType=none→∅; // scoped: path/host only for ws-family, serviceName/mode only for grpc/xhttp, // sni/alpn/pbk/sid only under tls/reality. func canonicalQuery(q url.Values, scheme string) url.Values { @@ -39,7 +39,7 @@ func canonicalQuery(q url.Values, scheme string) url.Values { if scheme == "trojan" && security == "" { security = "tls" } - if security == "none" { + if scheme != "trojan" && security == "none" { security = "" } typ := strings.ToLower(get("type")) @@ -332,7 +332,9 @@ func canonVMess(cleaned string) (string, error) { kept["net"] = net tls := strings.ToLower(field("tls")) - if tls == "tls" || tls == "reality" { + switch tls { + case "", "none": + case "tls": kept["tls"] = tls if sni := field("sni"); sni != "" { kept["sni"] = strings.ToLower(sni) @@ -340,6 +342,8 @@ func canonVMess(cleaned string) (string, error) { if alpn := field("alpn"); alpn != "" { kept["alpn"] = sortCSV(alpn) } + default: + return "", errors.New("vmess: unsupported transport security") } if scy := strings.ToLower(field("scy")); scy != "" && scy != "auto" { kept["scy"] = scy diff --git a/internal/upstream/parser.go b/internal/upstream/parser.go index b8d4848..2036bd0 100644 --- a/internal/upstream/parser.go +++ b/internal/upstream/parser.go @@ -123,9 +123,15 @@ func parseVLESS(u *url.URL, raw string) (*Upstream, error) { } q := u.Query() + security := strings.ToLower(strings.TrimSpace(q.Get("security"))) + switch security { + case "", "none", "tls", "reality": + default: + return nil, fmt.Errorf("vless: unsupported transport security") + } v := &VLESSConfig{ UUID: u.User.Username(), - Security: q.Get("security"), + Security: security, Encryption: q.Get("encryption"), Flow: q.Get("flow"), SNI: q.Get("sni"), @@ -135,6 +141,11 @@ func parseVLESS(u *url.URL, raw string) (*Upstream, error) { SpiderX: q.Get("spx"), } + transport, err := parseTransport(q.Get("type")) + if err != nil { + return nil, fmt.Errorf("vless: %w", err) + } + up := &Upstream{ Scheme: SchemeVLESS, Host: host, @@ -142,12 +153,12 @@ func parseVLESS(u *url.URL, raw string) (*Upstream, error) { Tag: u.Fragment, Raw: raw, VLESS: v, - Transport: q.Get("type"), + Transport: transport, Path: q.Get("path"), ServiceName: q.Get("serviceName"), } - if up.Transport == "" || up.Transport == "tcp" || up.Transport == "raw" { - up.Transport = "tcp" + if headerHost := q.Get("host"); up.Transport == "ws" && headerHost != "" { + up.Header = map[string]string{"Host": headerHost} } return up, nil } @@ -160,12 +171,25 @@ func parseTrojan(u *url.URL, raw string) (*Upstream, error) { } q := u.Query() + security := strings.ToLower(strings.TrimSpace(q.Get("security"))) + switch security { + case "": + security = "tls" + case "none", "tls": + default: + return nil, fmt.Errorf("trojan: unsupported transport security") + } t := &TrojanConfig{ Password: u.User.Username(), - Security: q.Get("security"), + Security: security, SNI: q.Get("sni"), } + transport, err := parseTransport(q.Get("type")) + if err != nil { + return nil, fmt.Errorf("trojan: %w", err) + } + up := &Upstream{ Scheme: SchemeTrojan, Host: host, @@ -173,16 +197,28 @@ func parseTrojan(u *url.URL, raw string) (*Upstream, error) { Tag: u.Fragment, Raw: raw, Trojan: t, - Transport: q.Get("type"), + Transport: transport, Path: q.Get("path"), ServiceName: q.Get("serviceName"), } - if up.Transport == "" || up.Transport == "tcp" || up.Transport == "raw" { - up.Transport = "tcp" + if headerHost := q.Get("host"); up.Transport == "ws" && headerHost != "" { + up.Header = map[string]string{"Host": headerHost} } return up, nil } +func parseTransport(transport string) (string, error) { + transport = strings.ToLower(strings.TrimSpace(transport)) + switch transport { + case "", "tcp", "raw": + return "tcp", nil + case "ws", "grpc": + return transport, nil + default: + return "", fmt.Errorf("unsupported transport") + } +} + func splitHostPort(s string) (string, int, error) { s = strings.TrimRight(s, "/") h, p, err := net.SplitHostPort(s) @@ -274,20 +310,23 @@ func parseVMess(raw string) (*Upstream, error) { security = "auto" } - transport := v.Net - if transport == "" { - transport = "tcp" + transport, err := parseTransport(v.Net) + if err != nil { + return nil, fmt.Errorf("vmess: %w", err) } - sni := v.SNI - if sni == "" { - sni = v.Host + tlsMode := strings.ToLower(strings.TrimSpace(v.TLS)) + switch tlsMode { + case "", "none", "tls": + default: + return nil, fmt.Errorf("vmess: unsupported transport security") } + sni := v.SNI if sni == "" { sni = v.Add } - return &Upstream{ + up := &Upstream{ Scheme: SchemeVMess, Host: v.Add, Port: port, @@ -297,12 +336,15 @@ func parseVMess(raw string) (*Upstream, error) { Path: v.Path, ServiceName: "", VMess: &VMessConfig{ - UUID: v.ID, - AlterID: alterID, - Security: security, - TLS: v.TLS == "tls", - ServerName: sni, - SkipCertVerify: true, + UUID: v.ID, + AlterID: alterID, + Security: security, + TLS: tlsMode == "tls", + ServerName: sni, }, - }, nil + } + if transport == "ws" && v.Host != "" { + up.Header = map[string]string{"Host": v.Host} + } + return up, nil } diff --git a/internal/upstream/parser_test.go b/internal/upstream/parser_test.go new file mode 100644 index 0000000..59df8d4 --- /dev/null +++ b/internal/upstream/parser_test.go @@ -0,0 +1,87 @@ +package upstream + +import ( + "encoding/base64" + "strings" + "testing" +) + +func TestCanonicalizeKeepsWebSocketHostIndependentOfSNI(t *testing.T) { + tests := []struct { + name, input, wantSNI string + }{ + {"vless", "vless://u@proxy.example:443?security=tls&type=ws&sni=tls.example&host=ws.example&allowInsecure=1", "tls.example"}, + {"trojan", "trojan://p@proxy.example:443?type=ws&sni=tls.example&host=ws.example&allowInsecure=1", "tls.example"}, + {"vmess", "vmess://" + b64(`{"add":"proxy.example","port":"443","id":"u","net":"ws","tls":"tls","sni":"tls.example","host":"ws.example","allowInsecure":true}`), "tls.example"}, + {"vmess implicit SNI", "vmess://" + b64(`{"add":"proxy.example","port":"443","id":"u","net":"ws","tls":"tls","host":"ws.example"}`), "proxy.example"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + canonical, up, err := Canonicalize(tc.input) + if err != nil { + t.Fatal(err) + } + if got := up.Header["Host"]; got != "ws.example" { + t.Fatalf("WS Host = %q, want ws.example", got) + } + var sni string + switch up.Scheme { + case SchemeVLESS: + sni = up.VLESS.SNI + case SchemeTrojan: + sni = up.Trojan.SNI + case SchemeVMess: + sni = up.VMess.ServerName + decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(canonical, "vmess://")) + if err != nil { + t.Fatal(err) + } + canonical = string(decoded) + } + if sni != tc.wantSNI { + t.Errorf("TLS server name = %q, want %q", sni, tc.wantSNI) + } + if strings.Contains(strings.ToLower(canonical), "insecure") { + t.Errorf("insecure hint remained in canonical output") + } + }) + } +} + +func TestCanonicalizeTrojanPreservesPlaintextOptOut(t *testing.T) { + implicit, defaultUp, err := Canonicalize("trojan://p@proxy.example:443?type=ws") + if err != nil { + t.Fatal(err) + } + explicit, plainUp, err := Canonicalize("trojan://p@proxy.example:443?security=none&type=ws") + if err != nil { + t.Fatal(err) + } + if implicit == explicit || defaultUp.Trojan.Security != "tls" || plainUp.Trojan.Security != "none" { + t.Fatal("canonical Trojan must distinguish implicit TLS from explicit security=none") + } +} + +func TestCanonicalizeRejectsUnsupportedTransportSecurity(t *testing.T) { + for _, input := range []string{ + "vless://u@proxy.example:443?security=xtls", + "trojan://p@proxy.example:443?security=reality", + "vmess://" + b64(`{"add":"proxy.example","port":"443","id":"u","tls":"reality"}`), + } { + if _, _, err := Canonicalize(input); err == nil { + t.Fatal("unsupported transport security must not become plaintext or regular TLS") + } + } +} + +func TestCanonicalizeRejectsUnsupportedTransport(t *testing.T) { + for _, input := range []string{ + "vless://u@proxy.example:443?type=xhttp", + "trojan://p@proxy.example:443?type=httpupgrade", + "vmess://" + b64(`{"add":"proxy.example","port":"443","id":"u","net":"http"}`), + } { + if _, _, err := Canonicalize(input); err == nil || !strings.Contains(err.Error(), "unsupported transport") { + t.Fatalf("expected unsupported transport error, got %v", err) + } + } +} diff --git a/internal/upstream/upstream.go b/internal/upstream/upstream.go index 983c030..c745f3f 100644 --- a/internal/upstream/upstream.go +++ b/internal/upstream/upstream.go @@ -27,8 +27,8 @@ type Upstream struct { Trojan *TrojanConfig VMess *VMessConfig - // Transport-specific (common for VLESS/Trojan) - Transport string // tcp, ws, grpc, xhttp + // Transport-specific (common for VLESS/Trojan/VMess) + Transport string // tcp, ws, grpc Path string Header map[string]string ServiceName string @@ -62,10 +62,9 @@ type TrojanConfig struct { } type VMessConfig struct { - UUID string - AlterID int - Security string // auto, aes-128-gcm, chacha20-poly1305, none - TLS bool - ServerName string - SkipCertVerify bool + UUID string + AlterID int + Security string // auto, aes-128-gcm, chacha20-poly1305, none + TLS bool + ServerName string } diff --git a/internal/worker/worker.go b/internal/worker/worker.go index 7349e02..75544d7 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -5,21 +5,21 @@ package worker import ( "context" + "errors" "fmt" "log/slog" "strconv" "strings" "sync" - "sync/atomic" "time" - "git.qomar.pw/omar/zhguchiy_perchik/internal/checker" - "git.qomar.pw/omar/zhguchiy_perchik/internal/config" - "git.qomar.pw/omar/zhguchiy_perchik/internal/db" - "git.qomar.pw/omar/zhguchiy_perchik/internal/fetcher" - "git.qomar.pw/omar/zhguchiy_perchik/internal/geoip" - "git.qomar.pw/omar/zhguchiy_perchik/internal/notify" - "git.qomar.pw/omar/zhguchiy_perchik/internal/upstream" + "git.eeee.moe/omar/zhguchiy_perchik/internal/checker" + "git.eeee.moe/omar/zhguchiy_perchik/internal/config" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" + "git.eeee.moe/omar/zhguchiy_perchik/internal/fetcher" + "git.eeee.moe/omar/zhguchiy_perchik/internal/geoip" + "git.eeee.moe/omar/zhguchiy_perchik/internal/notify" + "git.eeee.moe/omar/zhguchiy_perchik/internal/upstream" ) // Manual-trigger settings keys written by the API and consumed by the loop. @@ -31,12 +31,16 @@ const ( // Worker owns the check pipeline dependencies. type Worker struct { db *db.DB - chk *checker.Checker + chk proxyChecker geo *geoip.Resolver tg *notify.Telegram log *slog.Logger } +type proxyChecker interface { + Check(context.Context, string, checker.Config) checker.Result +} + // New builds a Worker. func New(database *db.DB, chk *checker.Checker, geo *geoip.Resolver, log *slog.Logger) *Worker { return &Worker{db: database, chk: chk, geo: geo, tg: notify.New(), log: log} @@ -45,15 +49,8 @@ func New(database *db.DB, chk *checker.Checker, geo *geoip.Resolver, log *slog.L // Run drives the control loop until ctx is cancelled. It polls every 5s for // manual triggers and the auto-interval schedule. func (w *Worker) Run(ctx context.Context) { - // Clear any session left 'running' by a previous process — we can't resume it. - if err := w.db.FailStaleRunningSessions(ctx); err != nil { - w.log.Warn("failed to clear stale running sessions", "err", err) - } - var lastFull time.Time - if recent, err := w.db.RecentSessions(ctx, 1); err == nil && len(recent) > 0 { - lastFull = recent[0].StartedAt - } + initialized := false ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() @@ -67,15 +64,47 @@ func (w *Worker) Run(ctx context.Context) { case <-ticker.C: } - settings := w.loadSettings(ctx) + if !initialized { + // Clear sessions from a previous process before taking more work. + if err := w.db.FailStaleRunningSessions(ctx); err != nil { + w.log.Warn("failed to clear stale running sessions") + continue + } + recent, err := w.db.RecentSessions(ctx, 1) + if err != nil { + w.log.Warn("failed to read recent sessions") + continue + } + if len(recent) > 0 { + lastFull = recent[0].StartedAt + } + initialized = true + } + + values, err := w.db.GetSettings(ctx) + if err != nil { + w.log.Warn("settings load failed") + continue + } + settings := config.FromMap(values) // Manual "recheck selected" has priority. - if ids := w.takeRecheckIDs(ctx); len(ids) > 0 { + ids, err := w.takeRecheckIDs(ctx) + if err != nil { + w.log.Warn("failed to consume selected recheck request") + continue + } + if len(ids) > 0 { w.runRecheckSelected(ctx, settings, ids) continue } // Manual full cycle. - if w.takeManualRun(ctx) { + manual, err := w.takeManualRun(ctx) + if err != nil { + w.log.Warn("failed to consume manual cycle request") + continue + } + if manual { w.runFullCycle(ctx, settings, "manual") lastFull = time.Now() continue @@ -91,37 +120,38 @@ func (w *Worker) Run(ctx context.Context) { } } -func (w *Worker) loadSettings(ctx context.Context) config.Settings { - m, err := w.db.GetSettings(ctx) - if err != nil { - w.log.Warn("settings load failed, using defaults", "err", err) - return config.Default() - } - return config.FromMap(m) -} - -func (w *Worker) takeManualRun(ctx context.Context) bool { +func (w *Worker) takeManualRun(ctx context.Context) (bool, error) { v, ok, err := w.db.GetSetting(ctx, keyManualRun) - if err != nil || !ok || v != "true" { - return false + if err != nil { + return false, errors.New("read manual cycle request failed") } - _ = w.db.SetSetting(ctx, keyManualRun, "false") - return true + if !ok || v != "true" { + return false, nil + } + if err := w.db.SetSetting(ctx, keyManualRun, "false"); err != nil { + return false, errors.New("clear manual cycle request failed") + } + return true, nil } -func (w *Worker) takeRecheckIDs(ctx context.Context) []int64 { +func (w *Worker) takeRecheckIDs(ctx context.Context) ([]int64, error) { v, ok, err := w.db.GetSetting(ctx, keyManualRecheck) - if err != nil || !ok || strings.TrimSpace(v) == "" { - return nil + if err != nil { + return nil, errors.New("read selected recheck request failed") + } + if !ok || strings.TrimSpace(v) == "" { + return nil, nil + } + if err := w.db.SetSetting(ctx, keyManualRecheck, ""); err != nil { + return nil, errors.New("clear selected recheck request failed") } - _ = w.db.SetSetting(ctx, keyManualRecheck, "") var ids []int64 for _, part := range strings.Split(v, ",") { if n, err := strconv.ParseInt(strings.TrimSpace(part), 10, 64); err == nil { ids = append(ids, n) } } - return ids + return ids, nil } func checkerConfig(s config.Settings) checker.Config { @@ -151,26 +181,79 @@ func (w *Worker) runFullCycle(ctx context.Context, s config.Settings, trigger st start := time.Now() sessionID, err := w.db.CreateSession(ctx, trigger) if err != nil { - w.log.Error("create session failed", "err", err) + w.log.Error("create session failed") return } - cycleCtx, cancel := context.WithCancel(ctx) - defer cancel() - cancelled := w.watchCancel(cycleCtx, sessionID, cancel) + cycleCtx, cancel := context.WithCancelCause(ctx) + defer cancel(nil) + stopWatching := w.watchCancel(cycleCtx, sessionID, cancel) - w.notify(ctx, s, s.TelegramNotifyStart, fmt.Sprintf("▶️ Проверка запущена (сессия #%d, %s)", sessionID, trigger)) + w.notify(cycleCtx, s, s.TelegramNotifyStart, fmt.Sprintf("▶️ Проверка запущена (сессия #%d, %s)", sessionID, trigger)) w.log.Info("full cycle start", "session", sessionID, "trigger", trigger) - candidates, totalRaw := w.collect(cycleCtx, sessionID) - unique := len(candidates) - collapsed := totalRaw - unique - if collapsed < 0 { - collapsed = 0 + passed, failed, err := w.stageCycle(cycleCtx, cancel, sessionID, s) + stopWatching() + if ctx.Err() != nil { + err = ctx.Err() + } else if cause := context.Cause(cycleCtx); cause != nil { + err = cause } - _ = w.db.SetSessionTotals(cycleCtx, sessionID, totalRaw, unique, collapsed, unique) - w.log.Info("candidates collected", "session", sessionID, "raw", totalRaw, "unique", unique) + dur := time.Since(start).Milliseconds() + if err == nil { + err = w.db.CompleteSession(cycleCtx, sessionID, dur) + if err != nil && !errors.Is(err, db.ErrSessionCancelled) { + if ctx.Err() != nil { + err = ctx.Err() + } else { + err = errors.New("snapshot publication failed") + } + } + } + if err != nil { + w.finishUnpublished(ctx, s, sessionID, dur, err) + return + } + w.log.Info("full cycle done", "session", sessionID, "valid", passed, "invalid", failed, "ms", dur) + w.notify(ctx, s, s.TelegramNotifyFinish, fmt.Sprintf( + "✅ Проверка #%d завершена\nВалидных: %d\nНевалидных: %d\nУникальных кандидатов: %d\nВремя: %.1fs", + sessionID, passed, failed, passed+failed, float64(dur)/1000)) +} - prevSet, _ := w.db.CurrentSessionProxyIDs(cycleCtx) +func (w *Worker) finishUnpublished(ctx context.Context, s config.Settings, sessionID, dur int64, err error) { + status, reason := "failed", err.Error() + if errors.Is(err, db.ErrSessionCancelled) { + status = "cancelled" + } else if ctx.Err() != nil && errors.Is(err, ctx.Err()) { + status, reason = "cancelled", "worker stopped" + } + // The active context may have been cancelled; this write cannot publish. + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + if err := w.db.FailSession(cleanupCtx, sessionID, status, reason, dur); err != nil { + w.log.Error("failed to record unpublished session", "session", sessionID) + } + if status == "cancelled" { + w.log.Info("full cycle cancelled", "session", sessionID, "reason", reason) + w.notify(ctx, s, s.TelegramNotifyFinish, fmt.Sprintf("⏹ Проверка #%d отменена", sessionID)) + return + } + w.log.Error("full cycle failed", "session", sessionID, "reason", reason) +} + +func (w *Worker) stageCycle(ctx context.Context, cancel context.CancelCauseFunc, sessionID int64, s config.Settings) (int, int, error) { + candidates, totalRaw, err := w.collect(ctx, sessionID) + if err != nil { + return 0, 0, err + } + unique := len(candidates) + if err := w.db.SetSessionTotals(ctx, sessionID, totalRaw, unique, totalRaw-unique, unique); err != nil { + return 0, 0, errors.New("record session totals failed") + } + w.log.Info("candidates collected", "session", sessionID, "raw", totalRaw, "unique", unique) + prevSet, err := w.db.CurrentSessionProxyIDs(ctx) + if err != nil { + return 0, 0, errors.New("read previous session membership failed") + } cfg := checkerConfig(s) var ( @@ -179,76 +262,85 @@ func (w *Worker) runFullCycle(ctx context.Context, s config.Settings, trigger st mu sync.Mutex passed int failed int - done int ) +schedule: for _, c := range candidates { - if cycleCtx.Err() != nil { - break + select { + case <-ctx.Done(): + break schedule + case sem <- struct{}{}: } wg.Add(1) - sem <- struct{}{} - go func(c candidate) { + go func() { defer wg.Done() defer func() { <-sem }() - - w.checkOne(cycleCtx, sessionID, c, cfg, prevSet, &mu, &passed, &failed) + if ctx.Err() != nil { + return + } + pass, err := w.checkOne(ctx, sessionID, c, cfg, prevSet) + if err != nil { + cancel(err) + return + } mu.Lock() - done++ - if done%25 == 0 { - _ = w.db.UpdateSessionProgress(cycleCtx, sessionID, done, passed, failed) + defer mu.Unlock() + if pass { + passed++ + } else { + failed++ } - mu.Unlock() - }(c) + done := passed + failed + if done%25 == 0 && done != unique && ctx.Err() == nil { + if err := w.db.UpdateSessionProgress(ctx, sessionID, done, passed, failed); err != nil { + cancel(errors.New("record session progress failed")) + } + } + }() } wg.Wait() - - // Final writes use the parent ctx: the cycle ctx may already be cancelled. - _ = w.db.UpdateSessionProgress(ctx, sessionID, passed+failed, passed, failed) - dur := time.Since(start).Milliseconds() - if cancelled() { - _ = w.db.FailSession(ctx, sessionID, "cancelled", "cancelled by operator", dur) - w.log.Info("full cycle cancelled", "session", sessionID, "passed", passed, "failed", failed) - w.notify(ctx, s, s.TelegramNotifyFinish, fmt.Sprintf("⏹ Проверка #%d отменена", sessionID)) - return + if err := ctx.Err(); err != nil { + return passed, failed, err } - if err := w.db.CompleteSession(ctx, sessionID, dur); err != nil { - w.log.Error("complete session failed", "session", sessionID, "err", err) - _ = w.db.FailSession(ctx, sessionID, "failed", err.Error(), dur) - return + if err := w.db.UpdateSessionProgress(ctx, sessionID, passed+failed, passed, failed); err != nil { + return passed, failed, errors.New("record final session progress failed") } - w.log.Info("full cycle done", "session", sessionID, "valid", passed, "invalid", failed, "ms", dur) - w.notify(ctx, s, s.TelegramNotifyFinish, fmt.Sprintf( - "✅ Проверка #%d завершена\nВалидных: %d\nНевалидных: %d\nУникальных кандидатов: %d\nВремя: %.1fs", - sessionID, passed, failed, unique, float64(dur)/1000)) + return passed, failed, nil } // collect fetches every active source, canonicalizes and dedups its lines, and -// records per-source stats. Returns the unique candidates and the raw line total. -func (w *Worker) collect(ctx context.Context, sessionID int64) ([]candidate, int) { +// records per-source stats. A failed source invalidates the whole cycle. +func (w *Worker) collect(ctx context.Context, sessionID int64) ([]candidate, int, error) { sources, err := w.db.ListActiveSources(ctx) if err != nil { - w.log.Warn("list sources failed", "err", err) - return nil, 0 + return nil, 0, errors.New("list active sources failed") } seen := make(map[string]struct{}) var candidates []candidate totalRaw := 0 for _, src := range sources { - if ctx.Err() != nil { - break + if err := ctx.Err(); err != nil { + return nil, 0, err } lines, ferr := fetcher.FetchSource(ctx, src.URL, src.Kind, w.log) errStr := "" if ferr != nil { errStr = ferr.Error() } - _ = w.db.UpdateSourceFetchStats(ctx, src.ID, len(lines), errStr) + if err := w.db.UpdateSourceFetchStats(ctx, src.ID, len(lines), errStr); err != nil { + return nil, 0, fmt.Errorf("record fetch status for source #%d failed", src.ID) + } + if ferr != nil { + return nil, 0, fmt.Errorf("source #%d: %w", src.ID, ferr) + } totalRaw += len(lines) uniqForSrc := 0 for _, ln := range lines { + if err := ctx.Err(); err != nil { + return nil, 0, err + } canon, up, cerr := upstream.Canonicalize(ln) if cerr != nil { continue @@ -267,36 +359,40 @@ func (w *Worker) collect(ctx context.Context, sessionID int64) ([]candidate, int sourceName: src.Name, }) } - _ = w.db.UpsertSourceStat(ctx, sessionID, src.Name, len(lines), uniqForSrc) + if err := w.db.UpsertSourceStat(ctx, sessionID, src.Name, len(lines), uniqForSrc); err != nil { + return nil, 0, fmt.Errorf("record session stats for source #%d failed", src.ID) + } } - return candidates, totalRaw + return candidates, totalRaw, ctx.Err() } // checkOne runs the pipeline for one candidate and records the outcome. func (w *Worker) checkOne(ctx context.Context, sessionID int64, c candidate, - cfg checker.Config, prevSet map[int64]struct{}, mu *sync.Mutex, passed, failed *int) { - - sid := c.sourceID - proxyID, _, err := w.db.EnsureProxy(ctx, c.canonical, c.protocol, c.host, c.port, &sid, c.sourceName) + cfg checker.Config, prevSet map[int64]struct{}) (bool, error) { + proxyID, _, err := w.db.EnsureProxy(ctx, c.canonical, c.protocol, c.host, c.port, &c.sourceID, c.sourceName) if err != nil { - w.log.Warn("ensure proxy failed", "url", c.canonical, "err", err) - return + return false, errors.New("ensure proxy failed") } res := w.chk.Check(ctx, c.canonical, cfg) - _ = w.db.BumpProtocolStat(ctx, sessionID, c.protocol, res.Passed) - + if ctx.Err() != nil { + return false, ctx.Err() + } + if err := w.db.BumpProtocolStat(ctx, sessionID, c.protocol, res.Passed); err != nil { + return false, errors.New("record protocol stats failed") + } if !res.Passed { - _ = w.db.MarkProxyFail(ctx, proxyID) - mu.Lock() - *failed++ - mu.Unlock() - return + if err := w.db.MarkProxyFail(ctx, proxyID); err != nil { + return false, errors.New("record failed proxy check failed") + } + return false, nil } - _ = w.db.MarkProxyPass(ctx, proxyID, res.LatencyMs, res.SpeedMbps, res.Country, res.ExitIP) + if err := w.db.MarkProxyPass(ctx, proxyID, res.LatencyMs, res.SpeedMbps, res.Country, res.ExitIP); err != nil { + return false, errors.New("record passed proxy check failed") + } _, isKnown := prevSet[proxyID] - _ = w.db.AddSessionProxy(ctx, &db.SessionProxy{ + if err := w.db.AddSessionProxy(ctx, &db.SessionProxy{ ProxyID: proxyID, CanonicalURL: c.canonical, Protocol: c.protocol, @@ -308,11 +404,13 @@ func (w *Worker) checkOne(ctx context.Context, sessionID int64, c candidate, Country: res.Country, ExitIP: res.ExitIP, IsNew: !isKnown, - }, sessionID) - _ = w.db.BumpSourcePassed(ctx, sessionID, c.sourceName) - mu.Lock() - *passed++ - mu.Unlock() + }, sessionID); err != nil { + return false, errors.New("stage session proxy failed") + } + if err := w.db.BumpSourcePassed(ctx, sessionID, c.sourceName); err != nil { + return false, errors.New("record source pass failed") + } + return true, nil } // runRecheckSelected re-validates chosen proxies in place within the current @@ -326,7 +424,7 @@ func (w *Worker) runRecheckSelected(ctx context.Context, s config.Settings, ids } refs, err := w.db.GetProxyRefs(ctx, ids) if err != nil { - w.log.Warn("recheck: load refs failed", "err", err) + w.log.Warn("recheck: load refs failed") return } w.log.Info("recheck selected start", "count", len(refs), "session", cur.ID) @@ -376,28 +474,38 @@ func (w *Worker) runRecheckSelected(ctx context.Context, s config.Settings, ids w.log.Info("recheck selected done", "rechecked", len(refs), "dropped", len(drop)) } -// watchCancel polls the session's cancel flag every 2s and cancels the cycle -// context when set. The returned closure reports whether cancel fired. -func (w *Worker) watchCancel(ctx context.Context, sessionID int64, cancel context.CancelFunc) func() bool { - var flag atomic.Bool +// watchCancel stops the cycle on explicit cancellation or polling failure. +// Stop and join the watcher before publication checks cancellation itself. +func (w *Worker) watchCancel(ctx context.Context, sessionID int64, cancel context.CancelCauseFunc) func() { + pollCtx, stop := context.WithCancel(ctx) + done := make(chan struct{}) go func() { + defer close(done) t := time.NewTicker(2 * time.Second) defer t.Stop() for { select { - case <-ctx.Done(): + case <-pollCtx.Done(): return case <-t.C: - b, err := w.db.IsCancelRequested(ctx, sessionID) - if err == nil && b { - flag.Store(true) - cancel() + requested, err := w.db.IsCancelRequested(pollCtx, sessionID) + if err != nil { + if pollCtx.Err() == nil || !errors.Is(err, pollCtx.Err()) { + cancel(errors.New("read session cancellation flag failed")) + } + return + } + if requested { + cancel(db.ErrSessionCancelled) return } } } }() - return flag.Load + return func() { + stop() + <-done + } } func (w *Worker) notify(ctx context.Context, s config.Settings, when bool, text string) { @@ -405,6 +513,6 @@ func (w *Worker) notify(ctx context.Context, s config.Settings, when bool, text return } if err := w.tg.Send(ctx, s.TelegramBotToken, s.TelegramChatID, text); err != nil { - w.log.Warn("telegram send failed", "err", err) + w.log.Warn("telegram send failed") } } diff --git a/internal/worker/worker_test.go b/internal/worker/worker_test.go new file mode 100644 index 0000000..d5b7a4d --- /dev/null +++ b/internal/worker/worker_test.go @@ -0,0 +1,265 @@ +package worker + +import ( + "bytes" + "context" + "crypto/rand" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5" + + "git.eeee.moe/omar/zhguchiy_perchik/internal/checker" + "git.eeee.moe/omar/zhguchiy_perchik/internal/config" + "git.eeee.moe/omar/zhguchiy_perchik/internal/db" +) + +const testProxy = "trojan://proxy-test-token@proxy.invalid:443" + +func TestFullCycleKeepsPreviousSnapshotOnFailure(t *testing.T) { + database := isolatedDB(t) + ctx := t.Context() + s := config.Settings{Workers: 1} + var logs bytes.Buffer + w := &Worker{ + db: database, + chk: staticChecker{Passed: true}, + log: slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})), + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/failed" { + w.WriteHeader(http.StatusForbidden) + } + _, _ = io.WriteString(w, testProxy+"\n") + })) + t.Cleanup(server.Close) + _, err := database.CreateSource(ctx, "working", server.URL+"/working", "plain", true) + mustDB(t, err) + w.runFullCycle(ctx, s, "manual") + current, err := database.GetCurrentSession(ctx) + mustDB(t, err) + if current == nil || current.Valid != 1 { + t.Fatal("initial complete snapshot with one proxy was not published") + } + + t.Run("other active source returned HTTP error", func(t *testing.T) { + id, err := database.CreateSource(ctx, "source-test-token", server.URL+"/failed?token=source-test-token", "plain", true) + mustDB(t, err) + t.Cleanup(func() { mustDB(t, database.DeleteSource(ctx, id)) }) + w.runFullCycle(ctx, s, "manual") + assertRetainedSnapshot(t, database, current.ID, "source returned HTTP status 403") + sources, err := database.ListActiveSources(ctx) + mustDB(t, err) + if len(sources) != 2 || sources[1].LastError != "source returned HTTP status 403" { + t.Fatal("fetch outcome was not persisted safely") + } + }) + + t.Run("source decoding failed", func(t *testing.T) { + id, err := database.CreateSource(ctx, "invalid subscription", server.URL+"/invalid", "base64", true) + mustDB(t, err) + t.Cleanup(func() { mustDB(t, database.DeleteSource(ctx, id)) }) + w.runFullCycle(ctx, s, "manual") + assertRetainedSnapshot(t, database, current.ID, "invalid base64 source body") + }) + + t.Run("proxy history write failed with sensitive error", func(t *testing.T) { + mustExec(t, database, `ALTER TABLE proxies ADD CONSTRAINT test_proxy_write CHECK (total_checks < 2 OR canonical_url = '')`) + t.Cleanup(func() { mustExec(t, database, `ALTER TABLE proxies DROP CONSTRAINT test_proxy_write`) }) + w.runFullCycle(ctx, s, "manual") + assertRetainedSnapshot(t, database, current.ID, "record passed proxy check failed") + }) + + t.Run("final progress write suppressed", func(t *testing.T) { + mustExec(t, database, `CREATE FUNCTION skip_update() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NULL; END; $$`) + t.Cleanup(func() { mustExec(t, database, `DROP FUNCTION skip_update() CASCADE`) }) + mustExec(t, database, `CREATE TRIGGER skip_progress BEFORE UPDATE OF progress_done ON check_sessions FOR EACH ROW EXECUTE FUNCTION skip_update()`) + w.runFullCycle(ctx, s, "manual") + assertRetainedSnapshot(t, database, current.ID, "record final session progress failed") + }) + + t.Run("publishing row failed after unsetting previous", func(t *testing.T) { + mustExec(t, database, `ALTER TABLE check_sessions ADD CONSTRAINT test_publication CHECK (NOT is_current) NOT VALID`) + t.Cleanup(func() { mustExec(t, database, `ALTER TABLE check_sessions DROP CONSTRAINT test_publication`) }) + w.runFullCycle(ctx, s, "manual") + assertRetainedSnapshot(t, database, current.ID, "snapshot publication failed") + }) + + t.Run("publishing row affected zero rows", func(t *testing.T) { + mustExec(t, database, `CREATE FUNCTION skip_update() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NULL; END; $$`) + t.Cleanup(func() { mustExec(t, database, `DROP FUNCTION skip_update() CASCADE`) }) + mustExec(t, database, `CREATE TRIGGER skip_publication BEFORE UPDATE ON check_sessions FOR EACH ROW + WHEN (NEW.is_current AND NOT OLD.is_current) EXECUTE FUNCTION skip_update()`) + w.runFullCycle(ctx, s, "manual") + assertRetainedSnapshot(t, database, current.ID, "snapshot publication failed") + }) + + for _, secret := range []string{"source-test-token", "proxy-test-token", "test_proxy_write", "test_publication", server.URL} { + if strings.Contains(logs.String(), secret) { + t.Fatal("worker leaked credentials or raw database error") + } + } +} + +func TestFullCycleCanPublishNoWorkingProxies(t *testing.T) { + database := isolatedDB(t) + ctx := t.Context() + s := config.Settings{Workers: 1} + w := &Worker{db: database, chk: staticChecker{}, log: slog.New(slog.DiscardHandler)} + w.runFullCycle(ctx, s, "manual") + empty, err := database.GetCurrentSession(ctx) + mustDB(t, err) + if empty == nil || empty.Valid != 0 || empty.ProgressDone != 0 { + t.Fatal("successful empty collection was not published") + } + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, testProxy+"\n") + })) + t.Cleanup(server.Close) + _, err = database.CreateSource(ctx, "one candidate", server.URL, "plain", true) + mustDB(t, err) + w.runFullCycle(ctx, s, "manual") + current, err := database.GetCurrentSession(ctx) + mustDB(t, err) + if current == nil || current.ID == empty.ID || current.Valid != 0 || current.Invalid != 1 || current.ProgressDone != 1 { + t.Fatal("successful cycle with no valid proxies did not replace previous snapshot") + } +} + +func TestCompleteSessionRejectsIncompleteAndCancelledSnapshots(t *testing.T) { + database := isolatedDB(t) + ctx := t.Context() + current, err := database.CreateSession(ctx, "manual") + mustDB(t, err) + mustDB(t, database.SetSessionTotals(ctx, current, 0, 0, 0, 0)) + mustDB(t, database.UpdateSessionProgress(ctx, current, 0, 0, 0)) + mustDB(t, database.CompleteSession(ctx, current, 0)) + + unstaged, err := database.CreateSession(ctx, "manual") + mustDB(t, err) + if err := database.CompleteSession(ctx, unstaged, 0); err == nil { + t.Fatal("published a new session without import totals or a final progress write") + } + mustDB(t, database.SetSessionTotals(ctx, unstaged, 0, 0, 0, 0)) + if err := database.CompleteSession(ctx, unstaged, 0); err == nil { + t.Fatal("published a zero-candidate session without a final progress write") + } + + incomplete, err := database.CreateSession(ctx, "manual") + mustDB(t, err) + mustDB(t, database.SetSessionTotals(ctx, incomplete, 1, 1, 0, 1)) + mustDB(t, database.UpdateSessionProgress(ctx, incomplete, 1, 1, 0)) + mustDB(t, database.UpsertSourceStat(ctx, incomplete, "one candidate", 1, 1)) + mustDB(t, database.BumpProtocolStat(ctx, incomplete, "http", true)) + mustDB(t, database.BumpSourcePassed(ctx, incomplete, "one candidate")) + if err := database.CompleteSession(ctx, incomplete, 0); err == nil { + t.Fatal("published without the passing membership row despite complete counters") + } + + cancelled, err := database.CreateSession(ctx, "manual") + mustDB(t, err) + mustDB(t, database.SetSessionTotals(ctx, cancelled, 0, 0, 0, 0)) + mustDB(t, database.UpdateSessionProgress(ctx, cancelled, 0, 0, 0)) + mustDB(t, database.RequestCancel(ctx, cancelled)) + if err := database.CompleteSession(ctx, cancelled, 0); !errors.Is(err, db.ErrSessionCancelled) { + t.Fatalf("CompleteSession returned %v; want operator cancellation", err) + } + published, err := database.GetCurrentSession(ctx) + mustDB(t, err) + if published == nil || published.ID != current { + t.Fatal("unpublishable session replaced the previous snapshot") + } +} + +type staticChecker checker.Result + +func (c staticChecker) Check(context.Context, string, checker.Config) checker.Result { + return checker.Result(c) +} + +func isolatedDB(t *testing.T) *db.DB { + t.Helper() + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("set TEST_DATABASE_URL to exercise snapshot transactions on test PostgreSQL") + } + admin, err := db.New(t.Context(), dsn) + if err != nil { + t.Fatal("could not connect to the snapshot test database") + } + t.Cleanup(admin.Close) + schema := "snapshot_test_" + strings.ToLower(rand.Text()) + identifier := pgx.Identifier{schema}.Sanitize() + mustExec(t, admin, "CREATE SCHEMA "+identifier) + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, err := admin.Pool().Exec(ctx, "DROP SCHEMA "+identifier+" CASCADE") + mustDB(t, err) + }) + scopedDSN := dsn + " search_path=" + schema + if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") { + uri, err := url.Parse(dsn) + if err != nil { + t.Fatal("could not parse the snapshot test database URI") + } + params := uri.Query() + params.Set("search_path", schema) + uri.RawQuery = params.Encode() + scopedDSN = uri.String() + } + database, err := db.New(t.Context(), scopedDSN) + if err != nil { + t.Fatal("could not connect to isolated snapshot schema") + } + t.Cleanup(database.Close) + mustDB(t, database.ApplySchema(t.Context())) + return database +} + +func mustDB(t *testing.T, err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } +} + +func mustExec(t *testing.T, database *db.DB, sql string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), 5*time.Second) + defer cancel() + _, err := database.Pool().Exec(ctx, sql) + mustDB(t, err) +} + +func assertRetainedSnapshot(t *testing.T, database *db.DB, previous int64, reason string) { + t.Helper() + ctx := t.Context() + current, err := database.GetCurrentSession(ctx) + mustDB(t, err) + if current == nil || current.ID != previous || current.Status != "completed" || current.Valid != 1 { + t.Fatal("previous current snapshot changed") + } + ids, err := database.CurrentSessionProxyIDs(ctx) + mustDB(t, err) + if len(ids) != 1 { + t.Fatal("previous current membership changed") + } + sessions, err := database.RecentSessions(ctx, 1) + mustDB(t, err) + if len(sessions) != 1 || sessions[0].Status != "failed" || sessions[0].IsCurrent || !strings.Contains(sessions[0].Error, reason) { + t.Fatalf("new session was not recorded as a noncurrent failure with reason %q", reason) + } + if strings.Contains(sessions[0].Error, "source-test-token") || strings.Contains(sessions[0].Error, "proxy-test-token") { + t.Fatal("stored worker failure reason leaked credentials") + } +} diff --git a/migrations/0001_init.sql b/migrations/0001_init.sql index a122934..962bc10 100644 --- a/migrations/0001_init.sql +++ b/migrations/0001_init.sql @@ -165,7 +165,7 @@ INSERT INTO settings (key, value) VALUES ('max_latency_ms', '1000'), ('min_speed_mbps', '3'), ('speedtest_enabled', 'true'), - ('speedtest_url', 'http://cachefly.cachefly.net/10mb.test'), + ('speedtest_url', 'https://speedtest.selectel.ru/10MB'), ('geoip_db_url', 'https://cdn.jsdelivr.net/npm/@ip-location-db/geolite2-geo-whois-asn-country-mmdb/geolite2-geo-whois-asn-country.mmdb'), ('auto_enabled', 'true'), ('telegram_bot_token', ''), @@ -173,3 +173,7 @@ INSERT INTO settings (key, value) VALUES ('telegram_notify_start', 'false'), ('telegram_notify_finish', 'true') ON CONFLICT (key) DO NOTHING; + +-- Replace the old built-in HTTP URL without changing custom settings. +UPDATE settings SET value = 'https://speedtest.selectel.ru/10MB', updated_at = now() +WHERE key = 'speedtest_url' AND value = 'http://cachefly.cachefly.net/10mb.test';