trusera

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 12, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

README

trusera-sdk-go

Go SDK for monitoring AI agents with Trusera's Cedar-based policy engine.

Go Reference Go Report Card License

Features

  • Zero Dependencies: Uses only Go standard library
  • HTTP Interception: Transparently wraps http.Client to monitor all outbound requests
  • Policy Enforcement: Three modes (log, warn, block) for handling policy violations
  • Event Tracking: Records tool calls, LLM invocations, API calls, file writes, and more
  • Thread-Safe: Concurrent request handling with proper synchronization
  • Background Flushing: Automatic batching and periodic event submission

Installation

go get github.com/Trusera/trusera-sdk-go

Quickstart

package main

import (
    "fmt"
    "net/http"

    "github.com/Trusera/trusera-sdk-go"
)

func main() {
    // Create Trusera client
    client := trusera.NewClient("your-api-key")
    defer client.Close()

    // Register your agent
    agentID, err := client.RegisterAgent("my-agent", "custom")
    if err != nil {
        panic(err)
    }
    fmt.Println("Agent registered:", agentID)

    // Track an event
    event := trusera.NewEvent(trusera.EventToolCall, "web_search").
        WithPayload("query", "AI security best practices").
        WithPayload("results_count", 10)

    client.Track(event)
}

HTTP Interception

The SDK can wrap Go's http.Client to automatically intercept and record all outbound HTTP requests:

package main

import (
    "net/http"
    "github.com/Trusera/trusera-sdk-go"
)

func main() {
    // Create Trusera client
    truseraClient := trusera.NewClient("your-api-key",
        trusera.WithAgentID("agent-123"))
    defer truseraClient.Close()

    // Wrap HTTP client with interception
    httpClient := trusera.WrapHTTPClient(&http.Client{}, truseraClient, trusera.InterceptorOptions{
        Enforcement: trusera.ModeBlock,
        BlockPatterns: []string{"malicious.com", "blocked-api.io"},
        ExcludePatterns: []string{"api.trusera.io"}, // Don't intercept Trusera API calls
    })

    // All requests are now monitored and enforced
    resp, err := httpClient.Get("https://api.example.com/data")
    if err != nil {
        // Request may be blocked by policy
        panic(err)
    }
    defer resp.Body.Close()
}
Convenience Helper

For quick setup with registration and interception:

truseraClient, httpClient, err := trusera.MustRegisterAndIntercept(
    "your-api-key",
    "my-agent",
    "langchain",
    trusera.InterceptorOptions{
        Enforcement: trusera.ModeWarn,
    },
)
if err != nil {
    panic(err)
}
defer truseraClient.Close()

// Use httpClient for all requests
resp, _ := httpClient.Get("https://api.openai.com/v1/chat/completions")

Enforcement Modes

The SDK supports three enforcement modes for handling policy violations:

Log Mode (Default)

Records all requests silently without blocking:

opts := trusera.InterceptorOptions{
    Enforcement: trusera.ModeLog,
    BlockPatterns: []string{"restricted.com"}, // Recorded but allowed
}
Warn Mode

Logs warnings for blocked patterns but allows requests to proceed:

opts := trusera.InterceptorOptions{
    Enforcement: trusera.ModeWarn,
    BlockPatterns: []string{"suspicious.com"},
}
// Request proceeds, warning recorded in Trusera
Block Mode

Rejects requests matching block patterns with HTTP 403:

opts := trusera.InterceptorOptions{
    Enforcement: trusera.ModeBlock,
    BlockPatterns: []string{"malicious.com"},
}
// Request returns error, backend never called

Event Types

The SDK supports tracking various agent actions:

// Tool calls
event := trusera.NewEvent(trusera.EventToolCall, "calculator").
    WithPayload("operation", "multiply").
    WithPayload("args", []int{5, 7})

// LLM invocations
event := trusera.NewEvent(trusera.EventLLMInvoke, "gpt-4").
    WithPayload("prompt_tokens", 150).
    WithPayload("completion_tokens", 75)

// Data access
event := trusera.NewEvent(trusera.EventDataAccess, "database_query").
    WithPayload("query", "SELECT * FROM users").
    WithPayload("rows_returned", 42)

// File writes
event := trusera.NewEvent(trusera.EventFileWrite, "save_report").
    WithPayload("path", "/tmp/report.pdf").
    WithPayload("size_bytes", 1024)

// API calls (auto-tracked by interceptor)
event := trusera.NewEvent(trusera.EventAPICall, "POST https://api.stripe.com/v1/charges")

// Decisions
event := trusera.NewEvent(trusera.EventDecision, "approve_transaction").
    WithPayload("confidence", 0.95).
    WithPayload("reasoning", "All fraud checks passed")

Configuration Options

Client Options
client := trusera.NewClient("api-key",
    trusera.WithBaseURL("https://custom.trusera.io"),
    trusera.WithAgentID("agent-123"),
    trusera.WithFlushInterval(60*time.Second),
    trusera.WithBatchSize(200),
)
Interceptor Options
opts := trusera.InterceptorOptions{
    Enforcement: trusera.ModeBlock,

    // URLs matching these patterns won't be intercepted
    ExcludePatterns: []string{
        "api.trusera.io",
        "localhost",
        "127.0.0.1",
    },

    // URLs matching these patterns trigger policy enforcement
    BlockPatterns: []string{
        "malicious.com",
        "blocked-api.io",
        "/internal/admin",
    },
}

