analyzer

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package analyzer defines the contract every security analyzer implements.

The contract is deliberately narrow: an analyzer is handed a target and a read-mostly context, and must return a result that states what it managed to do. There is no way to signal success by omission.

Index

Constants

This section is empty.

Variables

View Source
var Default = NewRegistry()

Default is the process-wide registry

View Source
var ErrConnectionClosed = errors.New("connection closed before the request was answered")

ErrConnectionClosed marks a request whose peer exited or disconnected before answering. A rejection is an answer and must not wrap this error. Implementations must wrap it with %w so callers can use errors.Is.

View Source
var ErrDialOptionUnsupported = errors.New("dialer does not support this session option")

ErrDialOptionUnsupported reports that a Dialer cannot open the session shape a caller asked for. Callers treat it as "this check could not run" rather than as "this check passed".

View Source
var ErrSessionRejected = errors.New("session id rejected by target")

ErrSessionRejected marks a protocol-level rejection of a session id: the target affirmatively told the caller the id it presented is not valid (for example the MCP "session not found" response to an unrecognized or terminated session), as opposed to the connection failing before any answer came back at all. Implementations must wrap it with %w so callers can use errors.Is.

Functions

func Get

func Get[T any](a *Artifacts, key string) (T, bool)

Get is the typed accessor. It returns the zero value when the artifact is absent or has a different type.

func Register

func Register(a Analyzer)

Register adds an analyzer to the default registry

func ToolCallAllowed

func ToolCallAllowed(probes ProbeLevel, allowedToolCalls []string, name string) bool

ToolCallAllowed is the rule behind AnalysisContext.ToolCallAllowed, exported so a session built outside an AnalysisContext (internal/mcp/client dials sessions from its own Options, not from one) can enforce the same allowlist rather than trusting a caller's own check

Types

type AnalysisContext

type AnalysisContext struct {
	// Log is scoped to the running analyzer
	Log *slog.Logger

	// Root is the filesystem boundary for the scan. Analyzers must not read
	// outside it.
	Root string

	// Snapshot is the discovered MCP surface. Nil for source-only scans
	Snapshot *model.Snapshot

	// Session gives protocol-level analyzers access to the live connection.
	// Nil for offline scans.
	Session Session

	// Dialer opens additional sessions. Auth and session checks need to
	// reconnect with different credentials. Nil for offline scans.
	Dialer Dialer

	// AllowPrivateNetworks mirrors the scan's --allow-private-networks setting for an analyzer
	// that opens its own outbound connection rather than going through Session or Dialer
	AllowPrivateNetworks bool

	// Probes is the active-probe policy for this scan
	Probes ProbeLevel

	// AllowedToolCalls lists the tools that may actually be invoked. Empty
	// means none, regardless of Probes.
	AllowedToolCalls []string

	// Runtime executes payloads in a sandbox. Nil when runtime confirmation
	// is not enabled or not available.
	Runtime RuntimeExecutor

	// LLM is the optional semantic-analysis backend
	LLM LLMClient

	// Options holds per-analyzer settings, keyed by analyzer name. Shared
	// across concurrently running analyzers and read-only to all of them;
	// read it through Option rather than reaching into the map.
	Options map[string]map[string]any

	// Artifacts is the hand-off between analyzers, for example the source
	// graph produced by the inventory pass and consumed by taint analysis
	Artifacts *Artifacts
}

AnalysisContext carries shared scan state. Each analyzer receives a shallow copy, so Options, Session, Artifacts, and Snapshot still point at values used concurrently by other analyzers. Treat them as read-only; only Artifacts may be mutated because it provides its own locking. Writing Options or mutating Snapshot is a data race, not a compile-time error.

func (*AnalysisContext) Option

func (ac *AnalysisContext) Option(analyzer, key string) (any, bool)

Option returns a setting for the named analyzer

func (*AnalysisContext) ToolCallAllowed

func (ac *AnalysisContext) ToolCallAllowed(name string) bool

ToolCallAllowed reports whether invoking the named tool is permitted

type Analyzer

type Analyzer interface {
	// Name is the stable identifier used in results, config and policy
	Name() string

	// Analyze runs the check. It must honour ctx cancellation and must always
	// return a result with a non-empty Status.
	Analyze(ctx context.Context, target model.Target, ac *AnalysisContext) model.AnalyzerResult
}

Analyzer inspects a target and reports findings.

Implementations must not panic; the scanner recovers panics and turns them into an ERROR result, but a panic loses the coverage accounting.

func Applicables

func Applicables(as []Analyzer, kind model.TargetKind) (run, skip []Analyzer)

Applicables separates analyzers that support kind from those that do not

type Applicable

type Applicable interface {
	AppliesTo(kind model.TargetKind) bool
}

Applicable is implemented by analyzers that only make sense for some target kinds. An analyzer that does not implement it runs for every target.

