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

+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}}