fix public ip selfcheck logic

This commit is contained in:
ayurishchev committed 2026-08-21 11:04:49 +03:00
1 parent a6f9646da5
commit 67adc6670e
18 files changed
+209 -90

No files matched your search

+62 -8
View File
@@ -11,8 +11,12 @@ package agentcore
import (
"context"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"strings"
"time"
"cloudipvalidator/internal/apiclient"
@@ -139,19 +143,16 @@ func (a *Agent) handleSelfCheckAndRun(ctx context.Context, assignment assignment
selfCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
var whoami struct {
IP string `json:"ip"`
}
_, err := a.client.Do(selfCtx, "GET", "/api/v1/whatsmyip", nil, &whoami)
success := err == nil && whoami.IP == assignment.IPAddress
detectedIP, err := a.detectPublicIP(selfCtx)
success := err == nil && detectedIP == assignment.IPAddress
detail := "matched"
if err != nil {
detail = "whatsmyip request failed: " + err.Error()
detail = "ip echo request failed: " + err.Error()
} else if !success {
detail = fmt.Sprintf("egress ip %q does not match assigned fip %q", whoami.IP, assignment.IPAddress)
detail = fmt.Sprintf("egress ip %q does not match assigned fip %q", detectedIP, assignment.IPAddress)
}
a.postSelfCheck(ctx, assignment.IPID, whoami.IP, success, detail)
a.postSelfCheck(ctx, assignment.IPID, detectedIP, success, detail)
a.postEvent(ctx, assignment.IPID, "self_check_result", fmt.Sprintf(`{"success":%t}`, success))
if !success {
@@ -161,6 +162,59 @@ func (a *Agent) handleSelfCheckAndRun(ctx context.Context, assignment assignment
a.runChecks(ctx, assignment)
}
// detectPublicIP asks each configured IP-echo URL, in order, for the
// address this validator is currently seen egressing from, returning the
// first one that answers with a parseable IP. These must be resources
// genuinely outside the cloud project (see config.SelfCheckCfg) — OpenStack
// only applies floating-IP SNAT to traffic leaving via the external
// network, so anything reachable over the project's internal network would
// report the validator's private address instead, regardless of whether
// the floating IP is correctly attached.
func (a *Agent) detectPublicIP(ctx context.Context) (string, error) {
var lastErr error
for _, url := range a.cfg.SelfCheck.IPEchoURLs {
ip, err := fetchIPEcho(ctx, url)
if err != nil {
lastErr = fmt.Errorf("%s: %w", url, err)
continue
}
return ip, nil
}
if lastErr == nil {
lastErr = fmt.Errorf("no self_check.ip_echo_urls configured")
}
return "", lastErr
}
// fetchIPEcho performs a single GET against an IP-echo endpoint that
// returns the caller's address as a bare string in the response body
// (the common contract shared by services like api.ipify.org,
// ifconfig.me/ip, icanhazip.com — and by the local stub used in
// scripts/run-local-e2e.sh).
func fetchIPEcho(ctx context.Context, url string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", fmt.Errorf("build request: %w", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return "", fmt.Errorf("unexpected status %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, 256))
if err != nil {
return "", fmt.Errorf("read response: %w", err)
}
ip := strings.TrimSpace(string(body))
if net.ParseIP(ip) == nil {
return "", fmt.Errorf("response is not a valid IP: %q", ip)
}
return ip, nil
}
func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) {
var results []checkResultDTO
for _, ct := range assignment.CheckConfig {
+14 -1
View File
@@ -175,8 +175,18 @@ type ValidatorAgent struct {
Checks AgentChecks `yaml:"checks"`
}
// SelfCheckCfg configures how the agent confirms its egress actually flows
// through the newly assigned floating IP. This must query a resource
// genuinely outside the cloud project: OpenStack only applies floating-IP
// SNAT to traffic leaving via the external/provider network, so any
// in-project resource (including control-api, if it's reachable over the
// project's internal network) would see the validator's private address
// instead — a false negative that never changes. IPEchoURLs are tried in
// order (falling through to the next on error/timeout, not on a genuine
// mismatch) until one returns a parseable IP.
type SelfCheckCfg struct {
TimeoutSeconds int `yaml:"timeout_seconds"`
TimeoutSeconds int `yaml:"timeout_seconds"`
IPEchoURLs []string `yaml:"ip_echo_urls"`
}
type AgentChecks struct {
@@ -202,6 +212,9 @@ func LoadValidatorAgent(path string) (*ValidatorAgent, error) {
if c.SelfCheck.TimeoutSeconds == 0 {
c.SelfCheck.TimeoutSeconds = 10
}
if len(c.SelfCheck.IPEchoURLs) == 0 {
c.SelfCheck.IPEchoURLs = []string{"https://api.ipify.org", "https://ifconfig.me/ip"}
}
if c.Checks.HTTPSTimeoutSeconds == 0 {
c.Checks.HTTPSTimeoutSeconds = 10
}
-4
View File
@@ -139,7 +139,3 @@ func (s *Server) handleAgentComplete(w http.ResponseWriter, r *http.Request) {
}
writeJSON(w, http.StatusOK, okResponse{OK: true})
}
func (s *Server) handleWhatsMyIP(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"ip": remoteIP(r)})
}
+4 -7
View File
@@ -123,13 +123,10 @@ func TestEndToEndHTTPFlow(t *testing.T) {
t.Fatalf("expected 1.2.3.4, got %s", assignment.IPAddress)
}
// Self-check via /whatsmyip: in the real deployment this would equal
// the FIP; here we just exercise the endpoint and always report success.
resp, body = fc.do(http.MethodGet, "/api/v1/whatsmyip", nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("whatsmyip: status=%d body=%s", resp.StatusCode, body)
}
// Self-check: in the real deployment the agent queries an external
// IP-echo service (see internal/agentcore.detectPublicIP) and compares
// the result to the assigned FIP; the HTTP layer here just accepts
// whatever outcome the caller reports.
resp, body = fc.do(http.MethodPost, "/api/v1/agents/validator-1/self-check", selfCheckRequest{
IPID: assignment.IPID, DetectedEgress: "1.2.3.4", Success: true, Detail: "matched",
})
-1
View File
@@ -4,7 +4,6 @@ import "net/http"
func (s *Server) routes(mux *http.ServeMux) {
mux.HandleFunc("GET /healthz", s.handleHealthz)
mux.HandleFunc("GET /api/v1/whatsmyip", s.handleWhatsMyIP)
mux.HandleFunc("POST /api/v1/agents/register", s.handleAgentRegister)
mux.HandleFunc("POST /api/v1/agents/{id}/heartbeat", s.handleAgentHeartbeat)
-13
View File
@@ -8,7 +8,6 @@ package httpapi
import (
"encoding/json"
"log/slog"
"net"
"net/http"
"cloudipvalidator/internal/db"
@@ -57,15 +56,3 @@ func readJSON(r *http.Request, v interface{}) error {
dec := json.NewDecoder(r.Body)
return dec.Decode(v)
}
// remoteIP returns the caller's source IP with any port stripped. Used by
// /whatsmyip — the validator-agent's self-check mechanism relies on this
// being the actual TCP peer address (as SNAT'd by the newly associated
// FIP), never a client-supplied header.
func remoteIP(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}