type Artifacts

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

Artifacts is a concurrency-safe hand-off between analyzers

func NewArtifacts

func NewArtifacts() *Artifacts

func (*Artifacts) Get

func (a *Artifacts) Get(key string) (any, bool)

func (*Artifacts) Set

func (a *Artifacts) Set(key string, v any)

type Canary

type Canary struct {
	ID    string
	Path  string // where it is planted in the sandbox
	Env   string // environment variable name, if planted as one
	Value string // the synthetic value to watch for
	Kind  string // aws_key | ssh_key | api_token | db_password | file

	// Content is the full file body to plant at Path, when it differs from
	// Value - an AWS credentials file or a netrc entry carries the secret
	// wrapped in the format a real parser expects, not the bare secret. A
	// canary with no Content plants Value itself, unchanged.
	Content string
}

Canary is a planted fake secret. Values are always synthetic

type Describer

type Describer interface {
	Describe() Description
}

Describer lets an analyzer document itself for `mcp-scanner analyzers`

type Description

type Description struct {
	Name        string                `json:"name"`
	Purpose     string                `json:"purpose"`
	Threats     []string              `json:"threats,omitempty"`
	Evidence    []model.EvidenceLevel `json:"evidence_levels,omitempty"`
	Active      bool                  `json:"active"` // true if it sends anything the target can observe as a probe
	Limitations []string              `json:"limitations,omitempty"`
	// RequiresNetwork, RequiresDocker and RequiresCredentials let the CLI
	// explain why an analyzer is unavailable instead of silently skipping it
	RequiresNetwork     bool `json:"requires_network,omitempty"`
	RequiresDocker      bool `json:"requires_docker,omitempty"`
	RequiresCredentials bool `json:"requires_credentials,omitempty"`
}

Description is the self-documentation every analyzer should provide: what it detects, how strong its evidence is, and where it is blind

type DialOptions

type DialOptions struct {
	// ResumeSessionID sends this id on every request and skips the
	// handshake, the way a client reconnecting to a session it already
	// holds does. It is what asks "does this server honour an id it should
	// not" - a foreign, closed or malformed one - rather than "what does
	// this server do when initialize carries a strange header".
	ResumeSessionID string

	// ProposeSessionID sends this id as Mcp-Session-Id on the handshake
	// itself and on no later request, so the answer says whether the server
	// adopts an id the client chose instead of minting its own
	ProposeSessionID string
}

DialOptions carries the two off-spec connection shapes the session checks need. At most one may be set, and the dialer must express it on the wire rather than as a test-only convention.

type Dialer

type Dialer interface {
	Dial(ctx context.Context, target model.Target) (Session, error)
}

Dialer opens new sessions to a target. Auth and session-security checks need to connect several times with different credentials.

type LLMClient

type LLMClient interface {
	Name() string
	Model() string
	Capabilities() ModelCapabilities
	Complete(ctx context.Context, req LLMRequest) (LLMResponse, error)
}

LLMClient is the semantic-analysis backend.

The content handed to it is untrusted, so implementations must not expose tools, filesystem access or MCP access to the model.

type LLMRequest

type LLMRequest struct {
	System      string
	User        string
	Schema      json.RawMessage
	MaxTokens   int
	Temperature *float64
}

LLMRequest is a single completion. Schema, when set and supported, asks for structured output.

type LLMResponse

type LLMResponse struct {
	Text         string
	InputTokens  int
	OutputTokens int
	Truncated    bool
}

LLMResponse is a completion result

type ModelCapabilities

type ModelCapabilities struct {
	SupportsTemperature bool
	SupportsJSONSchema  bool
	SupportsJSONMode    bool
	SupportsSeed        bool
	SupportsSystemRole  bool
	MaxInputTokens      int
}

ModelCapabilities describes what parameters a model actually accepts, so an adapter never sends a field the endpoint will reject

type Observation

type Observation struct {
	Kind     string         `json:"kind"` // process_exec | file_read | file_write | net_connect | dns_query | canary_hit
	Detail   string         `json:"detail"`
	CanaryID string         `json:"canary_id,omitempty"`
	Data     map[string]any `json:"data,omitempty"`
}

Observation is one thing the sandbox saw the target do

type ProbeLevel

type ProbeLevel string

ProbeLevel controls how much the scanner is allowed to poke at a live target

const (
	// ProbeNone: connect and read declarations only
	ProbeNone ProbeLevel = "none"
	// ProbeSafe: additionally send malformed or unsupported protocol messages
	// that a correct server must reject without side effects
	ProbeSafe ProbeLevel = "safe"
	// ProbeToolCalls: additionally invoke explicitly allowlisted tools
	ProbeToolCalls ProbeLevel = "tool-calls"
)

func (ProbeLevel) AtLeast

func (p ProbeLevel) AtLeast(want ProbeLevel) bool

AtLeast reports whether the configured level permits the requested level

