This commit is contained in:
Meghdad committed 2026-07-12 23:06:00 +03:30
commit eb115daf3b
76 files changed
+22739

No files matched your search

+197
View File
@@ -0,0 +1,197 @@
package health
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
type EndpointRepository interface {
ListEndpoints(context.Context) ([]domain.ObservedEndpoint, error)
SaveEndpoint(context.Context, domain.ObservedEndpoint) error
SaveHealthIssues(context.Context, string, []domain.HealthIssue) error
}
type EndpointProber interface {
Probe(context.Context, domain.ObservedEndpoint) (domain.ObservedEndpoint, error)
}
// ExpectedFingerprint returns the locally managed fingerprint expected on an
// endpoint. An empty string means no comparison is configured.
type ExpectedFingerprint func(context.Context, domain.ObservedEndpoint) (string, error)
type Checker struct {
Repository EndpointRepository
Prober EndpointProber
ExpectedFingerprint ExpectedFingerprint
Concurrency int
Interval time.Duration
Now func() time.Time
OnError func(error)
}
// RunOnce checks enabled endpoints with bounded concurrency. Individual probe
// failures become persisted endpoint issues and do not cancel other checks.
func (c *Checker) RunOnce(ctx context.Context) error {
if c == nil || c.Repository == nil {
return errors.New("health checker repository is required")
}
if c.Prober == nil {
return errors.New("health checker prober is required")
}
endpoints, err := c.Repository.ListEndpoints(ctx)
if err != nil {
return fmt.Errorf("list observed endpoints: %w", err)
}
concurrency := c.Concurrency
if concurrency <= 0 {
concurrency = 4
}
now := time.Now
if c.Now != nil {
now = c.Now
}
jobs := make(chan domain.ObservedEndpoint)
errs := make(chan error, len(endpoints)*3)
var workers sync.WaitGroup
for range concurrency {
workers.Add(1)
go func() {
defer workers.Done()
for endpoint := range jobs {
if ctx.Err() != nil {
return
}
observed, probeErr := c.Prober.Probe(ctx, endpoint)
if saveErr := c.Repository.SaveEndpoint(ctx, observed); saveErr != nil {
errs <- fmt.Errorf("save endpoint %s: %w", endpoint.ID, saveErr)
}
expected := ""
if c.ExpectedFingerprint != nil {
value, fingerprintErr := c.ExpectedFingerprint(ctx, observed)
if fingerprintErr != nil {
errs <- fmt.Errorf("expected fingerprint for %s: %w", endpoint.ID, fingerprintErr)
} else {
expected = value
}
}
issues := IssuesForObservation(observed, expected, probeErr, now().UTC())
if saveErr := c.Repository.SaveHealthIssues(ctx, endpoint.ID, issues); saveErr != nil {
errs <- fmt.Errorf("save endpoint issues %s: %w", endpoint.ID, saveErr)
}
}
}()
}
send:
for _, endpoint := range endpoints {
if !endpoint.Enabled {
continue
}
select {
case jobs <- endpoint:
case <-ctx.Done():
break send
}
}
close(jobs)
workers.Wait()
close(errs)
var combined []error
for workerErr := range errs {
combined = append(combined, workerErr)
}
if ctx.Err() != nil {
combined = append(combined, ctx.Err())
}
return errors.Join(combined...)
}
// Run checks immediately and then on every interval until cancellation.
// Transient cycle failures are reported but monitoring continues.
func (c *Checker) Run(ctx context.Context) error {
if c == nil {
return errors.New("health checker is nil")
}
interval := c.Interval
if interval <= 0 {
interval = 15 * time.Minute
}
report := func(err error) {
if err != nil && c.OnError != nil {
c.OnError(err)
}
}
report(c.RunOnce(ctx))
if ctx.Err() != nil {
return ctx.Err()
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
report(c.RunOnce(ctx))
}
}
}
func IssuesForObservation(endpoint domain.ObservedEndpoint, expectedFingerprint string, probeErr error, now time.Time) []domain.HealthIssue {
var issues []domain.HealthIssue
add := func(severity domain.Severity, kind, title, detail, action string) {
issues = append(issues, domain.HealthIssue{
ID: issueID(endpoint.ID, kind),
Severity: severity,
Kind: kind,
ResourceID: endpoint.ID,
Title: title,
Detail: detail,
Action: action,
ObservedAt: now.UTC(),
})
}
if probeErr != nil {
add(domain.SeverityCritical, "tls_probe_failed", "TLS endpoint is unreachable", probeErr.Error(), "Check DNS, firewall, port, and server TLS configuration")
return issues
}
if endpoint.NotAfter != nil && !endpoint.NotAfter.After(now) {
add(domain.SeverityCritical, "served_certificate_expired", "Served certificate is expired", "The public endpoint serves a certificate that expired at "+endpoint.NotAfter.UTC().Format(time.RFC3339), "Deploy a valid certificate immediately")
}
if !endpoint.ValidForHost {
add(domain.SeverityCritical, "served_certificate_wrong_host", "Served certificate does not cover the hostname", "The certificate SANs do not validate "+endpoint.Host, "Deploy a certificate containing this hostname")
}
if !endpoint.Trusted {
add(domain.SeverityWarning, "served_certificate_untrusted", "Served certificate chain is not publicly trusted", "The endpoint did not present a chain trusted by the configured root store", "Install the complete public certificate chain")
}
lowerExpected := strings.ToLower(expectedFingerprint)
revocationPending := strings.HasPrefix(lowerExpected, "revocation-pending:")
revokedFingerprint := strings.HasPrefix(lowerExpected, "revoked:")
expectedFingerprint = strings.TrimPrefix(lowerExpected, "revocation-pending:")
expectedFingerprint = strings.TrimPrefix(expectedFingerprint, "revoked:")
expectedFingerprint = strings.ReplaceAll(expectedFingerprint, ":", "")
observedFingerprint := strings.ToLower(strings.ReplaceAll(endpoint.FingerprintSHA256, ":", ""))
if revocationPending {
add(domain.SeverityWarning, "certificate_revocation_pending", "Certificate revocation status is unresolved", "A revocation request was recorded but its final CA result has not been reconciled locally", "Retry the revocation with the original reason before renewing or deploying this lineage")
} else if revokedFingerprint && expectedFingerprint != "" && expectedFingerprint == observedFingerprint {
add(domain.SeverityCritical, "served_certificate_revoked", "Endpoint still serves a revoked certificate", "The observed certificate was revoked by its issuing CA", "Deploy a new certificate immediately")
} else if !revokedFingerprint && expectedFingerprint != "" && observedFingerprint != "" && expectedFingerprint != observedFingerprint {
add(domain.SeverityWarning, "served_certificate_stale", "Endpoint serves a different certificate", "The observed fingerprint differs from the current locally managed certificate", "Deploy the current certificate and recheck")
}
return issues
}
func issueID(resourceID, kind string) string {
digest := sha256.Sum256([]byte(resourceID + "\x00" + kind))
return "issue_" + hex.EncodeToString(digest[:12])
}
+139
View File
@@ -0,0 +1,139 @@
package health
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
func TestIssuesForObservation(t *testing.T) {
now := time.Date(2026, 7, 11, 12, 0, 0, 0, time.UTC)
expired := now.Add(-time.Hour)
endpoint := domain.ObservedEndpoint{
ID: "endpoint", Host: "app.example.com", Port: 443,
FingerprintSHA256: "bbbb", NotAfter: &expired, ValidForHost: false, Trusted: false,
}
issues := IssuesForObservation(endpoint, "aaaa", nil, now)
want := map[string]bool{
"served_certificate_expired": false,
"served_certificate_wrong_host": false,
"served_certificate_untrusted": false,
"served_certificate_stale": false,
}
for _, issue := range issues {
if _, ok := want[issue.Kind]; ok {
want[issue.Kind] = true
}
if issue.ID == "" || issue.ResourceID != endpoint.ID || !issue.ObservedAt.Equal(now) {
t.Fatalf("invalid issue: %#v", issue)
}
}
for kind, found := range want {
if !found {
t.Errorf("missing issue %s in %#v", kind, issues)
}
}
revokedIssues := IssuesForObservation(domain.ObservedEndpoint{ID: "revoked-endpoint", Host: "example.com", FingerprintSHA256: "abcd", ValidForHost: true, Trusted: true}, "revoked:abcd", nil, now)
if len(revokedIssues) != 1 || revokedIssues[0].Kind != "served_certificate_revoked" || revokedIssues[0].Severity != domain.SeverityCritical {
t.Fatalf("revoked certificate issues = %#v", revokedIssues)
}
replacementIssues := IssuesForObservation(domain.ObservedEndpoint{ID: "replacement-endpoint", Host: "example.com", FingerprintSHA256: "ef01", ValidForHost: true, Trusted: true}, "revoked:abcd", nil, now)
for _, issue := range replacementIssues {
if issue.Kind == "served_certificate_stale" || issue.Kind == "served_certificate_revoked" {
t.Fatalf("replacement for revoked certificate was flagged against the revoked fingerprint: %#v", replacementIssues)
}
}
pendingIssues := IssuesForObservation(domain.ObservedEndpoint{ID: "pending-endpoint", Host: "example.com", FingerprintSHA256: "abcd", ValidForHost: true, Trusted: true}, "revocation-pending:abcd", nil, now)
if len(pendingIssues) != 1 || pendingIssues[0].Kind != "certificate_revocation_pending" {
t.Fatalf("pending revocation issues = %#v", pendingIssues)
}
failed := IssuesForObservation(endpoint, "", errors.New("connection refused"), now)
if len(failed) != 1 || failed[0].Kind != "tls_probe_failed" || failed[0].Severity != domain.SeverityCritical {
t.Fatalf("probe failure issues = %#v", failed)
}
}
func TestCheckerUsesBoundedConcurrencyAndPersistsEveryEndpoint(t *testing.T) {
var endpoints []domain.ObservedEndpoint
for i := 0; i < 20; i++ {
endpoints = append(endpoints, domain.ObservedEndpoint{ID: string(rune('a' + i)), ZoneID: "zone", Host: "example.com", Port: 443, Enabled: true})
}
repository := &checkerRepository{endpoints: endpoints}
prober := &boundedProber{}
checker := &Checker{Repository: repository, Prober: prober, Concurrency: 3, Now: func() time.Time { return time.Unix(100, 0).UTC() }}
if err := checker.RunOnce(context.Background()); err != nil {
t.Fatal(err)
}
if maximum := prober.maximum.Load(); maximum > 3 {
t.Fatalf("maximum concurrency = %d", maximum)
}
if got := repository.savedCount(); got != len(endpoints) {
t.Fatalf("saved endpoints = %d, want %d", got, len(endpoints))
}
}
type checkerRepository struct {
mu sync.Mutex
endpoints []domain.ObservedEndpoint
saved []domain.ObservedEndpoint
issues map[string][]domain.HealthIssue
}
func (r *checkerRepository) ListEndpoints(context.Context) ([]domain.ObservedEndpoint, error) {
return append([]domain.ObservedEndpoint(nil), r.endpoints...), nil
}
func (r *checkerRepository) SaveEndpoint(_ context.Context, endpoint domain.ObservedEndpoint) error {
r.mu.Lock()
defer r.mu.Unlock()
r.saved = append(r.saved, endpoint)
return nil
}
func (r *checkerRepository) SaveHealthIssues(_ context.Context, owner string, issues []domain.HealthIssue) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.issues == nil {
r.issues = make(map[string][]domain.HealthIssue)
}
r.issues[owner] = append([]domain.HealthIssue(nil), issues...)
return nil
}
func (r *checkerRepository) savedCount() int {
r.mu.Lock()
defer r.mu.Unlock()
return len(r.saved)
}
type boundedProber struct {
active atomic.Int32
maximum atomic.Int32
}
func (p *boundedProber) Probe(ctx context.Context, endpoint domain.ObservedEndpoint) (domain.ObservedEndpoint, error) {
active := p.active.Add(1)
for {
maximum := p.maximum.Load()
if active <= maximum || p.maximum.CompareAndSwap(maximum, active) {
break
}
}
defer p.active.Add(-1)
select {
case <-time.After(10 * time.Millisecond):
case <-ctx.Done():
return endpoint, ctx.Err()
}
now := time.Now().UTC()
future := now.Add(time.Hour)
endpoint.LastCheckedAt = &now
endpoint.NotAfter = &future
endpoint.ValidForHost = true
endpoint.Trusted = true
return endpoint, nil
}
+178
View File
@@ -0,0 +1,178 @@
// Package health performs cancellable public DNS and TLS observations without
// coupling network activity to TUI rendering.
package health
import (
"context"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"errors"
"fmt"
"net"
"slices"
"strconv"
"strings"
"time"
"crypto/tls"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
type Resolver interface {
LookupIPAddr(context.Context, string) ([]net.IPAddr, error)
}
type Dialer interface {
DialContext(context.Context, string, string) (net.Conn, error)
}
type Prober struct {
Resolver Resolver
Dialer Dialer
RootCAs *x509.CertPool
Timeout time.Duration
Now func() time.Time
}
func NewProber() *Prober {
return &Prober{
Resolver: net.DefaultResolver,
Dialer: &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second},
Timeout: 15 * time.Second,
Now: time.Now,
}
}
// Probe resolves the endpoint, tries each address, and performs a TLS handshake
// with SNI. Verification is manual so certificate identity, trust, and expiry
// metadata are still available when validation fails.
func (p *Prober) Probe(ctx context.Context, endpoint domain.ObservedEndpoint) (domain.ObservedEndpoint, error) {
result := endpoint
result.ResolvedAddresses = nil
result.FingerprintSHA256 = ""
result.Issuer = ""
result.NotAfter = nil
result.ValidForHost = false
result.Trusted = false
result.LastError = ""
now := time.Now
if p != nil && p.Now != nil {
now = p.Now
}
checkedAt := now().UTC()
result.LastCheckedAt = &checkedAt
if strings.TrimSpace(endpoint.Host) == "" {
err := errors.New("endpoint host is empty")
result.LastError = err.Error()
return result, err
}
port := endpoint.Port
if port == 0 {
port = 443
result.Port = port
}
if port < 1 || port > 65535 {
err := fmt.Errorf("endpoint port %d is outside 1..65535", port)
result.LastError = err.Error()
return result, err
}
resolver := Resolver(net.DefaultResolver)
if p != nil && p.Resolver != nil {
resolver = p.Resolver
}
lookup, err := resolver.LookupIPAddr(ctx, endpoint.Host)
if err != nil {
err = fmt.Errorf("resolve %s: %w", endpoint.Host, err)
result.LastError = err.Error()
return result, err
}
for _, address := range lookup {
if address.IP != nil {
result.ResolvedAddresses = append(result.ResolvedAddresses, address.IP.String())
}
}
slices.Sort(result.ResolvedAddresses)
result.ResolvedAddresses = slices.Compact(result.ResolvedAddresses)
if len(result.ResolvedAddresses) == 0 {
err = fmt.Errorf("resolve %s: no IP addresses returned", endpoint.Host)
result.LastError = err.Error()
return result, err
}
timeout := 15 * time.Second
if p != nil && p.Timeout > 0 {
timeout = p.Timeout
}
probeCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
dialer := Dialer(&net.Dialer{Timeout: timeout})
if p != nil && p.Dialer != nil {
dialer = p.Dialer
}
var attempts []error
for _, address := range result.ResolvedAddresses {
raw, dialErr := dialer.DialContext(probeCtx, "tcp", net.JoinHostPort(address, strconv.Itoa(port)))
if dialErr != nil {
attempts = append(attempts, fmt.Errorf("%s: %w", address, dialErr))
continue
}
connection := tls.Client(raw, &tls.Config{
ServerName: endpoint.Host,
InsecureSkipVerify: true, // Verification is performed independently below.
MinVersion: tls.VersionTLS12,
})
handshakeErr := connection.HandshakeContext(probeCtx)
if handshakeErr != nil {
_ = raw.Close()
attempts = append(attempts, fmt.Errorf("%s TLS handshake: %w", address, handshakeErr))
continue
}
state := connection.ConnectionState()
_ = connection.Close()
if len(state.PeerCertificates) == 0 {
attempts = append(attempts, fmt.Errorf("%s TLS handshake returned no peer certificate", address))
continue
}
observeCertificate(&result, endpoint.Host, state.PeerCertificates, p.rootCAs(), checkedAt)
return result, nil
}
err = fmt.Errorf("connect to %s:%d: %w", endpoint.Host, port, errors.Join(attempts...))
result.LastError = err.Error()
return result, err
}
func (p *Prober) rootCAs() *x509.CertPool {
if p == nil {
return nil
}
return p.RootCAs
}
func observeCertificate(result *domain.ObservedEndpoint, host string, peers []*x509.Certificate, roots *x509.CertPool, now time.Time) {
leaf := peers[0]
digest := sha256.Sum256(leaf.Raw)
result.FingerprintSHA256 = hex.EncodeToString(digest[:])
result.Issuer = leaf.Issuer.String()
notAfter := leaf.NotAfter.UTC()
result.NotAfter = &notAfter
result.ValidForHost = leaf.VerifyHostname(host) == nil
intermediates := x509.NewCertPool()
for _, certificate := range peers[1:] {
intermediates.AddCert(certificate)
}
options := x509.VerifyOptions{
Roots: roots,
Intermediates: intermediates,
CurrentTime: now,
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
_, trustErr := leaf.Verify(options)
result.Trusted = trustErr == nil
}