Files
silo-server/internal/plugins/service_connection.go
T
203a18ae83 feat(observability): OpenTelemetry logs+traces with secret redaction and slog standardization (#290)
* 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>
2026-07-09 08:53:52 -04:00

300 lines
7.0 KiB
Go

package plugins
import (
"context"
"errors"
"fmt"
"log/slog"
"sort"
"strings"
"time"
"google.golang.org/protobuf/types/known/structpb"
pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1"
"github.com/Silo-Server/silo-server/internal/pluginhost"
)
var ErrConnectionTestUnsupported = errors.New("plugin connection test unsupported")
type ConnectionTestError struct {
Message string
Cause error
}
func (e *ConnectionTestError) Error() string {
if e == nil {
return ""
}
return e.Message
}
func (e *ConnectionTestError) Unwrap() error {
if e == nil {
return nil
}
return e.Cause
}
var runPluginConnectionCheck = func(
ctx context.Context,
client pluginClient,
manifest *pluginv1.PluginManifest,
) error {
capabilityID, err := metadataProviderConnectionCheckCapabilityID(manifest)
if err != nil {
return err
}
capability := metadataProviderConnectionCheckCapability(manifest, capabilityID)
if !metadataProviderSupportsConnectionProbe(capability, "movie") {
slog.DebugContext(ctx,
"skipping metadata provider connection check for unsupported probe type", "component", "plugins",
"plugin_id", manifest.GetPluginId(),
"capability_id", capabilityID,
"item_type", "movie",
)
return nil
}
metadataClient, err := client.MetadataProvider(capabilityID)
if err != nil {
return &ConnectionTestError{
Message: fmt.Sprintf("Failed to initialize the metadata provider: %v", err),
Cause: err,
}
}
probeCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
if _, err := metadataClient.Search(probeCtx, &pluginv1.SearchMetadataRequest{
Query: "The Matrix",
ItemType: "movie",
Year: 1999,
Language: "en",
}); err != nil {
return &ConnectionTestError{
Message: fmt.Sprintf("Connection check failed: %v", err),
Cause: err,
}
}
return nil
}
func (s *Service) TestGlobalConfig(
ctx context.Context,
installationID int,
key string,
value map[string]any,
) error {
if strings.TrimSpace(key) == "" {
return &ConnectionTestError{Message: "Config key is required"}
}
if s.host == nil {
return fmt.Errorf("plugin host not configured")
}
installation, manifest, err := s.ensureInstallationCache(ctx, installationID, false)
if err != nil {
return err
}
if value == nil {
value = map[string]any{}
}
if err := ValidateGlobalConfigValue(manifest, key, value); err != nil {
return &ConnectionTestError{
Message: err.Error(),
Cause: err,
}
}
if _, err := metadataProviderConnectionCheckCapabilityID(manifest); err != nil {
return err
}
configEntries, err := s.mergedGlobalConfigEntries(ctx, installationID, key, value)
if err != nil {
return err
}
testInstallationID := -int(s.testConfigSeq.Add(1))
client, err := s.host.Start(ctx, pluginhost.StartRequest{
InstallationID: testInstallationID,
BinaryPath: installation.InstallPath,
Manifest: manifest,
Config: configEntries,
})
if err != nil {
return &ConnectionTestError{
Message: fmt.Sprintf("Failed to start the plugin with the test configuration: %v", err),
Cause: err,
}
}
defer func() {
if stopErr := s.host.Stop(testInstallationID); stopErr != nil && !errors.Is(stopErr, pluginhost.ErrClientNotFound) {
slog.WarnContext(ctx,
"stopping temporary plugin connection check instance failed", "component", "plugins",
"installation_id", installationID,
"test_installation_id", testInstallationID,
"error", stopErr,
)
}
}()
return runPluginConnectionCheck(ctx, client, manifest)
}
func (s *Service) mergedGlobalConfigEntries(
ctx context.Context,
installationID int,
key string,
value map[string]any,
) ([]*pluginv1.ConfigEntry, error) {
configsByKey := make(map[string]map[string]any)
if s.configs != nil {
configs, err := s.configs.ListGlobalConfigs(ctx, installationID)
if err != nil {
return nil, fmt.Errorf("list plugin runtime configs for installation %d: %w", installationID, err)
}
for _, config := range configs {
if config == nil {
continue
}
configsByKey[config.Key] = cloneConfigMap(config.Value)
}
}
configsByKey[key] = cloneConfigMap(value)
return configEntriesFromValues(configsByKey, installationID)
}
func configEntriesFromValues(
configsByKey map[string]map[string]any,
installationID int,
) ([]*pluginv1.ConfigEntry, error) {
if len(configsByKey) == 0 {
return nil, nil
}
keys := make([]string, 0, len(configsByKey))
for key := range configsByKey {
keys = append(keys, key)
}
sort.Strings(keys)
entries := make([]*pluginv1.ConfigEntry, 0, len(keys))
for _, key := range keys {
value := configsByKey[key]
if value == nil {
value = map[string]any{}
}
structValue, err := structpb.NewStruct(value)
if err != nil {
return nil, fmt.Errorf(
"encode runtime config %q for installation %d: %w",
key,
installationID,
err,
)
}
entries = append(entries, &pluginv1.ConfigEntry{
Key: key,
Value: structValue,
})
}
return entries, nil
}
func cloneConfigMap(value map[string]any) map[string]any {
if value == nil {
return map[string]any{}
}
cloned := make(map[string]any, len(value))
for key, entry := range value {
cloned[key] = entry
}
return cloned
}
func metadataProviderConnectionCheckCapabilityID(manifest *pluginv1.PluginManifest) (string, error) {
for _, capability := range manifest.GetCapabilities() {
if capability.GetType() != "metadata_provider.v1" {
continue
}
return capability.GetId(), nil
}
return "", &ConnectionTestError{
Message: "Connection checks are not supported for this plugin yet.",
Cause: ErrConnectionTestUnsupported,
}
}
func metadataProviderConnectionCheckCapability(
manifest *pluginv1.PluginManifest,
capabilityID string,
) *pluginv1.CapabilityDescriptor {
for _, capability := range manifest.GetCapabilities() {
if capability.GetType() == "metadata_provider.v1" && capability.GetId() == capabilityID {
return capability
}
}
return nil
}
func metadataProviderSupportsConnectionProbe(
capability *pluginv1.CapabilityDescriptor,
contentType string,
) bool {
priorities, ok := metadataProviderDefaultPriorities(capability)
if !ok {
return true
}
return priorities[contentType] > 0
}
func metadataProviderDefaultPriorities(
capability *pluginv1.CapabilityDescriptor,
) (map[string]float64, bool) {
if capability == nil || capability.GetMetadata() == nil {
return nil, false
}
metadataMap := capability.GetMetadata().AsMap()
raw, ok := metadataMap["default_priority"]
if !ok {
nested, nestedOK := metadataMap["metadata"].(map[string]any)
if !nestedOK {
return nil, false
}
raw, ok = nested["default_priority"]
if !ok {
return nil, false
}
}
rawMap, ok := raw.(map[string]any)
if !ok {
return nil, false
}
priorities := make(map[string]float64, len(rawMap))
for key, value := range rawMap {
switch v := value.(type) {
case float64:
priorities[key] = v
case int:
priorities[key] = float64(v)
case int32:
priorities[key] = float64(v)
case int64:
priorities[key] = float64(v)
}
}
return priorities, len(priorities) > 0
}