func (ProbeLevel) Valid

func (p ProbeLevel) Valid() bool

type ProtocolError

type ProtocolError struct {
	Code    int64           `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

ProtocolError is a JSON-RPC error returned by the peer. Analyzers inspect the code to tell "correctly rejected" from "crashed".

func (*ProtocolError) Error

func (e *ProtocolError) Error() string

type Registry

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

Registry holds analyzers registered by imported packages in this build

func NewRegistry

func NewRegistry() *Registry

func (*Registry) All

func (r *Registry) All() []Analyzer

All returns registered analyzers in name order

func (*Registry) Get

func (r *Registry) Get(name string) (Analyzer, bool)

func (*Registry) Names

func (r *Registry) Names() []string

Names lists registered analyzers in name order

func (*Registry) Register

func (r *Registry) Register(a Analyzer)

Register adds an analyzer. Empty or duplicate names panic because they are initialization errors that would make results ambiguous.

func (*Registry) Select

func (r *Registry) Select(names []string, kind model.TargetKind) ([]Analyzer, error)

Select resolves the requested analyzer names for a target kind.

Unknown names are errors so CI cannot silently omit a requested analyzer.

type ResourceContent

type ResourceContent struct {
	URI      string `json:"uri"`
	MIMEType string `json:"mime_type,omitempty"`
	Text     string `json:"text,omitempty"`
	Blob     []byte `json:"-"`
}

ResourceContent is the payload of resources/read

type RuntimeExecutor

type RuntimeExecutor interface {
	// Available reports whether a sandbox backend is usable right now
	Available(ctx context.Context) error
	Execute(ctx context.Context, req RuntimeRequest) RuntimeResult
}

RuntimeExecutor runs a target inside a sandbox and reports what it did. Analyzers use it to turn a static suspicion into a confirmed finding.

type RuntimeRequest

type RuntimeRequest struct {
	Target model.Target

	// Tool and Arguments invoke a specific MCP capability inside the sandbox
	Tool      string
	Arguments map[string]any

	Timeout time.Duration

	// Canaries are the fake secrets and files planted in the sandbox. Reading
	// or exfiltrating one is the signal.
	Canaries []Canary
}

RuntimeRequest describes one sandboxed execution

type RuntimeResult

type RuntimeResult struct {
	Started  bool
	ExitCode int
	TimedOut bool
	Stdout   string
	Stderr   string

	// Answered reports a JSON-RPC result or error for tools/call on stdout. An initialization
	// reply alone does not count.
	Answered bool

	Observations []Observation

	// Err is set when the sandbox itself failed, which is different from the
	// sandboxed process failing
	Err error
}

RuntimeResult is what the sandbox observed

func (RuntimeResult) Hit

func (r RuntimeResult) Hit(kind string) bool

Hit reports whether any observation of the given kind was recorded

type Session

type Session interface {
	// Snapshot returns the discovery snapshot for this session
	Snapshot() *model.Snapshot

	// Call sends a raw JSON-RPC request. Protocol analyzers use it for probes
	// the SDK would refuse to build, such as unknown methods or malformed
	// parameters. It returns the raw result, or a ProtocolError for a
	// well-formed JSON-RPC error response.
	Call(ctx context.Context, method string, params any) (json.RawMessage, error)

	// CallTool invokes a tool. Callers must check AnalysisContext.ToolCallAllowed
	// first; implementations also enforce the allowlist and return
	// ErrToolCallNotAllowed otherwise.
	CallTool(ctx context.Context, name string, args map[string]any) (*ToolCallResult, error)

	// ReadResource fetches a resource by URI
	ReadResource(ctx context.Context, uri string) (*ResourceContent, error)

	// SessionID is the transport session identifier, when the transport has one
	SessionID() string

	Close() error
}

Session is a live MCP connection, reduced to what analyzers need. It exists so an analyzer can be tested against a fake without linking the transport implementation.

type SessionDialer

type SessionDialer interface {
	Dialer
	DialWithOptions(ctx context.Context, target model.Target, opts DialOptions) (Session, error)
}

SessionDialer is a Dialer that can also open the session shapes in DialOptions. A Dialer that cannot honour a set option must return ErrDialOptionUnsupported rather than quietly dialing without it: a probe that reports on a connection it did not actually make is worse than one that says it could not be made.

type StatusCoder

type StatusCoder interface {
	error
	Status() int
}

StatusCoder classifies a Dialer or Session error by HTTP status code. Callers must not infer the status from error prose.

type ToolCallResult

type ToolCallResult struct {
	Text       []string        `json:"text,omitempty"`
	IsError    bool            `json:"is_error"`
	Structured json.RawMessage `json:"structured,omitempty"`
	Raw        json.RawMessage `json:"raw,omitempty"`
}

ToolCallResult is a tool invocation outcome

Jump to

Keyboard shortcuts

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