Documentation
¶
Overview ¶
Package shield360 provides OpenTelemetry-native observability for LLM applications in Go. It offers automatic instrumentation for popular LLM providers like OpenAI and Anthropic.
Index ¶
- Constants
- func CaptureLogs(level string) bool
- func Flags() *flags.Client
- func HTTPClient() *http.Client
- func Handler(h http.Handler, operation string) http.Handler
- func Init(cfg Config) error
- func IsInitialized() bool
- func LogHandler(name string) slog.Handler
- func MaskLogText(s string, max int) string
- func NewCodeLocationProcessor(cfg Config) sdktrace.SpanProcessor
- func NewLogHandler(opts LogHandlerOptions) slog.Handler
- func OpenDB(driverName, dataSourceName string) (*sql.DB, error)
- func ReportRuntimePackages(ctx context.Context, o RuntimePackagesOptions) (ok bool)
- func ResolveLogLevel(name string) otellog.Severity
- func RuntimePackagesActive() bool
- func RuntimePackagesEnabled(disabled bool, getenv func(string) string) bool
- func Shutdown(ctx context.Context) error
- func StartRuntimePackages(o RuntimePackagesOptions) bool
- func StopCapturingLogs()
- func StopRuntimePackages()
- func Transport(base http.RoundTripper) http.RoundTripper
- type Config
- type EvaluateRuleOptions
- type EvaluateRuleResult
- type LogHandlerOptions
- type ModelPricing
- type RuleEntity
- type RuleEntityType
- type RuntimePackagesOptions
Constants ¶
const ( // DefaultLogLevel is the lowest level sent when application logs are on. DefaultLogLevel = "info" // DefaultLoggerName is the instrumentation scope of records from LogHandler(""). DefaultLoggerName = "app" // DefaultLogsPerSecond is the most records a handler sends a second. DefaultLogsPerSecond = 500 )
const ( RuntimePackagesStartDelay = 15 * time.Second RuntimePackagesEvery = 24 * time.Hour )
Runtime package report timing.
const IngestPath = "/api/ingest/otlp"
IngestPath is the platform's authenticated OTLP ingest route.
const Version = "1.2.0"
Version is the current version of the Shield360 Go SDK.
This is the single source of truth. Releases go through the Release / Packages workflow, which tags this repository `sdk-go-<Version>`; the mirror sync then tags Shield360-AI/shield360-go `v<Version>`, which is the tag Go itself resolves, because a module's import path is its repository URL and this repository is private.
Variables ¶
This section is empty.
Functions ¶
func CaptureLogs ¶
CaptureLogs sends slog records at level ("info" by default) and above to Shield360: the handlers LogHandler returns start sending, and slog.Default (and with it the log package) also forwards, its output still going where it went before. Calling it again changes the level. Call it after Init; it returns false when Init has not set up a LoggerProvider.
func Flags ¶
Flags is the SDK's feature-flags client. It fetches the environment's flags from Config.Shield360URL with Config.Shield360APIKey (or SHIELD360_URL and SHIELD360_API_KEY) and evaluates them locally; flags scoped to an app are served only when their app is Config.ApplicationName. Polling starts on first use. It never panics: until rules arrive, or on any error, callers get their default.
if shield360.Flags().IsEnabled(ctx, "new-checkout", map[string]any{"key": userID}) { ... }
func HTTPClient ¶
HTTPClient is an http.Client whose requests are traced.
func Init ¶
Init initializes the Shield360 SDK with the provided configuration. This should be called once at application startup.
Example:
err := shield360.Init(shield360.Config{
OtlpEndpoint: "http://127.0.0.1:4318",
Environment: "production",
ApplicationName: "my-go-app",
})
if err != nil {
log.Fatalf("Failed to initialize Shield360: %v", err)
}
defer shield360.Shutdown(context.Background())
func IsInitialized ¶
func IsInitialized() bool
IsInitialized returns whether Shield360 has been initialized.
func LogHandler ¶
LogHandler returns a slog handler sending to Shield360 through the SDK's LoggerProvider under scope name ("app" when empty); see logHandler.
func MaskLogText ¶
MaskLogText is at most max characters of s, masked by the contract every SDK shares (sdk/rasp/README.md, "Masking") before it is cut: credential pairs, bearer credentials and opaque tokens are masked; readable identifiers such as class names and file paths survive.
func NewCodeLocationProcessor ¶
func NewCodeLocationProcessor(cfg Config) sdktrace.SpanProcessor
NewCodeLocationProcessor returns the span processor that records the application call site on GenAI spans, or nil when capture is disabled by Config.CaptureCodeLocation or SHIELD360_CAPTURE_CODE_LOCATION. Init registers it automatically; use it directly only with your own TracerProvider.
func NewLogHandler ¶
func NewLogHandler(opts LogHandlerOptions) slog.Handler
NewLogHandler returns a slog handler sending to Shield360 with these options.
func OpenDB ¶
OpenDB opens a database whose queries are traced (statement text, never the arguments), as sql.Open would.
func ReportRuntimePackages ¶
func ReportRuntimePackages(ctx context.Context, o RuntimePackagesOptions) (ok bool)
ReportRuntimePackages sends one report now and reports whether every batch was accepted. Never panics.
func ResolveLogLevel ¶
ResolveLogLevel turns a level name ("info", "WARN", "critical") into the lowest severity sent; empty or unknown names are INFO.
func RuntimePackagesActive ¶
func RuntimePackagesActive() bool
RuntimePackagesActive reports whether the report is running.
func RuntimePackagesEnabled ¶
RuntimePackagesEnabled reports whether the report runs: Disabled, or SHIELD360_RUNTIME_PACKAGES=off|false|0|no, turns it off.
func Shutdown ¶
Shutdown gracefully shuts down the Shield360 SDK. It should be called before application exit to ensure all telemetry data is flushed.
func StartRuntimePackages ¶
func StartRuntimePackages(o RuntimePackagesOptions) bool
StartRuntimePackages starts the report: once after StartDelay, then every Every. It returns whether it started; a second call while it runs, a missing URL or key, or a turned-off report start nothing. While it runs, runtime protection leaves its components report to it.
func StopCapturingLogs ¶
func StopCapturingLogs()
StopCapturingLogs stops sending application logs and puts slog.Default and the log package back as they were.
func StopRuntimePackages ¶
func StopRuntimePackages()
StopRuntimePackages stops the report (Shutdown, tests).
func Transport ¶
func Transport(base http.RoundTripper) http.RoundTripper
Transport traces each request base sends (http.DefaultTransport when nil), except calls to Shield360.
Types ¶
type Config ¶
type Config struct {
// OtlpEndpoint is the OTLP endpoint for sending traces, metrics and logs.
// Default: OTEL_EXPORTER_OTLP_ENDPOINT; else, with a Shield360 URL and API
// key, <Shield360URL>/api/ingest/otlp with the key as bearer; else
// "http://127.0.0.1:4318".
OtlpEndpoint string
// OtlpHeaders are additional headers to send with OTLP requests
OtlpHeaders map[string]string
// Environment identifies the deployment environment
// Default: "default"
Environment string
// ApplicationName is the name of your application
// Default: "default"
ApplicationName string
// SHIELD: Shield360URL is Shield360's base URL, for feature flags (Flags()) and
// Prompt Hub. Default: SHIELD360_URL.
Shield360URL string
// Shield360APIKey is the environment's API key for Shield360URL.
// Default: SHIELD360_API_KEY.
Shield360APIKey string
// TracerName is the name for the tracer provider
// Default: "shield360"
TracerName string
// ServiceVersion is the version of your service
ServiceVersion string
// DisableTracing disables trace collection
// Default: false
DisableTracing bool
// DisableMetrics disables metrics collection
// Default: false
DisableMetrics bool
// DisableBatch disables batch processing for exports
// Default: false
DisableBatch bool
// TraceExporterTimeout is the timeout for trace exports
// Default: 10 seconds
TraceExporterTimeout time.Duration
// MetricExporterTimeout is the timeout for metric exports
// Default: 10 seconds
MetricExporterTimeout time.Duration
// MetricExportInterval is the interval for metric exports
// Default: 30 seconds
MetricExportInterval time.Duration
// PricingInfo contains custom pricing information for models
PricingInfo map[string]ModelPricing
// PricingEndpoint is the endpoint to fetch pricing information
// Default: none; pricing is not fetched unless an endpoint is set
PricingEndpoint string
// DisablePricingFetch disables automatic pricing information fetching
DisablePricingFetch bool
// CaptureMessageContent records prompt/completion text as span attributes.
// Default: false — no content is captured unless asked for, here or with
// OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true (matching the
// Python and TypeScript SDKs). A Shield360 organisation stores content only
// when its Data retention setting allows it, whatever is sent.
CaptureMessageContent bool
// DisableCaptureMessageContent prevents prompt/completion text from being
// recorded, and wins over CaptureMessageContent and the environment.
// Kept for compatibility; content is off by default.
DisableCaptureMessageContent bool
// DetailedTracing enables detailed component-level tracing.
// Default: false
DetailedTracing bool
// IDGenerator overrides the default OTel ID generator. Use this when
// callers need deterministic trace/span IDs (e.g. the shield360 CLI's
// coding-agent hook deriving a stable TraceId from a session id so
// every span emitted across separate hook invocations lands in the
// same trace). When nil, OTel's random generator is used.
IDGenerator sdktrace.IDGenerator
// Sampler overrides the default head sampler. When nil, the SDK
// uses AlwaysSample — every span emitted reaches the collector.
// Callers wanting a head-sampling strategy (e.g. drop noisy
// `coding_agent.tool.requested` events) can pass a
// ParentBasedSampler or a custom span-name aware sampler here.
// See cli/internal/otlp/sampler.go for an example.
Sampler sdktrace.Sampler
// ExtraResourceAttributes are merged into the OTel Resource set on
// every span/metric this SDK emits. Callers use this to attach
// stable identity (e.g. `gen_ai.user.name`, `host.name`) once at
// startup rather than tagging each span individually.
ExtraResourceAttributes map[string]string
// CaptureCodeLocation records the application call site on GenAI spans
// as code.function.name, code.file.path and code.line.number. Nil means
// on unless SHIELD360_CAPTURE_CODE_LOCATION is false/0/no/off; a value
// set here wins over the environment.
CaptureCodeLocation *bool
// CaptureCallLocation also records the call site on the app's outbound
// calls: database, HTTP, RPC and messaging client (and producer) spans,
// so Shield360 can price the costly code patterns shield360 scan finds.
// Nil means on unless SHIELD360_CAPTURE_CALL_LOCATION is false/0/no/off;
// it has no effect when CaptureCodeLocation is off.
CaptureCallLocation *bool
// CodeRoot is stripped from code.file.path to make it repo-relative.
// Default: SHIELD360_CODE_ROOT, then the main module path (-trimpath
// builds) or the working directory.
CodeRoot string
// CodeLocationIgnoreModules lists extra module path prefixes whose
// frames are never reported as the call site (e.g. your own wrapper
// around the instrumented client).
CodeLocationIgnoreModules []string
// SHIELD: CaptureLogs sends the application's own log/slog records to
// Shield360 as OpenTelemetry logs, on the same endpoint and headers as
// traces (signal path /v1/logs). Nil means off unless
// SHIELD360_CAPTURE_LOGS is true/1/yes/on; a value set here wins. See
// LogHandler and CaptureLogs.
CaptureLogs *bool
// LogLevel is the lowest level sent when CaptureLogs is on: trace,
// debug, info, warn, error or fatal. Default: SHIELD360_LOG_LEVEL, then info.
LogLevel string
// SHIELD: Rasp turns on runtime application self-protection (the rasp
// package) unless Rasp.Disabled is set. Nil leaves it off unless
// SHIELD360_RASP=monitor|block; SHIELD360_RASP=off always wins. Events
// and the signed config use Shield360URL and Shield360APIKey.
Rasp *rasp.Options
// SHIELD: DisableRuntimePackages stops the runtime package report: the
// names and versions of the modules the binary was built with (never
// paths), sent to Shield360URL so it can match them against
// vulnerability data. On by default with a Shield360 URL and API key;
// SHIELD360_RUNTIME_PACKAGES=off also turns it off.
DisableRuntimePackages bool
}
Config holds the configuration for Shield360 SDK initialization
type EvaluateRuleOptions ¶
type EvaluateRuleOptions struct {
// URL is the Shield360 dashboard base URL.
// Falls back to SHIELD360_URL env var, then http://127.0.0.1:3000.
URL string
// APIKey is the Bearer token for authentication.
// Falls back to SHIELD360_API_KEY env var.
APIKey string
// EntityType specifies which kind of entities to match ("context", "prompt", or "evaluation").
EntityType RuleEntityType
// Fields are the trace attributes to evaluate against rules.
// Example: {"gen_ai.system": "openai", "gen_ai.request.model": "gpt-4"}
Fields map[string]interface{}
// IncludeEntityData requests full entity data in the response when true.
IncludeEntityData bool
// EntityInputs provides optional inputs for entity resolution (e.g. prompt variables).
EntityInputs map[string]interface{}
// Timeout for the HTTP request. Defaults to 30 seconds.
Timeout time.Duration
}
EvaluateRuleOptions holds parameters for the EvaluateRule call.
type EvaluateRuleResult ¶
type EvaluateRuleResult struct {
MatchingRuleIDs []string `json:"matchingRuleIds"`
Entities []RuleEntity `json:"entities"`
EntityData map[string]interface{} `json:"entity_data,omitempty"`
}
EvaluateRuleResult is the parsed response from the rule engine evaluate endpoint.
func EvaluateRule ¶
func EvaluateRule(ctx context.Context, opts EvaluateRuleOptions) (*EvaluateRuleResult, error)
EvaluateRule calls the Shield360 dashboard rule-engine evaluate endpoint. It sends the provided fields against configured rules and returns matching rule IDs, associated entities, and optionally the full entity data.
This function does NOT require shield360.Init() — it is a standalone HTTP call, consistent with get_prompt/get_secrets in the Python and TypeScript SDKs.
Example:
result, err := shield360.EvaluateRule(ctx, shield360.EvaluateRuleOptions{
EntityType: shield360.RuleEntityContext,
Fields: map[string]interface{}{
"gen_ai.system": "openai",
"gen_ai.request.model": "gpt-4",
"service.name": "my-app",
},
IncludeEntityData: true,
})
type LogHandlerOptions ¶
type LogHandlerOptions struct {
// Name is the instrumentation scope; "app" by default.
Name string
// LoggerProvider receives the records. Nil follows the SDK: records go
// through Init's LoggerProvider while application logs are on
// (Config.CaptureLogs, SHIELD360_CAPTURE_LOGS or CaptureLogs) and
// nowhere otherwise.
LoggerProvider otellog.LoggerProvider
// Level is the lowest level sent with an explicit LoggerProvider
// ("info" by default). With the SDK's provider the SDK's level applies.
Level string
// MaxPerSecond caps the records sent a second (default 500); the rest
// are dropped.
MaxPerSecond int
}
LogHandlerOptions configures NewLogHandler.
type ModelPricing ¶
ModelPricing represents pricing information for a model
type RuleEntity ¶
type RuleEntity struct {
RuleID string `json:"rule_id"`
EntityType string `json:"entity_type"`
EntityID string `json:"entity_id"`
}
RuleEntity represents a single matched rule-entity association.
type RuleEntityType ¶
type RuleEntityType string
RuleEntityType constrains the entity_type values accepted by the rule engine.
const ( // RuleEntityContext matches rules that return context entities. RuleEntityContext RuleEntityType = "context" // RuleEntityPrompt matches rules that return prompt entities. RuleEntityPrompt RuleEntityType = "prompt" // RuleEntityEvaluation matches rules that return evaluation entities. RuleEntityEvaluation RuleEntityType = "evaluation" )
type RuntimePackagesOptions ¶
type RuntimePackagesOptions struct {
URL string
APIKey string
ApplicationName string
Environment string
SDKVersion string
// Disabled turns the report off (Config.DisableRuntimePackages).
Disabled bool
// Getenv reads the environment (tests); default os.Getenv.
Getenv func(string) string
// StartDelay and Every override the timing (tests).
StartDelay time.Duration
Every time.Duration
// Collect lists the components (tests); default rasp.CollectComponents.
Collect func() []rasp.Component
HTTPClient *http.Client
RetryDelay time.Duration
}
RuntimePackagesOptions configure StartRuntimePackages.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package clienttype says who is calling, with the reasons, deterministic and explainable (docs/latest/shield360/client-type.mdx).
|
Package clienttype says who is calling, with the reasons, deterministic and explainable (docs/latest/shield360/client-type.mdx). |
|
Package defend is Shield360 Defend: decide in the app whether a request may go on.
|
Package defend is Shield360 Defend: decide in the app whether a request may go on. |
|
internal/crumb
Package crumb is Shield360's one crumb generator: stateless deception tokens (fake paths, credentials, headers, LLM tripwires, decoy files) derived from HMAC(environment secret, epoch, owner fingerprint) and verifiable on a hit with no storage.
|
Package crumb is Shield360's one crumb generator: stateless deception tokens (fake paths, credentials, headers, LLM tripwires, decoy files) derived from HMAC(environment secret, epoch, owner fingerprint) and verifiable on a hit with no storage. |
|
internal/injection
Package injection finds prompt injection in text an AI agent is about to read: a developer's prompt (direct injection), and tool results, files, fetched pages and tool descriptions (indirect injection and tool poisoning), plus the URL beacons attackers use to get data back out.
|
Package injection finds prompt injection in text an AI agent is about to read: a developer's prompt (direct injection), and tool results, files, fetched pages and tool descriptions (indirect injection and tool poisoning), plus the URL beacons attackers use to get data back out. |
|
Package flags is the Shield360 feature-flag engine and client for Go.
|
Package flags is the Shield360 feature-flag engine and client for Go. |
|
instrumentation
|
|
|
awstrace
Package awstrace traces AWS SDK for Go v2 (github.com/aws/aws-sdk-go-v2) calls inside the request trace.
|
Package awstrace traces AWS SDK for Go v2 (github.com/aws/aws-sdk-go-v2) calls inside the request trace. |
|
goredis
Package goredis traces go-redis (github.com/redis/go-redis/v9) commands inside the request trace, recorded by command name only.
|
Package goredis traces go-redis (github.com/redis/go-redis/v9) commands inside the request trace, recorded by command name only. |
|
grpctrace
Package grpctrace traces gRPC (google.golang.org/grpc) clients and servers with the OpenTelemetry stats handlers, health checks left out.
|
Package grpctrace traces gRPC (google.golang.org/grpc) clients and servers with the OpenTelemetry stats handlers, health checks left out. |
|
internal/spantest
Package spantest records spans for the instrumentation tests.
|
Package spantest records spans for the instrumentation tests. |
|
kafkago
Package kafkago traces segmentio/kafka-go producers and consumers and carries the trace across Kafka in message headers.
|
Package kafkago traces segmentio/kafka-go producers and consumers and carries the trace across Kafka in message headers. |
|
mongodb
Package mongodb traces MongoDB Go driver v2 (go.mongodb.org/mongo-driver/v2) commands inside the request trace.
|
Package mongodb traces MongoDB Go driver v2 (go.mongodb.org/mongo-driver/v2) commands inside the request trace. |
|
internal
|
|
|
guardevents
Package guardevents is the transport to Shield360's /api/guard/events: the endpoint guard reports, heartbeats and runtime-protection (RASP) events share.
|
Package guardevents is the transport to Shield360's /api/guard/events: the endpoint guard reports, heartbeats and runtime-protection (RASP) events share. |
|
masking
Package masking is the masking contract every Shield360 SDK shares (sdk/rasp/README.md, "Masking"), checked by sdk/rasp/testdata/masking.json: credential pairs, bearer credentials and opaque tokens are masked; readable identifiers (class names, package and file paths) survive; an attribute named like a credential is masked whole.
|
Package masking is the masking contract every Shield360 SDK shares (sdk/rasp/README.md, "Masking"), checked by sdk/rasp/testdata/masking.json: credential pairs, bearer credentials and opaque tokens are masked; readable identifiers (class names, package and file paths) survive; an attribute named like a credential is masked whole. |
|
Package rasp is Shield360 runtime application self-protection (RASP) for Go, opt-in.
|
Package rasp is Shield360 runtime application self-protection (RASP) for Go, opt-in. |
|
Package semconv provides semantic conventions for Gen AI observability.
|
Package semconv provides semantic conventions for Gen AI observability. |