Intercept Global Default Client

To intercept all HTTP requests using http.DefaultClient:

truseraClient := trusera.NewClient("api-key")
defer truseraClient.Close()

// Wrap the default client
trusera.InterceptDefault(truseraClient, trusera.InterceptorOptions{
    Enforcement: trusera.ModeLog,
})

// Now all http.Get, http.Post, etc. are intercepted
resp, _ := http.Get("https://api.example.com")

Warning: This affects all code using http.DefaultClient globally.

Manual Flushing

Events are automatically flushed based on batch size and interval, but you can force a flush:

client := trusera.NewClient("api-key")

// Track events
client.Track(event1)
client.Track(event2)

// Force immediate send
if err := client.Flush(); err != nil {
    log.Printf("Failed to flush events: %v", err)
}

Thread Safety

The SDK is safe for concurrent use. Multiple goroutines can call Track() simultaneously:

client := trusera.NewClient("api-key")
defer client.Close()

var wg sync.WaitGroup
for i := 0; i < 100; i++ {
    wg.Add(1)
    go func(id int) {
        defer wg.Done()
        event := trusera.NewEvent(trusera.EventToolCall, fmt.Sprintf("tool-%d", id))
        client.Track(event)
    }(i)
}
wg.Wait()

Testing

Run the test suite:

go test -v ./...

Run with race detection:

go test -race ./...

Examples

See the examples directory for complete working examples:

  • Basic tracking
  • HTTP interception with different enforcement modes
  • Integration with popular frameworks

Contributing

Contributions welcome! Please read our Contributing Guide.

License

Apache 2.0 - See LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateInterceptedClient

func CreateInterceptedClient(truseraClient *Client, opts InterceptorOptions) *http.Client

CreateInterceptedClient creates a new http.Client with Trusera interception

func InterceptDefault

func InterceptDefault(truseraClient *Client, opts InterceptorOptions)

InterceptDefault wraps http.DefaultClient with Trusera interception

func WrapHTTPClient

func WrapHTTPClient(client *http.Client, truseraClient *Client, opts InterceptorOptions) *http.Client

WrapHTTPClient wraps an http.Client to intercept all outbound requests

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client sends agent events to Trusera API

func MustRegisterAndIntercept

func MustRegisterAndIntercept(apiKey, agentName, framework string, opts InterceptorOptions) (*Client, *http.Client, error)

MustRegisterAndIntercept is a convenience function that registers an agent and returns an intercepted client

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient creates a Trusera monitoring client

func (*Client) Close

func (c *Client) Close() error

Close flushes remaining events and stops background goroutine

func (*Client) Flush

func (c *Client) Flush() error

Flush sends all queued events to the API

func (*Client) RegisterAgent

func (c *Client) RegisterAgent(name, framework string) (string, error)

RegisterAgent registers an agent with Trusera, returns agent ID

func (*Client) Track

func (c *Client) Track(event Event)

Track queues an event for sending

type EnforcementMode

type EnforcementMode string

EnforcementMode determines how policy violations are handled

const (
	ModeLog   EnforcementMode = "log"   // Record but allow all requests
	ModeWarn  EnforcementMode = "warn"  // Log warnings for blocked patterns but allow
	ModeBlock EnforcementMode = "block" // Reject blocked requests with error
)

type Event

type Event struct {
	ID        string         `json:"id"`
	Type      EventType      `json:"type"`
	Name      string         `json:"name"`
	Payload   map[string]any `json:"payload"`
	Metadata  map[string]any `json:"metadata,omitempty"`
	Timestamp string         `json:"timestamp"`
}

Event represents an agent action tracked by Trusera

func NewEvent

func NewEvent(eventType EventType, name string) Event

NewEvent creates a new event with generated ID and timestamp

func (Event) WithMetadata

func (e Event) WithMetadata(key string, value any) Event

WithMetadata adds metadata to the event (builder pattern)

func (Event) WithPayload

func (e Event) WithPayload(key string, value any) Event

WithPayload adds payload data to the event (builder pattern)

type EventType

type EventType string

EventType defines the type of agent event

const (
	EventToolCall   EventType = "tool_call"
	EventLLMInvoke  EventType = "llm_invoke"
	EventDataAccess EventType = "data_access"
	EventAPICall    EventType = "api_call"
	EventFileWrite  EventType = "file_write"
	EventDecision   EventType = "decision"
)

type InterceptorOptions

type InterceptorOptions struct {
	Enforcement     EnforcementMode
	ExcludePatterns []string // URL patterns to skip interception
	BlockPatterns   []string // URL patterns to block (for testing enforcement)
}

InterceptorOptions configures the HTTP interceptor

type Option

type Option func(*Client)

Option configures a Client

func WithAgentID

func WithAgentID(id string) Option

WithAgentID sets the agent identifier

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL sets the Trusera API base URL

func WithBatchSize

func WithBatchSize(n int) Option

WithBatchSize sets the max events before auto-flush

func WithFlushInterval

func WithFlushInterval(d time.Duration) Option

WithFlushInterval sets how often to auto-flush events

Directories

Path Synopsis
examples
basic command
block-mode command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL