* feat(observability): OpenTelemetry logs+traces with secret redaction Part of #265. Adds opt-in OpenTelemetry (logs + traces) alongside the existing stderr + opslog pipeline, plus secret redaction on all sinks. Default-off: with no OTEL_* / SILO_OTEL_ENABLED config, behavior is unchanged. Bootstrap (internal/telemetry): - Setup() builds one shared resource, a TracerProvider (parent-based trace-id ratio sampler), a LoggerProvider, and the W3C TraceContext+Baggage propagator from env. It installs NO MeterProvider — metrics stay on Prometheus, and the built-in no-op global MeterProvider keeps the trace instrumentation libs from double-emitting. Shutdown is deferred with a flush timeout. - Logs are bridged via otelslog fan-out (slog.MultiHandler), level-gated by the shared LevelVar and best-effort so a failing collector can't break the console or DB branches. stderr + opslog stay untouched. Secret redaction (internal/logredact): - A slog.Handler masks secret-keyed attributes (password, token, api_key, authorization, cookie, ...) — including .With-bound attrs, nested groups, secret-keyed group subtrees, and values behind a LogValuer — on the console and OTLP sinks, with a no-op fast path when a record has no secret keys. opslog.shouldRedact delegates to logredact.SecretKey so all sinks share one marker list. Rotation is infra-managed (no custom file sink): container runtime for stderr, collector/backend for OTLP, opslog partition-pruning for the DB. Documented in docs/architecture/observability.md. Verification: go build ./..., go vet, gofmt -l — clean; go test ./internal/telemetry/ ./internal/logredact/ -race pass. AI-use disclosure: implemented with AI assistance (Claude Code), including adversarial reviews that hardened the bootstrap and fixed two redaction leak paths; reviewed by the author. * refactor(observability): slog context+component sweep, sloglint gate (phase 3) Part of #265. Builds on the OTel bootstrap + redaction commit. Standardizes every log call site onto the context-carrying slog variants so records correlate with the active OpenTelemetry trace, and locks the standard in with a machine gate so future code (human- or AI-authored) can't drift back. - Call-site sweep: converted the remaining slog.<Level>(...) calls to the slog.<Level>Context(ctx, ...) form wherever a context.Context is in scope (background/init calls with no ctx are left as-is), across 183 files. Applied via a type-aware AST codemod. Log levels and message strings are preserved verbatim; a component attr (canonical per-package name) is added to direct package-level slog calls. Bound-logger calls keep their existing .With bindings. The main.go and telemetry package conversions rode with their file in the previous commit to keep each file within a single commit. - Enforcement (.golangci.yml): enable sloglint with context=scope, static-msg, key-naming-case=snake, no-mixed-args. After the sweep all four report zero violations repo-wide (tests included), so make lint / CI now blocks any regression to the non-context form. The gate ships with the sweep because it cannot be green until the legacy sites are converted. Metrics remain on Prometheus; no behavior change to /metrics or Grafana. Verification: go build ./..., go vet ./..., gofmt -l — clean; sloglint (all 4 rules) 0 violations repo-wide; log levels verified unchanged. AI-use disclosure: implemented with AI assistance (Claude Code), including the codemod; reviewed by the author. * fix(observability): honor per-signal OTLP protocol and secret WithGroup names Two Codex review findings on PR #290: - telemetry: OTEL_EXPORTER_OTLP_{TRACES,LOGS}_PROTOCOL now override the generic OTEL_EXPORTER_OTLP_PROTOCOL per signal, so mixed collector setups (e.g. HTTP logs + gRPC traces) build the right exporter. - logredact: entering a group whose name is secret-bearing (e.g. WithGroup("authorization")) now masks every leaf in that subtree, matching how slog.Group("authorization", ...) is masked as a whole. * fix(observability): address review feedback on telemetry bootstrap - Telemetry setup failure no longer kills boot: Setup returns usable no-op providers alongside the error and main logs and continues with telemetry disabled, honoring the best-effort contract. - Honor OTEL_TRACES_SAMPLER (always_on/off, traceidratio, parentbased_* variants); unsupported values fall back to parentbased_traceidratio. - Attach node identity as semconv service.instance.id instead of the non-semconv node.name. - Rename opslog retention-scope log attrs to target_component/target_level so they no longer collide with the canonical component routing key, and tag those lines with component=opslog. - Fix stale levelGated comment casing; use WarnContext in the telemetry shutdown defer; document the LogValuer double-resolve on the redaction slow path. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
237 lines
8.1 KiB
Go
237 lines
8.1 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
"sort"
|
|
|
|
"github.com/Silo-Server/silo-server/internal/cache"
|
|
"github.com/Silo-Server/silo-server/internal/markers"
|
|
)
|
|
|
|
// AdminMarkerProvidersHandler serves the per-provider marker config + key
|
|
// validation API under the RequireAdmin group.
|
|
type AdminMarkerProvidersHandler struct {
|
|
Registry *markers.Registry
|
|
Config *markers.ProviderConfigStore
|
|
EventBus cache.EventBus
|
|
logger *slog.Logger
|
|
}
|
|
|
|
// NewAdminMarkerProvidersHandler constructs the handler.
|
|
func NewAdminMarkerProvidersHandler(registry *markers.Registry, config *markers.ProviderConfigStore, eventBus cache.EventBus, logger *slog.Logger) *AdminMarkerProvidersHandler {
|
|
if logger == nil {
|
|
logger = slog.Default()
|
|
}
|
|
return &AdminMarkerProvidersHandler{Registry: registry, Config: config, EventBus: eventBus, logger: logger}
|
|
}
|
|
|
|
type providerConfigResponse struct {
|
|
Provider string `json:"provider"`
|
|
DisplayName string `json:"display_name,omitempty"`
|
|
SourceType string `json:"source_type,omitempty"`
|
|
PluginID string `json:"plugin_id,omitempty"`
|
|
PluginInstallationID int `json:"plugin_installation_id,omitempty"`
|
|
CapabilityID string `json:"capability_id,omitempty"`
|
|
IsSubmitter bool `json:"is_submitter"`
|
|
FetchEnabled bool `json:"fetch_enabled"`
|
|
FetchPriority int `json:"fetch_priority"`
|
|
ContributeEnabled bool `json:"contribute_enabled"`
|
|
ContributeAutoLocal bool `json:"contribute_auto_local"`
|
|
ContributeMinConfidence float64 `json:"contribute_min_confidence"`
|
|
}
|
|
|
|
type markerUserStatsResponse struct {
|
|
Total int `json:"total"`
|
|
Accepted int `json:"accepted"`
|
|
Pending int `json:"pending"`
|
|
Rejected int `json:"rejected"`
|
|
AcceptanceRate float64 `json:"acceptance_rate"`
|
|
CurrentStreak int `json:"current_streak"`
|
|
BestStreak int `json:"best_streak"`
|
|
}
|
|
|
|
func (h *AdminMarkerProvidersHandler) submitterIDs() map[string]bool {
|
|
out := map[string]bool{}
|
|
if h.Registry == nil {
|
|
return out
|
|
}
|
|
for _, p := range h.Registry.Providers() {
|
|
if _, ok := p.(markers.Submitter); ok {
|
|
out[p.ID()] = true
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (h *AdminMarkerProvidersHandler) providerDescriptions() map[string]markers.ProviderDescriptor {
|
|
out := map[string]markers.ProviderDescriptor{}
|
|
if h.Registry == nil {
|
|
return out
|
|
}
|
|
for _, p := range h.Registry.Providers() {
|
|
desc := markers.ProviderDescriptor{ID: p.ID()}
|
|
if described, ok := p.(markers.DescribedProvider); ok {
|
|
desc = described.ProviderDescription()
|
|
}
|
|
if desc.ID == "" {
|
|
desc.ID = p.ID()
|
|
}
|
|
out[p.ID()] = desc
|
|
}
|
|
return out
|
|
}
|
|
|
|
// HandleListProviders lists registered providers with their config + capability.
|
|
func (h *AdminMarkerProvidersHandler) HandleListProviders(w http.ResponseWriter, r *http.Request) {
|
|
if h == nil || h.Config == nil {
|
|
writeError(w, http.StatusServiceUnavailable, "unavailable", "Marker providers are not configured")
|
|
return
|
|
}
|
|
submitters := h.submitterIDs()
|
|
descriptions := h.providerDescriptions()
|
|
out := []providerConfigResponse{}
|
|
if h.Registry != nil {
|
|
for _, provider := range h.Registry.Providers() {
|
|
c, ok := h.Config.Get(provider.ID())
|
|
if !ok {
|
|
continue
|
|
}
|
|
out = append(out, toProviderConfigResponse(c, submitters[c.Provider], descriptions[c.Provider]))
|
|
}
|
|
} else {
|
|
for _, c := range h.Config.List() {
|
|
out = append(out, toProviderConfigResponse(c, submitters[c.Provider], descriptions[c.Provider]))
|
|
}
|
|
}
|
|
sort.Slice(out, func(i, j int) bool {
|
|
if out[i].FetchPriority != out[j].FetchPriority {
|
|
return out[i].FetchPriority < out[j].FetchPriority
|
|
}
|
|
return out[i].Provider < out[j].Provider
|
|
})
|
|
writeJSON(w, http.StatusOK, map[string]any{"providers": out})
|
|
}
|
|
|
|
// HandleUpdateProvider updates a provider's config row.
|
|
func (h *AdminMarkerProvidersHandler) HandleUpdateProvider(w http.ResponseWriter, r *http.Request) {
|
|
if h == nil || h.Config == nil {
|
|
writeError(w, http.StatusServiceUnavailable, "unavailable", "Marker providers are not configured")
|
|
return
|
|
}
|
|
provider, err := decodedURLParam(r, "provider")
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "Invalid provider ID")
|
|
return
|
|
}
|
|
existing, ok := h.Config.Get(provider)
|
|
if !ok {
|
|
writeError(w, http.StatusNotFound, "not_found", "Unknown marker provider")
|
|
return
|
|
}
|
|
var body struct {
|
|
FetchEnabled *bool `json:"fetch_enabled"`
|
|
FetchPriority *int `json:"fetch_priority"`
|
|
ContributeEnabled *bool `json:"contribute_enabled"`
|
|
ContributeAutoLocal *bool `json:"contribute_auto_local"`
|
|
ContributeMinConfidence *float64 `json:"contribute_min_confidence"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "Invalid request body")
|
|
return
|
|
}
|
|
if body.FetchEnabled != nil {
|
|
existing.FetchEnabled = *body.FetchEnabled
|
|
}
|
|
if body.FetchPriority != nil {
|
|
existing.FetchPriority = *body.FetchPriority
|
|
}
|
|
if body.ContributeEnabled != nil {
|
|
existing.ContributeEnabled = *body.ContributeEnabled
|
|
}
|
|
if body.ContributeAutoLocal != nil {
|
|
existing.ContributeAutoLocal = *body.ContributeAutoLocal
|
|
}
|
|
if body.ContributeMinConfidence != nil {
|
|
v := *body.ContributeMinConfidence
|
|
if v < 0 || v > 1 {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "contribute_min_confidence must be between 0 and 1")
|
|
return
|
|
}
|
|
existing.ContributeMinConfidence = v
|
|
}
|
|
if err := h.Config.Update(r.Context(), existing); err != nil {
|
|
h.logger.ErrorContext(r.Context(), "admin markers: update provider config failed", "provider", provider, "error", err)
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to update provider")
|
|
return
|
|
}
|
|
if h.EventBus != nil {
|
|
_ = h.EventBus.Publish(r.Context(), cache.ChannelAdmin, cache.Event{
|
|
Type: cache.EventMarkerProviderConfigChanged,
|
|
Payload: provider,
|
|
})
|
|
}
|
|
writeJSON(w, http.StatusOK, toProviderConfigResponse(existing, h.submitterIDs()[provider], h.providerDescriptions()[provider]))
|
|
}
|
|
|
|
// HandleValidateProvider validates the provider's configured key and returns stats.
|
|
func (h *AdminMarkerProvidersHandler) HandleValidateProvider(w http.ResponseWriter, r *http.Request) {
|
|
if h == nil || h.Registry == nil {
|
|
writeError(w, http.StatusServiceUnavailable, "unavailable", "Marker providers are not configured")
|
|
return
|
|
}
|
|
provider, err := decodedURLParam(r, "provider")
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "Invalid provider ID")
|
|
return
|
|
}
|
|
var submitter markers.Submitter
|
|
for _, p := range h.Registry.Providers() {
|
|
if p.ID() == provider {
|
|
if s, ok := p.(markers.Submitter); ok {
|
|
submitter = s
|
|
}
|
|
}
|
|
}
|
|
if submitter == nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "Provider does not support contribution")
|
|
return
|
|
}
|
|
stats, err := submitter.FetchUserStats(r.Context())
|
|
if err != nil {
|
|
writeJSON(w, http.StatusOK, map[string]any{"valid": false, "error": err.Error()})
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"valid": true, "stats": toMarkerUserStatsResponse(stats)})
|
|
}
|
|
|
|
func toProviderConfigResponse(c markers.ProviderConfig, isSubmitter bool, desc markers.ProviderDescriptor) providerConfigResponse {
|
|
return providerConfigResponse{
|
|
Provider: c.Provider,
|
|
DisplayName: desc.DisplayName,
|
|
SourceType: desc.SourceType,
|
|
PluginID: desc.PluginID,
|
|
PluginInstallationID: desc.PluginInstallationID,
|
|
CapabilityID: desc.CapabilityID,
|
|
IsSubmitter: isSubmitter,
|
|
FetchEnabled: c.FetchEnabled,
|
|
FetchPriority: c.FetchPriority,
|
|
ContributeEnabled: c.ContributeEnabled,
|
|
ContributeAutoLocal: c.ContributeAutoLocal,
|
|
ContributeMinConfidence: c.ContributeMinConfidence,
|
|
}
|
|
}
|
|
|
|
func toMarkerUserStatsResponse(s markers.UserStats) markerUserStatsResponse {
|
|
return markerUserStatsResponse{
|
|
Total: s.Total,
|
|
Accepted: s.Accepted,
|
|
Pending: s.Pending,
|
|
Rejected: s.Rejected,
|
|
AcceptanceRate: s.AcceptanceRate,
|
|
CurrentStreak: s.CurrentStreak,
|
|
BestStreak: s.BestStreak,
|
|
}
|
|
}
|