Files
RustProxy/docker-agent/server.go
T
2026-11-28 17:36:53 +01:00

109 lines
3.4 KiB
Go

package main
import (
"crypto/subtle"
"encoding/json"
"io"
"net/http"
"strings"
"time"
)
func tokenOK(got, expected string) bool {
if expected == "" || len(got) != len(expected) {
return false
}
return subtle.ConstantTimeCompare([]byte(got), []byte(expected)) == 1
}
func requireToken(w http.ResponseWriter, r *http.Request, expected string) bool {
auth := strings.TrimSpace(r.Header.Get("Authorization"))
const prefix = "Bearer "
if strings.HasPrefix(auth, prefix) && tokenOK(strings.TrimSpace(strings.TrimPrefix(auth, prefix)), expected) {
return true
}
w.Header().Set("WWW-Authenticate", "Bearer")
http.Error(w, "unauthorized", http.StatusUnauthorized)
return false
}
func handler(cfg config) http.Handler {
mux := http.NewServeMux()
detector := &ipDetector{}
collector := newSystemCollector()
stats := newContainerCollector()
inventorySlots := make(chan struct{}, 2)
mux.HandleFunc("/v1/enroll", enrollHandler(cfg))
mux.HandleFunc("/v1/diagnostics", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if !requireToken(w, r, cfg.Token) {
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(agentDiagnostics())
})
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
if cfg.Fingerprint != "" {
w.Header().Set("X-RustProxy-Agent-Certificate-SHA256", cfg.Fingerprint)
}
_, _ = io.WriteString(w, `{"status":"ok"}`)
})
mux.HandleFunc("/v1/inventory", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if !requireToken(w, r, cfg.Token) {
return
}
select {
case inventorySlots <- struct{}{}:
defer func() { <-inventorySlots }()
default:
w.Header().Set("Retry-After", "1")
http.Error(w, "inventory busy", http.StatusServiceUnavailable)
return
}
containers, err := dockerContainers(r.Context(), cfg.DockerSock)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
addresses, primaryIP, primarySource := detectedAddresses(r.Context(), cfg, detector)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
if cfg.Fingerprint != "" {
w.Header().Set("X-RustProxy-Agent-Certificate-SHA256", cfg.Fingerprint)
}
result := inventory{
AgentVersion: version, Hostname: cfg.Hostname, PublicIP: primaryIP, PublicIPSource: primarySource, CertificateSHA256: cfg.Fingerprint,
Addresses: addresses, ObservedAt: time.Now().UTC().Format(time.RFC3339), Services: servicesFrom(containers),
}
extended := r.URL.Query().Get("system") == "1"
if extended && !cfg.DisableSystemInfo {
result.System = collector.collect(r.Context(), cfg.DockerSock)
stats.enrich(r.Context(), cfg.DockerSock, result.Services)
}
if !extended || cfg.DisableSystemInfo {
for i := range result.Services {
if !extended {
result.Services[i].Labels = nil
}
result.Services[i].Container = nil
}
}
_ = json.NewEncoder(w).Encode(result)
})
return mux
}