Support configurable TLS probes in the API and dashboard

This commit is contained in:
ayurishchev committed 2026-11-20 21:15:22 +03:00
1 parent 0bde5627f0
commit c7fdd2c430
38 files changed
+495 -203

No files matched your search

+21 -3
View File
@@ -3,6 +3,7 @@ package checkrunner
import (
"context"
"crypto/tls"
"fmt"
"net"
"strconv"
"time"
@@ -16,15 +17,25 @@ import (
// to expect a signed cert yet. This checks "is there a real TLS listener
// here", not "is its certificate valid" — same scope-limiting principle
// SSHBanner already applies (banner only, no auth handshake).
func TLSHandshake(host string, port int, timeout time.Duration) func(ctx context.Context) Result {
func TLSHandshake(host string, port int, version string, timeout time.Duration) func(ctx context.Context) Result {
target := net.JoinHostPort(host, strconv.Itoa(port))
checkType := "tls-" + strconv.Itoa(port)
return run(checkType, target, func(ctx context.Context) error {
probe := run(checkType, target, func(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
config := &tls.Config{InsecureSkipVerify: true}
switch version {
case "":
case "1.2":
config.MinVersion, config.MaxVersion = tls.VersionTLS12, tls.VersionTLS12
case "1.3":
config.MinVersion, config.MaxVersion = tls.VersionTLS13, tls.VersionTLS13
default:
return fmt.Errorf("unsupported TLS version %q", version)
}
d := tls.Dialer{
NetDialer: &net.Dialer{Timeout: timeout},
Config: &tls.Config{InsecureSkipVerify: true},
Config: config,
}
conn, err := d.DialContext(ctx, "tcp", target)
if err != nil {
@@ -32,4 +43,11 @@ func TLSHandshake(host string, port int, timeout time.Duration) func(ctx context
}
return conn.Close()
})
return func(ctx context.Context) Result {
result := probe(ctx)
if version != "" {
result.Detail = "TLS " + version + ": " + result.Detail
}
return result
}
}
+29 -3
View File
@@ -2,9 +2,11 @@ package checkrunner
import (
"context"
"crypto/tls"
"net"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
)
@@ -29,7 +31,7 @@ func TestTLSHandshakeSucceedsAgainstTLSServer(t *testing.T) {
defer ts.Close()
host, port := splitHostPortInt(t, ts.Listener.Addr().String())
res := TLSHandshake(host, port, time.Second)(context.Background())
res := TLSHandshake(host, port, "", time.Second)(context.Background())
if !res.Success {
t.Fatalf("expected success, got failure: %s", res.Detail)
}
@@ -47,7 +49,7 @@ func TestTLSHandshakeFailsAgainstPlainTCP(t *testing.T) {
defer ts.Close()
host, port := splitHostPortInt(t, ts.Listener.Addr().String())
res := TLSHandshake(host, port, time.Second)(context.Background())
res := TLSHandshake(host, port, "", time.Second)(context.Background())
if res.Success {
t.Fatalf("expected failure against a plain TCP listener, got success")
}
@@ -63,8 +65,32 @@ func TestTLSHandshakeFailsOnConnectionRefused(t *testing.T) {
_, port := splitHostPortInt(t, l.Addr().String())
l.Close() // close immediately so the port refuses connections
res := TLSHandshake("127.0.0.1", port, time.Second)(context.Background())
res := TLSHandshake("127.0.0.1", port, "", time.Second)(context.Background())
if res.Success {
t.Fatalf("expected failure against a closed port, got success")
}
}
func TestTLSHandshakeRequiresExactVersion(t *testing.T) {
for _, server := range []struct {
name string
version uint16
}{{"1.2", tls.VersionTLS12}, {"1.3", tls.VersionTLS13}} {
t.Run(server.name, func(t *testing.T) {
ts := httptest.NewUnstartedServer(nil)
ts.TLS = &tls.Config{MinVersion: server.version, MaxVersion: server.version}
ts.StartTLS()
defer ts.Close()
host, port := splitHostPortInt(t, ts.Listener.Addr().String())
for _, requested := range []string{"", "1.2", "1.3"} {
result := TLSHandshake(host, port, requested, time.Second)(context.Background())
if result.Success != (requested == "" || requested == server.name) {
t.Errorf("TLS %q against %s: %+v", requested, server.name, result)
}
if requested != "" && !strings.HasPrefix(result.Detail, "TLS "+requested+": ") {
t.Errorf("missing requested version in result detail: %q", result.Detail)
}
}
})
}
}
+5 -2
View File
@@ -8,6 +8,8 @@ import (
"fmt"
"os"
"cloudipvalidator/internal/inbound"
"gopkg.in/yaml.v3"
)
@@ -133,8 +135,9 @@ type CheckTypeConfig struct {
}
type InboundConfig struct {
Ports []int `yaml:"ports"`
ICMP bool `yaml:"icmp"`
Ports []int `yaml:"ports"`
ICMP bool `yaml:"icmp"`
TLSChecks []inbound.TLSCheck `yaml:"tls_checks"`
}
func LoadControlAPI(path string) (*ControlAPI, error) {
+9 -3
View File
@@ -11,6 +11,8 @@ import (
"strconv"
"strings"
"time"
"cloudipvalidator/internal/inbound"
)
// apiErr is returned by every client method for a non-2xx response from
@@ -490,10 +492,14 @@ func (c *client) GetInboundChecks(ctx context.Context) (inboundChecksDTO, error)
return out, err
}
func (c *client) PutInboundChecks(ctx context.Context, ports []int, icmp bool) (inboundChecksDTO, error) {
func (c *client) PutInboundChecks(ctx context.Context, ports []int, icmp bool, tlsChecks *[]inbound.TLSCheck) (inboundChecksDTO, error) {
var out inboundChecksDTO
err := c.do(ctx, http.MethodPut, "/api/v1/admin/config/inbound-checks",
inboundChecksDTO{Ports: ports, ICMP: icmp}, &out)
body := struct {
Ports []int `json:"ports"`
ICMP bool `json:"icmp"`
TLSChecks *[]inbound.TLSCheck `json:"tls_checks,omitempty"`
}{Ports: ports, ICMP: icmp, TLSChecks: tlsChecks}
err := c.do(ctx, http.MethodPut, "/api/v1/admin/config/inbound-checks", body, &out)
return out, err
}
+6 -2
View File
@@ -15,6 +15,8 @@ import (
"sync"
"testing"
"time"
"cloudipvalidator/internal/inbound"
)
// fakeControlAPI is a minimal in-memory stand-in for control-api's
@@ -35,6 +37,7 @@ type fakeControlAPI struct {
fipSettleSeconds int
inboundPorts []int
inboundICMP bool
inboundTLS []inbound.TLSCheck
historyRetentionCycles int
selfCheckMaxAttempts int
@@ -661,7 +664,7 @@ func (f *fakeControlAPI) handler() http.Handler {
mux.HandleFunc("GET /api/v1/admin/config/inbound-checks", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
writeJSON(w, http.StatusOK, inboundChecksDTO{Ports: f.inboundPorts, ICMP: f.inboundICMP})
writeJSON(w, http.StatusOK, inboundChecksDTO{Ports: f.inboundPorts, ICMP: f.inboundICMP, TLSChecks: f.inboundTLS})
})
mux.HandleFunc("PUT /api/v1/admin/config/inbound-checks", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
@@ -676,7 +679,8 @@ func (f *fakeControlAPI) handler() http.Handler {
}
f.inboundPorts = req.Ports
f.inboundICMP = req.ICMP
writeJSON(w, http.StatusOK, inboundChecksDTO{Ports: f.inboundPorts, ICMP: f.inboundICMP})
f.inboundTLS = req.TLSChecks
writeJSON(w, http.StatusOK, req)
})
mux.HandleFunc("GET /api/v1/admin/config/validators", func(w http.ResponseWriter, r *http.Request) {
+15 -2
View File
@@ -4,6 +4,8 @@ import (
"fmt"
"strconv"
"time"
"cloudipvalidator/internal/inbound"
)
// Wire shapes for control-api's /api/v1/admin/* surface, defined locally
@@ -412,8 +414,19 @@ type orchestratorSettingsDTO struct {
}
type inboundChecksDTO struct {
Ports []int `json:"ports"`
ICMP bool `json:"icmp"`
Ports []int `json:"ports"`
ICMP bool `json:"icmp"`
TLSChecks []inbound.TLSCheck `json:"tls_checks"`
}
func (v inboundChecksDTO) TLSMode() string {
if v.TLSChecks == nil {
return "auto"
}
if len(v.TLSChecks) == 0 {
return "disabled"
}
return "custom"
}
// autoCycleDTO mirrors internal/httpapi's autoCycleDTO — the status and
+48 -12
View File
@@ -6,12 +6,15 @@ import (
"net/http"
"strconv"
"strings"
"cloudipvalidator/internal/inbound"
)
type settingsPageData struct {
PageData
Settings orchestratorSettingsDTO
Inbound inboundChecksDTO
Settings orchestratorSettingsDTO
Inbound inboundChecksDTO
InboundError bannerData
// AutoCycle is the automatic-check-cycle panel's status/parameters.
AutoCycle autoCycleDTO
// Subnets is the list the analytics page groups addresses by.
@@ -43,6 +46,10 @@ func (s *Server) handleSettingsPage(w http.ResponseWriter, r *http.Request) {
// banner — same pattern as renderIPsTable: always reflect true current
// state regardless of whether the mutation itself succeeded.
func (s *Server) renderSettingsForm(w http.ResponseWriter, r *http.Request, actionErr error) {
s.renderSettings(w, r, actionErr, nil)
}
func (s *Server) renderSettings(w http.ResponseWriter, r *http.Request, actionErr, inboundFormErr error) {
settings, getErr := s.CA.GetOrchestratorSettings(r.Context())
if actionErr == nil {
actionErr = getErr
@@ -59,7 +66,9 @@ func (s *Server) renderSettingsForm(w http.ResponseWriter, r *http.Request, acti
if actionErr == nil {
actionErr = subnetsErr
}
s.renderFragment(w, "settings_form", settingsPageData{Settings: settings, Inbound: inbound, AutoCycle: autoCycle, Subnets: subnets}, actionErr)
s.renderFragment(w, "settings_form", settingsPageData{
Settings: settings, Inbound: inbound, InboundError: bannerFor(inboundFormErr), AutoCycle: autoCycle, Subnets: subnets,
}, actionErr)
}
func (s *Server) handleSettingsPut(w http.ResponseWriter, r *http.Request) {
@@ -86,14 +95,9 @@ func (s *Server) handleSettingsPut(w http.ResponseWriter, r *http.Request) {
s.renderSettingsForm(w, r, err)
}
// handleInboundChecksPut parses the comma-separated ports field of the
// second form on /settings and saves it via PUT
// /api/v1/admin/config/inbound-checks. A separate form/handler from
// fip_settle_seconds above — the two settings are unrelated and shouldn't
// share one submit.
func (s *Server) handleInboundChecksPut(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
s.renderSettingsForm(w, r, fmt.Errorf("invalid form: %w", err))
s.renderSettings(w, r, nil, fmt.Errorf("invalid form: %w", err))
return
}
raw := strings.TrimSpace(r.PostFormValue("ports"))
@@ -106,15 +110,47 @@ func (s *Server) handleInboundChecksPut(w http.ResponseWriter, r *http.Request)
}
p, err := strconv.Atoi(part)
if err != nil {
s.renderSettingsForm(w, r, &apiErr{Status: http.StatusBadRequest, Message: "порты должны быть целыми числами через запятую"})
s.renderSettings(w, r, nil, &apiErr{Status: http.StatusBadRequest, Message: "порты должны быть целыми числами через запятую"})
return
}
ports = append(ports, p)
}
}
tlsChecks, err := parseInboundTLSForm(r)
if err != nil {
s.renderSettings(w, r, nil, &apiErr{Status: http.StatusBadRequest, Message: err.Error()})
return
}
icmp := r.PostFormValue("icmp") == "on"
_, err := s.CA.PutInboundChecks(r.Context(), ports, icmp)
s.renderSettingsForm(w, r, err)
_, err = s.CA.PutInboundChecks(r.Context(), ports, icmp, tlsChecks)
s.renderSettings(w, r, nil, err)
}
func parseInboundTLSForm(r *http.Request) (*[]inbound.TLSCheck, error) {
var checks []inbound.TLSCheck
switch r.PostFormValue("tls_mode") {
case "":
return nil, nil
case "auto":
return &checks, nil
case "disabled":
checks = []inbound.TLSCheck{}
case "custom":
ports, versions := r.PostForm["tls_port"], r.PostForm["tls_version"]
if len(ports) == 0 || len(ports) != len(versions) {
return nil, fmt.Errorf("добавьте хотя бы одну TLS-проверку с портом и версией")
}
for i, rawPort := range ports {
port, err := strconv.Atoi(rawPort)
if err != nil {
return nil, fmt.Errorf("порт в строке TLS %d должен быть целым числом", i+1)
}
checks = append(checks, inbound.TLSCheck{Port: port, Version: versions[i]})
}
default:
return nil, fmt.Errorf("выберите режим TLS")
}
return &checks, nil
}
// handleSubnetsPut saves the subnet list from the textarea of /settings: one
+26
View File
@@ -443,6 +443,32 @@ func TestInboundChecksPutUpdatesForm(t *testing.T) {
}
}
func TestInboundTLSFormRoundTrip(t *testing.T) {
_, caURL := newFakeControlAPI(t)
ts := newTestServer(t, caURL)
form := map[string][]string{
"tls_mode": {"custom"}, "tls_port": {"8443", "9443"}, "tls_version": {"1.2", "1.3"},
}
body := postForm(t, ts, "PUT", "/settings/inbound-checks", form)
for _, page := range []string{body, get(t, ts, "/settings")} {
for _, value := range []string{`value="custom" selected`, `value="8443"`, `value="9443"`, `value="1.2" selected`, `value="1.3" selected`} {
if !strings.Contains(page, value) {
t.Errorf("missing %q from persisted TLS form", value)
}
}
}
for _, mode := range []string{"disabled", "auto"} {
body = postForm(t, ts, "PUT", "/settings/inbound-checks", map[string][]string{"tls_mode": {mode}})
if !strings.Contains(body, fmt.Sprintf(`value="%s" selected`, mode)) {
t.Errorf("TLS mode %q did not round-trip", mode)
}
}
body = postForm(t, ts, "PUT", "/settings/inbound-checks", map[string][]string{"tls_mode": {"custom"}})
if !strings.Contains(body, "добавьте хотя бы одну TLS-проверку") {
t.Error("missing validation message for custom TLS with no rows")
}
}
func TestIPsPageShowsSettleBadge(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
now := time.Now()
@@ -0,0 +1,30 @@
(() => {
function addRow(form) {
const template = form.querySelector("[data-tls-row-template]");
const row = template.content.cloneNode(true);
const input = row.querySelector("input");
form.querySelector("[data-tls-rows]").append(row);
input.focus();
}
document.addEventListener("change", event => {
if (!event.target.matches("[data-inbound-checks] select[name=tls_mode]")) return;
const form = event.target.form;
const fields = form.querySelector("[data-tls-fields]");
const custom = event.target.value === "custom";
fields.hidden = fields.disabled = !custom;
if (custom && !fields.querySelector("[data-tls-row]")) addRow(form);
});
document.addEventListener("click", event => {
const button = event.target.closest("[data-tls-add], [data-tls-remove]");
const form = button?.closest("[data-inbound-checks]");
if (!form) return;
if (button.matches("[data-tls-add]")) {
addRow(form);
} else {
button.closest("[data-tls-row]").remove();
form.querySelector("[data-tls-add]").focus();
}
});
})();
+37 -7
View File
@@ -15,6 +15,7 @@
</main>
</div>
</div>
<script src="/static/settings-inbound.js" defer></script>
</body>
</html>
{{end}}
@@ -106,12 +107,10 @@
<div class="panel">
<div class="panel-body">
<p class="muted" style="margin-bottom:16px">Типы проверок, которые прогоняет <code>prober</code> на каждой
настроенной площадке для каждого проверяемого адреса — глобальный набор, общий для всех площадок. Отдельно от
списка площадок (<a href="/sites">/sites</a>), который решает, <em>сколько</em> площадок опрашивать, а не
<em>что</em> именно они проверяют. Пустой список портов и выключенный ICMP — штатный способ временно свести
inbound-проверки к нулю, не трогая список площадок.</p>
<form hx-put="/settings/inbound-checks" hx-target="#settings-form-wrap" hx-swap="innerHTML">
<h2 class="section-title" style="margin-top:0">Входящие проверки</h2>
<p class="muted" style="margin-bottom:16px">Эти настройки применяются ко всем <a href="/sites">площадкам</a> пробера.</p>
{{template "banner_inner" .InboundError}}
<form data-inbound-checks hx-put="/settings/inbound-checks" hx-target="#settings-form-wrap" hx-swap="innerHTML">
<div class="field-row">
<div class="field">
<label for="inbound_ports">TCP-порты (через запятую)</label>
@@ -120,8 +119,24 @@ inbound-проверки к нулю, не трогая список площа
<div class="field">
<label for="inbound_icmp"><input type="checkbox" id="inbound_icmp" name="icmp" {{if .Inbound.ICMP}}checked{{end}}> ICMP</label>
</div>
<button type="submit" class="btn btn-primary">Сохранить</button>
</div>
{{$tlsMode := .Inbound.TLSMode}}
<div class="field">
<label for="inbound_tls_mode">TLS-рукопожатие</label>
<select id="inbound_tls_mode" name="tls_mode">
<option value="auto" {{if eq $tlsMode "auto"}}selected{{end}}>Автоматически при наличии TCP-порта 443</option>
<option value="custom" {{if eq $tlsMode "custom"}}selected{{end}}>Указать порт и версию</option>
<option value="disabled" {{if eq $tlsMode "disabled"}}selected{{end}}>Отключить TLS</option>
</select>
</div>
<fieldset data-tls-fields {{if ne $tlsMode "custom"}}hidden disabled{{end}} style="border:0;padding:0">
<div data-tls-rows>
{{range .Inbound.TLSChecks}}{{template "inbound_tls_row" .}}{{end}}
</div>
<button type="button" class="btn" data-tls-add>Добавить TLS-проверку</button>
<template data-tls-row-template>{{template "inbound_tls_row"}}</template>
</fieldset>
<button type="submit" class="btn btn-primary">Сохранить</button>
</form>
</div>
</div>
@@ -145,3 +160,18 @@ inbound-проверки к нулю, не трогая список площа
</div>
</div>
{{end}}
{{define "inbound_tls_row"}}
<div class="field-row" data-tls-row>
<label class="field">Порт TLS
<input type="number" name="tls_port" min="1" max="65535" step="1" required {{with .}}value="{{.Port}}"{{end}}>
</label>
<label class="field">Версия TLS
<select name="tls_version">
<option value="1.2" {{with .}}{{if eq .Version "1.2"}}selected{{end}}{{end}}>TLS 1.2</option>
<option value="1.3" {{with .}}{{if eq .Version "1.3"}}selected{{end}}{{end}}>TLS 1.3</option>
</select>
</label>
<button type="button" class="btn" data-tls-remove>Удалить</button>
</div>
{{end}}
+15 -7
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"cloudipvalidator/internal/config"
"cloudipvalidator/internal/inbound"
)
// BootstrapFromConfig ensures the database's baseline state matches the
@@ -37,7 +38,7 @@ func (d *DB) BootstrapFromConfig(ctx context.Context, cfg *config.ControlAPI) er
if err := d.bootstrapSettings(ctx, cfg.Orchestrator.FIPSettleSeconds); err != nil {
return fmt.Errorf("bootstrap settings: %w", err)
}
if err := d.bootstrapInboundChecks(ctx, cfg.Inbound.Ports, cfg.Inbound.ICMP); err != nil {
if err := d.bootstrapInboundChecks(ctx, cfg.Inbound); err != nil {
return fmt.Errorf("bootstrap inbound checks: %w", err)
}
if err := d.SeedQueue(ctx, cfg.IPAddresses); err != nil {
@@ -125,7 +126,7 @@ func (d *DB) bootstrapSettings(ctx context.Context, fipSettleSeconds int) error
return err
}
func (d *DB) bootstrapInboundChecks(ctx context.Context, ports []int, icmp bool) error {
func (d *DB) bootstrapInboundChecks(ctx context.Context, settings config.InboundConfig) error {
var count int
if err := d.QueryRowContext(ctx, `SELECT COUNT(*) FROM inbound_checks_settings`).Scan(&count); err != nil {
return err
@@ -133,16 +134,23 @@ func (d *DB) bootstrapInboundChecks(ctx context.Context, ports []int, icmp bool)
if count > 0 {
return nil
}
if ports == nil {
ports = []int{}
if err := inbound.ValidateTLSChecks(settings.TLSChecks); err != nil {
return err
}
payload, err := json.Marshal(ports)
if settings.Ports == nil {
settings.Ports = []int{}
}
payload, err := json.Marshal(settings.Ports)
if err != nil {
return err
}
tlsChecks, err := json.Marshal(settings.TLSChecks)
if err != nil {
return err
}
now := timeToDB(Now())
_, err = d.ExecContext(ctx, `
INSERT INTO inbound_checks_settings (id, ports, icmp, created_at, updated_at) VALUES (1, ?, ?, ?, ?)
`, string(payload), icmp, now, now)
INSERT INTO inbound_checks_settings (id, ports, icmp, tls_checks, created_at, updated_at) VALUES (1, ?, ?, ?, ?, ?)
`, string(payload), settings.ICMP, string(tlsChecks), now, now)
return err
}
+4
View File
@@ -56,6 +56,9 @@ var dropChecksIndexSchema string
//go:embed migrations/0014_diagnostic_holds.sql
var diagnosticHoldsSchema string
//go:embed migrations/0015_inbound_tls_checks.sql
var inboundTLSChecksSchema string
// migrations is the ordered list of schema versions. Each entry's SQL is
// applied, in order, for any version greater than the database's current
// PRAGMA user_version — so a fresh database walks the whole list and an
@@ -78,6 +81,7 @@ var migrations = []struct {
{12, selfCheckFailuresSchema},
{13, dropChecksIndexSchema},
{14, diagnosticHoldsSchema},
{15, inboundTLSChecksSchema},
}
// connPragmas are applied to every new connection. A larger WAL checkpoint
@@ -0,0 +1 @@
ALTER TABLE inbound_checks_settings ADD COLUMN tls_checks TEXT NOT NULL DEFAULT 'null';
+4 -1
View File
@@ -3,6 +3,8 @@ package db
import (
"strings"
"time"
"cloudipvalidator/internal/inbound"
)
// Validator and IP lifecycle states. Kept as typed string constants rather
@@ -294,11 +296,12 @@ const (
)
// InboundChecksSettings is the singleton row describing what the prober
// checks on every site for every in-flight IP (TCP ports + optional ICMP).
// checks on every site for every in-flight IP.
// Admin-configurable at runtime (see queries_inbound.go).
type InboundChecksSettings struct {
Ports []int
ICMP bool
TLSChecks []inbound.TLSCheck
CreatedAt time.Time
UpdatedAt time.Time
}
+24 -12
View File
@@ -4,6 +4,8 @@ import (
"context"
"encoding/json"
"fmt"
"cloudipvalidator/internal/inbound"
)
// GetInboundChecks returns the singleton inbound-checks settings row.
@@ -12,10 +14,10 @@ import (
// normal condition.
func (d *DB) GetInboundChecks(ctx context.Context) (InboundChecksSettings, error) {
var s InboundChecksSettings
var portsJSON, createdAt, updatedAt string
var portsJSON, tlsJSON, createdAt, updatedAt string
err := d.QueryRowContext(ctx, `
SELECT ports, icmp, created_at, updated_at FROM inbound_checks_settings WHERE id=1
`).Scan(&portsJSON, &s.ICMP, &createdAt, &updatedAt)
SELECT ports, icmp, tls_checks, created_at, updated_at FROM inbound_checks_settings WHERE id=1
`).Scan(&portsJSON, &s.ICMP, &tlsJSON, &createdAt, &updatedAt)
if err != nil {
return InboundChecksSettings{}, err
}
@@ -25,6 +27,9 @@ func (d *DB) GetInboundChecks(ctx context.Context) (InboundChecksSettings, error
if s.Ports == nil {
s.Ports = []int{}
}
if err := json.Unmarshal([]byte(tlsJSON), &s.TLSChecks); err != nil {
return InboundChecksSettings{}, fmt.Errorf("decode inbound TLS checks: %w", err)
}
if s.CreatedAt, err = dbToTime(createdAt); err != nil {
return InboundChecksSettings{}, err
}
@@ -34,12 +39,9 @@ func (d *DB) GetInboundChecks(ctx context.Context) (InboundChecksSettings, error
return s, nil
}
// SetInboundChecks persists a new prober check configuration. Validation is
// purely local (port range, no duplicates) — unlike fip_settle_seconds,
// there's no cross-field dependency on other orchestrator config, so this
// is called directly by the HTTP handler without going through
// orchestrator.Orchestrator.
func (d *DB) SetInboundChecks(ctx context.Context, ports []int, icmp bool) error {
// SetInboundChecks preserves the TLS configuration when tlsChecks is nil.
// A pointer to a nil slice selects automatic mode.
func (d *DB) SetInboundChecks(ctx context.Context, ports []int, icmp bool, tlsChecks *[]inbound.TLSCheck) error {
seen := make(map[int]bool, len(ports))
for _, p := range ports {
if p < 1 || p > 65535 {
@@ -57,9 +59,19 @@ func (d *DB) SetInboundChecks(ctx context.Context, ports []int, icmp bool) error
if err != nil {
return err
}
now := timeToDB(Now())
var tlsJSON any
if tlsChecks != nil {
if err := inbound.ValidateTLSChecks(*tlsChecks); err != nil {
return fmt.Errorf("%v: %w", err, ErrValidation)
}
encoded, err := json.Marshal(*tlsChecks)
if err != nil {
return err
}
tlsJSON = string(encoded)
}
_, err = d.ExecContext(ctx, `
UPDATE inbound_checks_settings SET ports=?, icmp=?, updated_at=? WHERE id=1
`, string(payload), icmp, now)
UPDATE inbound_checks_settings SET ports=?, icmp=?, tls_checks=COALESCE(?, tls_checks), updated_at=? WHERE id=1
`, string(payload), icmp, tlsJSON, timeToDB(Now()))
return err
}
+4 -4
View File
@@ -45,7 +45,7 @@ func TestSetInboundChecksRejectsPortOutOfRange(t *testing.T) {
t.Fatalf("bootstrap: %v", err)
}
for _, p := range []int{0, -1, 65536, 70000} {
if err := d.SetInboundChecks(ctx, []int{p}, false); !errors.Is(err, ErrValidation) {
if err := d.SetInboundChecks(ctx, []int{p}, false, nil); !errors.Is(err, ErrValidation) {
t.Fatalf("port %d: expected ErrValidation, got %v", p, err)
}
}
@@ -56,7 +56,7 @@ func TestSetInboundChecksRejectsDuplicatePorts(t *testing.T) {
if err := d.BootstrapFromConfig(ctx, &config.ControlAPI{}); err != nil {
t.Fatalf("bootstrap: %v", err)
}
if err := d.SetInboundChecks(ctx, []int{22, 80, 22}, false); !errors.Is(err, ErrValidation) {
if err := d.SetInboundChecks(ctx, []int{22, 80, 22}, false, nil); !errors.Is(err, ErrValidation) {
t.Fatalf("expected ErrValidation for duplicate port, got %v", err)
}
}
@@ -74,7 +74,7 @@ func TestGetSetInboundChecksRoundTrip(t *testing.T) {
t.Fatalf("expected default {[] false}, got %+v", before)
}
if err := d.SetInboundChecks(ctx, []int{22, 443, 8080}, true); err != nil {
if err := d.SetInboundChecks(ctx, []int{22, 443, 8080}, true, nil); err != nil {
t.Fatalf("set inbound checks: %v", err)
}
after, err := d.GetInboundChecks(ctx)
@@ -90,7 +90,7 @@ func TestGetSetInboundChecksRoundTrip(t *testing.T) {
// Setting an empty port list + icmp:false is legal — it's the "disable
// all inbound checks without touching sites" configuration.
if err := d.SetInboundChecks(ctx, nil, false); err != nil {
if err := d.SetInboundChecks(ctx, nil, false, nil); err != nil {
t.Fatalf("set empty inbound checks: %v", err)
}
cleared, err := d.GetInboundChecks(ctx)
+1 -1
View File
@@ -391,7 +391,7 @@ func TestMigration0011BuildsRunsFromExistingData(t *testing.T) {
}
var ver int
d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver)
if ver != 14 {
if ver != 15 {
t.Errorf("user_version = %d", ver)
}
}
@@ -240,7 +240,7 @@ func TestMigration0010MarksRowsAfterVerdict(t *testing.T) {
t.Errorf("ssh: after_verdict=%d recorded=%s created=%s", a, rec, cr)
}
var ver int
if err := d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver); err != nil || ver != 14 {
if err := d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver); err != nil || ver != 15 {
t.Errorf("user_version=%d err=%v", ver, err)
}
}
+7 -4
View File
@@ -1,5 +1,7 @@
package httpapi
import "cloudipvalidator/internal/inbound"
// Request/response bodies for the /api/v1 surface. Kept in one file since
// they're small and mostly 1:1 with a single handler each.
@@ -86,10 +88,11 @@ type registerProberRequest struct {
}
type proberAssignment struct {
IPID int64 `json:"ip_id"`
IPAddress string `json:"ip_address"`
Ports []int `json:"ports"`
ICMP bool `json:"icmp"`
IPID int64 `json:"ip_id"`
IPAddress string `json:"ip_address"`
Ports []int `json:"ports"`
ICMP bool `json:"icmp"`
TLSChecks []inbound.TLSCheck `json:"tls_checks"`
}
type proberResultDTO struct {
+4 -5
View File
@@ -4,6 +4,7 @@ import (
"time"
"cloudipvalidator/internal/db"
"cloudipvalidator/internal/inbound"
)
// DTOs for the admin queue-management and dynamic-config endpoints
@@ -254,12 +255,10 @@ type putOrchestratorSettingsRequest struct {
SelfCheckMaxAttempts *int `json:"self_check_max_attempts"`
}
// inboundChecksDTO doubles as both the GET response and the PUT request
// body for /api/v1/admin/config/inbound-checks. Same field shape as
// proberAssignment.Ports/ICMP (dto.go).
type inboundChecksDTO struct {
Ports []int `json:"ports"`
ICMP bool `json:"icmp"`
Ports []int `json:"ports"`
ICMP bool `json:"icmp"`
TLSChecks []inbound.TLSCheck `json:"tls_checks"`
}
// autoCycleDTO is the status+parameters object returned by every
+19 -7
View File
@@ -1,11 +1,13 @@
package httpapi
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"cloudipvalidator/internal/db"
"cloudipvalidator/internal/inbound"
)
// --- validators ---
@@ -261,21 +263,31 @@ func (s *Server) handleConfigGetInboundChecks(w http.ResponseWriter, r *http.Req
writeDBError(w, err)
return
}
writeJSON(w, http.StatusOK, inboundChecksDTO{Ports: settings.Ports, ICMP: settings.ICMP})
writeJSON(w, http.StatusOK, inboundChecksDTO{Ports: settings.Ports, ICMP: settings.ICMP, TLSChecks: settings.TLSChecks})
}
// handleConfigPutInboundChecks writes directly to the DB (unlike the
// orchestrator-settings PUT above) because port-range/duplicate validation
// is purely local — no cross-field dependency on other orchestrator config.
func (s *Server) handleConfigPutInboundChecks(w http.ResponseWriter, r *http.Request) {
var req inboundChecksDTO
var req struct {
Ports []int `json:"ports"`
ICMP bool `json:"icmp"`
TLSChecks json.RawMessage `json:"tls_checks"`
}
if err := readJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
return
}
if err := s.DB.SetInboundChecks(r.Context(), req.Ports, req.ICMP); err != nil {
var tlsChecks *[]inbound.TLSCheck
if req.TLSChecks != nil {
var checks []inbound.TLSCheck
if err := json.Unmarshal(req.TLSChecks, &checks); err != nil {
writeError(w, http.StatusBadRequest, "invalid tls_checks: "+err.Error())
return
}
tlsChecks = &checks
}
if err := s.DB.SetInboundChecks(r.Context(), req.Ports, req.ICMP, tlsChecks); err != nil {
writeDBError(w, err)
return
}
writeJSON(w, http.StatusOK, inboundChecksDTO{Ports: req.Ports, ICMP: req.ICMP})
s.handleConfigGetInboundChecks(w, r)
}
+39 -1
View File
@@ -13,6 +13,7 @@ import (
"cloudipvalidator/internal/config"
"cloudipvalidator/internal/db"
"cloudipvalidator/internal/inbound"
"cloudipvalidator/internal/openstack"
"cloudipvalidator/internal/orchestrator"
)
@@ -623,7 +624,9 @@ func TestInboundChecksReflectedInProberAssignmentsWithoutRestart(t *testing.T) {
t.Fatalf("expected seeded {[22 80] true} before PUT, got %+v", assignments)
}
resp, body = fc.do(http.MethodPut, "/api/v1/admin/config/inbound-checks", inboundChecksDTO{Ports: []int{8080}, ICMP: false})
resp, body = fc.do(http.MethodPut, "/api/v1/admin/config/inbound-checks", inboundChecksDTO{
Ports: []int{8080}, TLSChecks: []inbound.TLSCheck{{Port: 8443, Version: "1.2"}, {Port: 9443, Version: "1.3"}},
})
if resp.StatusCode != http.StatusOK {
t.Fatalf("put inbound checks: status=%d body=%s", resp.StatusCode, body)
}
@@ -638,6 +641,41 @@ func TestInboundChecksReflectedInProberAssignmentsWithoutRestart(t *testing.T) {
if len(assignments) != 1 || len(assignments[0].Ports) != 1 || assignments[0].Ports[0] != 8080 || assignments[0].ICMP {
t.Fatalf("expected updated {[8080] false} without restart, got %+v", assignments)
}
if checks := assignments[0].TLSChecks; len(checks) != 2 ||
checks[0] != (inbound.TLSCheck{Port: 8443, Version: "1.2"}) ||
checks[1] != (inbound.TLSCheck{Port: 9443, Version: "1.3"}) {
t.Fatalf("unexpected TLS checks in assignment: %+v", checks)
}
}
func TestInboundTLSModesAndValidation(t *testing.T) {
fc, _, _, _ := newConfigTestHarness(t)
const path = "/api/v1/admin/config/inbound-checks"
for _, tc := range []struct {
input, wantTLS string
status int
}{
{`{"ports":[443],"tls_checks":[{"port":8443,"version":"1.2"}]}`, `[{"port":8443,"version":"1.2"}]`, http.StatusOK},
{`{"ports":[22]}`, `[{"port":8443,"version":"1.2"}]`, http.StatusOK},
{`{"ports":[443],"tls_checks":[{"port":0,"version":"1.2"}]}`, "", http.StatusBadRequest},
{`{"ports":[443],"tls_checks":[{"port":8443,"version":"1.1"}]}`, "", http.StatusBadRequest},
{`{"ports":[443],"tls_checks":[{"port":8443,"version":"1.2"},{"port":8443,"version":"1.3"}]}`, "", http.StatusBadRequest},
{`{"ports":[443],"tls_checks":[]}`, "[]", http.StatusOK},
{`{"ports":[443],"tls_checks":null}`, "null", http.StatusOK},
} {
resp, body := fc.do(http.MethodPut, path, json.RawMessage(tc.input))
if resp.StatusCode != tc.status {
t.Fatalf("%s: status=%d, body=%s", tc.input, resp.StatusCode, body)
}
if tc.status == http.StatusOK {
var got struct {
TLSChecks json.RawMessage `json:"tls_checks"`
}
if err := json.Unmarshal(body, &got); err != nil || string(got.TLSChecks) != tc.wantTLS {
t.Fatalf("%s: want tls_checks=%s, got %s (%v)", tc.input, tc.wantTLS, got.TLSChecks, err)
}
}
}
}
// TestProberRegisterSetsHostnameAndIdleState proves POST
+1 -1
View File
@@ -74,7 +74,7 @@ func (s *Server) handleProberAssignments(w http.ResponseWriter, r *http.Request)
for _, item := range items {
out = append(out, proberAssignment{
IPID: item.ID, IPAddress: item.IPAddress,
Ports: inbound.Ports, ICMP: inbound.ICMP,
Ports: inbound.Ports, ICMP: inbound.ICMP, TLSChecks: inbound.TLSChecks,
})
}
writeJSON(w, http.StatusOK, out)
+37
View File
@@ -0,0 +1,37 @@
package inbound
import (
"fmt"
"slices"
)
type TLSCheck struct {
Port int `json:"port" yaml:"port"`
Version string `json:"version" yaml:"version"`
}
func ValidateTLSChecks(checks []TLSCheck) error {
seen := make(map[int]bool, len(checks))
for _, check := range checks {
if check.Port < 1 || check.Port > 65535 {
return fmt.Errorf("TLS port %d is outside 1..65535", check.Port)
}
if check.Version != "1.2" && check.Version != "1.3" {
return fmt.Errorf("TLS port %d requires version 1.2 or 1.3", check.Port)
}
if seen[check.Port] {
return fmt.Errorf("duplicate TLS port %d", check.Port)
}
seen[check.Port] = true
}
return nil
}
// EffectiveTLSChecks resolves a nil (automatic mode) configuration.
// An explicitly empty slice disables TLS checks.
func EffectiveTLSChecks(ports []int, checks []TLSCheck) []TLSCheck {
if checks == nil && slices.Contains(ports, 443) {
return []TLSCheck{{Port: 443}}
}
return checks
}
+8 -7
View File
@@ -14,10 +14,13 @@ import (
"errors"
"fmt"
"log/slog"
"slices"
"strings"
"sync"
"time"
"cloudipvalidator/internal/inbound"
"cloudipvalidator/internal/config"
"cloudipvalidator/internal/db"
"cloudipvalidator/internal/openstack"
@@ -857,18 +860,16 @@ func (o *Orchestrator) expectedCheckCount(ctx context.Context) (int, error) {
if err != nil {
return 0, err
}
inbound, err := o.DB.GetInboundChecks(ctx)
settings, err := o.DB.GetInboundChecks(ctx)
if err != nil {
return 0, err
}
inboundPerSite := len(inbound.Ports)
if inbound.ICMP {
inboundPerSite := len(settings.Ports) + len(inbound.EffectiveTLSChecks(settings.Ports, settings.TLSChecks))
if settings.ICMP {
inboundPerSite++
}
for _, p := range inbound.Ports {
if p == 443 || p == 22 {
inboundPerSite++
}
if slices.Contains(settings.Ports, 22) {
inboundPerSite++
}
return egress + inboundPerSite*len(sites), nil
}
+3 -3
View File
@@ -703,7 +703,7 @@ func TestExpectedCheckCountReflectsInboundChecksConfigChange(t *testing.T) {
// Shrink the inbound check config to a single TCP port, no ICMP — an
// admin API change made between assignment and aggregation. Port 22
// still auto-triggers the extra "ssh" check (see expectedCheckCount).
if err := d.SetInboundChecks(ctx, []int{22}, false); err != nil {
if err := d.SetInboundChecks(ctx, []int{22}, false, nil); err != nil {
t.Fatalf("set inbound checks: %v", err)
}
@@ -812,7 +812,7 @@ func TestExpectedCheckCountIncludesTLSAndSSHForPorts443And22(t *testing.T) {
})
_ = o.MarkEgressComplete(ctx, ip.ID)
if err := d.SetInboundChecks(ctx, []int{22, 443}, false); err != nil {
if err := d.SetInboundChecks(ctx, []int{22, 443}, false, nil); err != nil {
t.Fatalf("set inbound checks: %v", err)
}
@@ -858,7 +858,7 @@ func TestAggregationWaitsForTLSAndSSHResults(t *testing.T) {
})
_ = o.MarkEgressComplete(ctx, ip.ID)
if err := d.SetInboundChecks(ctx, []int{22, 443}, false); err != nil {
if err := d.SetInboundChecks(ctx, []int{22, 443}, false, nil); err != nil {
t.Fatalf("set inbound checks: %v", err)
}
+13 -27
View File
@@ -1,7 +1,7 @@
// Package probercore implements a prober's poll loop: register once with
// its site identity, then each cycle fetch the set of IPs currently under
// test and run inbound reachability checks (TCP connect on each configured
// port, ICMP echo) directly against each one — this is the real,
// test and run inbound reachability checks (TCP, SSH, TLS and ICMP)
// directly against each one — this is the real,
// unmediated network test; only the control channel goes through the
// Control API.
package probercore
@@ -15,6 +15,7 @@ import (
"cloudipvalidator/internal/apiclient"
"cloudipvalidator/internal/checkrunner"
"cloudipvalidator/internal/config"
"cloudipvalidator/internal/inbound"
)
type Prober struct {
@@ -110,10 +111,11 @@ func (p *Prober) registerWithRetry(ctx context.Context) error {
}
type assignment struct {
IPID int64 `json:"ip_id"`
IPAddress string `json:"ip_address"`
Ports []int `json:"ports"`
ICMP bool `json:"icmp"`
IPID int64 `json:"ip_id"`
IPAddress string `json:"ip_address"`
Ports []int `json:"ports"`
ICMP bool `json:"icmp"`
TLSChecks []inbound.TLSCheck `json:"tls_checks"`
}
type resultDTO struct {
@@ -148,25 +150,6 @@ func (p *Prober) pollOnce(ctx context.Context) {
}
}
// extraChecksForPort returns checks to run in addition to the base
// TCPConnect for ports where a bare TCP handshake doesn't actually prove
// the expected service is behind it: a real TLS handshake on 443, a real
// SSH banner exchange on 22. nil for every other port.
func extraChecksForPort(host string, port int, timeout time.Duration) []func(ctx context.Context) checkrunner.Result {
switch port {
case 443:
return []func(ctx context.Context) checkrunner.Result{
checkrunner.TLSHandshake(host, port, timeout),
}
case 22:
return []func(ctx context.Context) checkrunner.Result{
checkrunner.SSHBanner(host, timeout),
}
default:
return nil
}
}
func (p *Prober) probeOne(ctx context.Context, a assignment) {
tcpTimeout := time.Duration(p.cfg.Checks.TCPTimeoutSeconds) * time.Second
icmpTimeout := time.Duration(p.cfg.Checks.ICMPTimeoutSeconds) * time.Second
@@ -182,10 +165,13 @@ func (p *Prober) probeOne(ctx context.Context, a assignment) {
for _, port := range a.Ports {
record(checkrunner.TCPConnect(a.IPAddress, port, tcpTimeout)(ctx))
for _, extra := range extraChecksForPort(a.IPAddress, port, tcpTimeout) {
record(extra(ctx))
if port == 22 {
record(checkrunner.SSHBanner(a.IPAddress, tcpTimeout)(ctx))
}
}
for _, check := range inbound.EffectiveTLSChecks(a.Ports, a.TLSChecks) {
record(checkrunner.TLSHandshake(a.IPAddress, check.Port, check.Version, tcpTimeout)(ctx))
}
if a.ICMP {
record(checkrunner.ICMPEcho(a.IPAddress, p.cfg.Checks.ICMPCount, icmpTimeout)(ctx))
}
+30 -27
View File
@@ -2,7 +2,10 @@ package probercore
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"os"
@@ -13,6 +16,7 @@ import (
"cloudipvalidator/internal/apiclient"
"cloudipvalidator/internal/config"
"cloudipvalidator/internal/inbound"
)
func testLogger() *slog.Logger {
@@ -176,36 +180,35 @@ func TestRegisterWithRetryStopsOnCancel(t *testing.T) {
}
}
// TestExtraChecksForPort confirms only ports 443 (TLS) and 22 (SSH) get an
// extra protocol check beyond the baseline TCPConnect every port gets.
func TestExtraChecksForPort(t *testing.T) {
// Use a host nothing is listening on so the extra check's own network
// call fails fast — only its CheckType is asserted here, the
// port->check mapping, not real connectivity.
closedHost := "127.0.0.1"
cases := []struct {
port int
wantLen int
wantCheckType string
}{
{port: 443, wantLen: 1, wantCheckType: "tls-443"},
{port: 22, wantLen: 1, wantCheckType: "ssh"},
{port: 80, wantLen: 0},
{port: 8080, wantLen: 0},
}
for _, tc := range cases {
extra := extraChecksForPort(closedHost, tc.port, 100*time.Millisecond)
if len(extra) != tc.wantLen {
t.Fatalf("port %d: expected %d extra checks, got %d", tc.port, tc.wantLen, len(extra))
// TestProbeReportsCustomTLS checks the result sent for a TLS-only port.
func TestProbeReportsCustomTLS(t *testing.T) {
target := httptest.NewTLSServer(nil)
defer target.Close()
port := target.Listener.Addr().(*net.TCPAddr).Port
results := make(chan []resultDTO, 1)
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
Results []resultDTO `json:"results"`
}
if tc.wantLen == 0 {
continue
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
res := extra[0](context.Background())
if res.CheckType != tc.wantCheckType {
t.Fatalf("port %d: expected check type %q, got %q", tc.port, tc.wantCheckType, res.CheckType)
results <- body.Results
w.WriteHeader(http.StatusNoContent)
}))
defer api.Close()
cfg := &config.Prober{SiteID: "site-1", ControlAPIURL: api.URL, Checks: config.ProberChecks{TCPTimeoutSeconds: 1}}
New(cfg, testLogger()).probeOne(context.Background(), assignment{
IPID: 1, IPAddress: "127.0.0.1", TLSChecks: []inbound.TLSCheck{{Port: port, Version: "1.2"}},
})
select {
case got := <-results:
if len(got) != 1 || got[0].CheckType != fmt.Sprintf("tls-%d", port) || !got[0].Success || !got[0].Complete {
t.Fatalf("unexpected TLS results: %+v", got)
}
default:
t.Fatal("prober sent no results")
}
}