server

package
v0.0.0-...-1a28f28 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2026 License: MIT Imports: 79 Imported by: 0

Documentation

Overview

Package server provides the Deputy gRPC/Connect server implementation.

The server exposes all Deputy capabilities via ConnectRPC, supporting both gRPC and HTTP/JSON protocols. This enables remote access from various clients including CLI tools, web applications, and CI/CD pipelines.

Services

The server provides seven main services:

  • ScanService: Vulnerability scanning - finds CVEs and advisories in dependencies
  • SecretsService: Secret detection - finds leaked credentials and API keys
  • ListService: Package enumeration - lists dependencies and ecosystems
  • SBOMService: SBOM generation - creates and compares Software Bills of Materials
  • RemediationService: Fix planning - generates and executes remediation plans
  • DiffService: Dependency comparison - compares packages and vulnerabilities between targets
  • GraphService: Dependency graph analysis - builds and queries dependency graphs

Architecture

Each service has a dedicated handler that wraps Deputy's internal packages and exposes them via ConnectRPC. Bidirectional type converters in internal/proto handle translation between proto messages and internal domain types.

Handler implementations:

  • scan_handler.go: Vulnerability scanning via internal/scanning
  • list_handler.go: Package listing via internal/inventory
  • sbom_handler.go: SBOM generation via internal/sbom
  • remediation_handler.go: Fix planning via internal/remediation
  • secrets_handler.go: Secret detection via internal/secrets
  • diff_handler.go: Dependency comparison via internal/compare
  • graph_handler.go: Dependency graph via internal/dependency/graph

Starting the Server

srv, err := server.New(server.Config{
    Addr: ":8090",
})
if err != nil {
    log.Fatal(err)
}
if err := srv.ListenAndServe(); err != nil {
    log.Fatal(err)
}

Configuration

The server supports various configuration options:

cfg := server.Config{
    Addr:         ":8090",           // Listen address
    ReadTimeout:  30 * time.Second,  // Request read timeout
    WriteTimeout: 5 * time.Minute,   // Response write timeout
    IdleTimeout:  2 * time.Minute,   // Idle connection timeout
    TLS:          &server.TLSConfig{...}, // Optional TLS
    CORS:         &server.CORSConfig{...}, // Optional CORS
    Auth:         &server.AuthConfig{...}, // Optional JWT auth
    RateLimit:    &server.RateLimitConfig{...}, // Optional rate limiting
}

Client Usage

Clients can connect using any ConnectRPC-compatible client:

// Scan for VULNERABILITIES (CVEs in dependencies)
scanClient := scanv1connect.NewScanServiceClient(
    http.DefaultClient,
    "http://localhost:8090",
)
resp, err := scanClient.Scan(ctx, connect.NewRequest(&scanv1.ScanRequest{
    Target: "github.com/example/repo",
}))

// Scan for SECRETS (leaked credentials, API keys)
secretsClient := secretsv1connect.NewSecretsServiceClient(
    http.DefaultClient,
    "http://localhost:8090",
)
resp, err := secretsClient.Scan(ctx, connect.NewRequest(&secretsv1.ScanRequest{
    Target: "github.com/example/repo",
}))

HTTP Endpoints

In addition to the gRPC services, the server exposes health check endpoints:

GET /health  - Returns {"status":"ok"} when healthy
GET /ready   - Returns {"status":"ready"} when ready
GET /version - Returns API version information

Package server provides HTTP handlers for Deputy's gRPC services.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthConfig

type AuthConfig struct {
	// Mode determines how authentication is enforced.
	// - "required": requests without valid tokens are rejected (401)
	// - "disabled": no authentication (default for backward compatibility)
	Mode string

	// JWKS configures JSON Web Key Set endpoints for key discovery.
	JWKS *JWKSConfig

	// StaticKeys provides inline public keys for validation.
	// Useful for development, testing, or air-gapped environments.
	StaticKeys []StaticKeyConfig

	// Issuers lists trusted token issuers (iss claim).
	// If empty, issuer validation is skipped.
	Issuers []string

	// Audiences lists expected audiences (aud claim).
	// If empty, audience validation is skipped.
	Audiences []string

	// RequiredClaims specifies claims that must be present in tokens.
	RequiredClaims []string

	// ClockSkew allows for clock drift when validating exp/nbf/iat.
	// Defaults to 0 (no skew allowed). Maximum 5 minutes.
	ClockSkew time.Duration

	// Deprecated: Use Mode="required" or Mode="disabled" instead.
	// Enabled turns authentication on/off.
	Enabled bool

	// Deprecated: Use JWKS.URL instead.
	// JWKSURL is the URL to fetch JSON Web Key Sets.
	JWKSURL string
}

AuthConfig configures authentication for the server. This uses the same JWT infrastructure as the proxy (internal/auth/jwt).

type CORSConfig

type CORSConfig struct {
	// AllowedOrigins is a list of allowed origins (* for all).
	AllowedOrigins []string

	// AllowedMethods is a list of allowed HTTP methods.
	AllowedMethods []string

	// AllowedHeaders is a list of allowed headers.
	AllowedHeaders []string

	// ExposedHeaders is a list of headers exposed to the client.
	ExposedHeaders []string

	// AllowCredentials indicates whether credentials are allowed.
	AllowCredentials bool

	// MaxAge is the max age for preflight cache in seconds.
	MaxAge int
}

CORSConfig configures Cross-Origin Resource Sharing.

type Config

type Config struct {
	// Addr is the address to listen on (e.g., ":8090", "localhost:8090").
	Addr string

	// ReadTimeout is the maximum duration for reading the request.
	ReadTimeout time.Duration

	// WriteTimeout is the maximum duration for writing the response.
	WriteTimeout time.Duration

	// IdleTimeout is the maximum duration to wait for the next request.
	IdleTimeout time.Duration

	// TLS configuration for production deployments.
	TLS *TLSConfig

	// CORS configuration for web clients.
	CORS *CORSConfig

	// Auth configuration for JWT authentication.
	Auth *AuthConfig

	// RateLimit configuration for rate limiting.
	RateLimit *RateLimitConfig

	// MaxRequestBodyBytes limits request body size (default: 10MB).
	MaxRequestBodyBytes int64

	// Policies lists paths to policy files for service-level authorization.
	// These policies are evaluated at service_* entrypoints to control
	// which users/services can perform which operations on which targets.
	Policies []string

	// Security configures explicit security overrides and public binding behavior.
	Security *SecurityConfig

	// Egress configures outbound network allowlists for remote server mode.
	Egress *EgressConfig
}

Config configures the Deputy server.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults.

type DiffHandler

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

DiffHandler implements the DiffService gRPC handler.

func NewDiffHandler

func NewDiffHandler(opts ...DiffHandlerOption) *DiffHandler

NewDiffHandler creates a new Diff service handler.

func (*DiffHandler) DiffContainerImages

DiffContainerImages performs a comprehensive diff between two container images.

SECURITY: This method can access local Docker daemon when transport is "daemon". Local transports (docker-daemon://, tarball://, oci-archive://) require localMode.

func (*DiffHandler) DiffPackages

DiffPackages compares dependencies between two targets.

func (*DiffHandler) DiffVulnerabilities

DiffVulnerabilities compares vulnerabilities between two targets.

type DiffHandlerOption

type DiffHandlerOption func(*DiffHandler)

DiffHandlerOption configures a DiffHandler.

func WithDiffLocalMode

func WithDiffLocalMode() DiffHandlerOption

WithDiffLocalMode enables local mode for DiffHandler.

func WithDiffTargetPolicy

func WithDiffTargetPolicy(policy *targets.RemoteTargetPolicy) DiffHandlerOption

WithDiffTargetPolicy sets the remote target policy for server mode validation.

type EgressConfig

type EgressConfig struct {
	// AllowedHosts is a list of hostnames allowed to resolve to private IPs.
	// Entries may be exact hosts or suffixes prefixed with a dot (e.g., ".corp.local").
	AllowedHosts []string

	// AllowedCIDRs is a list of CIDR ranges allowed for outbound connections.
	AllowedCIDRs []string

	// AllowSSH permits SSH-style git targets (ssh://, git@host:repo).
	AllowSSH bool

	// AllowLoopback permits loopback targets (127.0.0.1, ::1) for remote server mode.
	AllowLoopback bool

	// AllowLinkLocal permits link-local targets (169.254.0.0/16, fe80::/10).
	AllowLinkLocal bool
}

EgressConfig restricts outbound access for remote server mode. Use allowlists to permit internal registries or SCM safely.

type GraphHandler

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

GraphHandler implements the GraphService gRPC handler.

func NewGraphHandler

func NewGraphHandler(opts ...GraphHandlerOption) *GraphHandler

NewGraphHandler creates a new Graph service handler.

func (*GraphHandler) BuildGraph

BuildGraph constructs a dependency graph for a target.

func (*GraphHandler) QueryGraph

QueryGraph returns a filtered subset of a dependency graph.

func (*GraphHandler) WhyDependency

WhyDependency finds paths explaining why a dependency exists.

type GraphHandlerOption

type GraphHandlerOption func(*GraphHandler)

GraphHandlerOption configures a GraphHandler.

func WithGraphLocalMode

func WithGraphLocalMode() GraphHandlerOption

WithGraphLocalMode enables local mode which skips remote target validation. Use this for in-process clients that need to access local filesystems.

func WithGraphTargetPolicy

func WithGraphTargetPolicy(policy *targets.RemoteTargetPolicy) GraphHandlerOption

WithGraphTargetPolicy sets the remote target policy for server mode validation.

type HandlerOptions

type HandlerOptions struct {
	// LocalMode skips remote target validation for in-process usage.
	// When true, handlers allow local filesystem paths and other
	// targets that would normally be rejected for remote servers.
	LocalMode bool
}

HandlerOptions holds shared configuration for all service handlers.

func DefaultHandlerOptions

func DefaultHandlerOptions() HandlerOptions

DefaultHandlerOptions returns the default options for remote server mode.

func LocalHandlerOptions

func LocalHandlerOptions() HandlerOptions

LocalHandlerOptions returns options configured for in-process/local mode.

type InventoryHandler

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

InventoryHandler implements the InventoryService gRPC handler.

func NewInventoryHandler

func NewInventoryHandler(opts ...InventoryHandlerOption) *InventoryHandler

NewInventoryHandler creates a new Inventory service handler.

func (*InventoryHandler) CollectInventory

CollectInventory extracts package inventory from a target.

func (*InventoryHandler) ListExtractors

ListExtractors returns available inventory extractors.

func (*InventoryHandler) RegisterExtractor

RegisterExtractor registers a proto-based extractor plugin.

func (*InventoryHandler) StreamCollectInventory

StreamCollectInventory extracts inventory with streaming progress updates.

func (*InventoryHandler) UnregisterExtractor

UnregisterExtractor removes a previously registered plugin.

type InventoryHandlerOption

type InventoryHandlerOption func(*InventoryHandler)

InventoryHandlerOption configures an InventoryHandler.

func WithInventoryLocalMode

func WithInventoryLocalMode() InventoryHandlerOption

WithInventoryLocalMode enables local mode for InventoryHandler.

func WithInventoryRegistry

func WithInventoryRegistry(r *registry.Registry) InventoryHandlerOption

WithInventoryRegistry sets a custom registry for the handler. If not set, uses the default global registry.

func WithInventoryTargetPolicy

func WithInventoryTargetPolicy(policy *targets.RemoteTargetPolicy) InventoryHandlerOption

WithInventoryTargetPolicy sets the remote target policy for server mode validation.

type JWKSConfig

type JWKSConfig struct {
	// URL is the JWKS endpoint (e.g., https://issuer/.well-known/jwks.json).
	URL string

	// OIDCDiscovery enables OIDC discovery from issuer URL.
	// When true, URL should be the issuer URL; JWKS URI is auto-discovered.
	OIDCDiscovery bool

	// RefreshInterval controls background JWKS refresh (default: 1h).
	RefreshInterval time.Duration
}

JWKSConfig configures JWKS endpoint discovery.

type ListHandler

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

ListHandler implements the ListService gRPC handler.

func NewListHandler

func NewListHandler(opts ...ListHandlerOption) *ListHandler

NewListHandler creates a new List service handler.

func (*ListHandler) ListEcosystems

ListEcosystems returns supported ecosystems with their file patterns.

func (*ListHandler) ListPackages

ListPackages enumerates packages in a target.

type ListHandlerOption

type ListHandlerOption func(*ListHandler)

ListHandlerOption configures a ListHandler.

func WithListLocalMode

func WithListLocalMode() ListHandlerOption

WithListLocalMode enables local mode for ListHandler.

func WithListTargetPolicy

func WithListTargetPolicy(policy *targets.RemoteTargetPolicy) ListHandlerOption

WithListTargetPolicy sets the remote target policy for server mode validation.

type PolicyHandler

type PolicyHandler struct {
	policyv1connect.UnimplementedPolicyServiceHandler
	// contains filtered or unexported fields
}

PolicyHandler implements the PolicyService.

func NewPolicyHandler

func NewPolicyHandler(opts ...PolicyOption) *PolicyHandler

NewPolicyHandler creates a new PolicyServiceHandler.

func (*PolicyHandler) Evaluate

Evaluate runs policy evaluation against provided context.

func (*PolicyHandler) ListEntrypoints

ListEntrypoints returns all available policy entrypoints.

func (*PolicyHandler) Validate

Validate checks policy syntax and CEL expressions.

type PolicyOption

type PolicyOption func(*PolicyHandler)

PolicyOption configures the policy handler.

func WithPolicyLocalMode

func WithPolicyLocalMode() PolicyOption

WithPolicyLocalMode enables local filesystem access for policy files.

type RateLimitConfig

type RateLimitConfig struct {
	// Enabled turns rate limiting on/off.
	Enabled bool

	// RequestsPerSecond is the maximum requests per second per client.
	RequestsPerSecond float64

	// Burst is the maximum burst size.
	Burst int

	// TrustXFF enables trusting X-Forwarded-For header from all sources.
	// WARNING: Only enable this if ALL traffic goes through a trusted proxy.
	// Default: false (XFF headers are ignored to prevent spoofing).
	TrustXFF bool

	// TrustedProxies is a list of IP addresses or CIDR ranges that are trusted
	// to provide accurate X-Forwarded-For headers.
	// Example: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.1"]
	// If empty and TrustXFF is false, X-Forwarded-For is never trusted.
	TrustedProxies []string
}

RateLimitConfig configures rate limiting.

type RemediationHandler

type RemediationHandler struct {
	remediationv1connect.UnimplementedRemediationServiceHandler
	// contains filtered or unexported fields
}

RemediationHandler implements the RemediationService ConnectRPC service.

func NewRemediationHandler

func NewRemediationHandler(opts ...RemediationHandlerOption) *RemediationHandler

NewRemediationHandler creates a new RemediationHandler.

func NewRemediationHandlerWithRegistry

func NewRemediationHandlerWithRegistry(registry *agent.Registry) *RemediationHandler

NewRemediationHandlerWithRegistry creates a RemediationHandler with a custom registry. Deprecated: Use NewRemediationHandler(WithRemediationRegistry(r)) instead.

func (*RemediationHandler) ApproveStep

ApproveStep approves or denies a pending remediation step.

func (*RemediationHandler) ExecutePlan

ExecutePlan applies a previously generated remediation plan.

SECURITY: This method executes shell commands on the local filesystem. It is only available in local mode (in-process clients). Remote servers MUST NOT enable local mode, as this would allow arbitrary code execution.

func (*RemediationHandler) ExecuteWithAgent

ExecuteWithAgent uses an AI agent plugin to generate and apply fixes interactively.

SECURITY: This method uses AI agents that can execute shell commands and modify files. It is only available in local mode (in-process clients). Remote servers MUST NOT enable local mode, as this would allow arbitrary code execution.

func (*RemediationHandler) GeneratePlan

GeneratePlan creates a remediation plan from scan results.

func (*RemediationHandler) ListAgents

ListAgents returns available AI agents for remediation.

func (*RemediationHandler) ResumeAgent

ResumeAgent resumes a previous agent execution session.

type RemediationHandlerOption

type RemediationHandlerOption func(*RemediationHandler)

RemediationHandlerOption configures a RemediationHandler.

func WithRemediationLocalMode

func WithRemediationLocalMode() RemediationHandlerOption

WithRemediationLocalMode enables local mode which allows plan execution. Use this for in-process clients that need to execute remediation steps. SECURITY: Never enable this for remote servers - it allows arbitrary code execution.

func WithRemediationRegistry

func WithRemediationRegistry(registry *agent.Registry) RemediationHandlerOption

WithRemediationRegistry sets a custom agent registry.

type SBOMHandler

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

SBOMHandler implements the SBOMService gRPC handler.

func NewSBOMHandler

func NewSBOMHandler(opts ...SBOMHandlerOption) *SBOMHandler

NewSBOMHandler creates a new SBOM service handler.

func (*SBOMHandler) Diff

Diff compares two SBOMs.

func (*SBOMHandler) Generate

Generate creates an SBOM for a target.

type SBOMHandlerOption

type SBOMHandlerOption func(*SBOMHandler)

SBOMHandlerOption configures a SBOMHandler.

func WithSBOMLocalMode

func WithSBOMLocalMode() SBOMHandlerOption

WithSBOMLocalMode enables local mode which skips remote target validation. Use this for in-process clients that need to access local filesystems.

func WithSBOMTargetPolicy

func WithSBOMTargetPolicy(policy *targets.RemoteTargetPolicy) SBOMHandlerOption

WithSBOMTargetPolicy sets the remote target policy for server mode validation.

type ScanHandler

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

ScanHandler implements the ScanService ConnectRPC service.

func NewScanHandler

func NewScanHandler(opts ...ScanHandlerOption) *ScanHandler

NewScanHandler creates a new ScanHandler.

func (*ScanHandler) Scan

Scan performs a vulnerability scan on a target.

func (*ScanHandler) StreamScan

StreamScan performs a vulnerability scan with streaming progress updates.

type ScanHandlerOption

type ScanHandlerOption func(*ScanHandler)

ScanHandlerOption configures a ScanHandler.

func WithLocalMode

func WithLocalMode() ScanHandlerOption

WithLocalMode enables local mode which skips remote target validation. Use this for in-process clients that need to access local filesystems.

func WithScanTargetPolicy

func WithScanTargetPolicy(policy *targets.RemoteTargetPolicy) ScanHandlerOption

WithScanTargetPolicy sets the remote target policy for server mode validation.

type SecretsHandler

type SecretsHandler struct {
	secretsv1connect.UnimplementedSecretsServiceHandler
	// contains filtered or unexported fields
}

SecretsHandler implements the SecretsService ConnectRPC service.

func NewSecretsHandler

func NewSecretsHandler(opts ...SecretsHandlerOption) (*SecretsHandler, error)

NewSecretsHandler creates a new SecretsHandler with default configuration.

func NewSecretsHandlerWithConfig

func NewSecretsHandlerWithConfig(config secrets.EngineConfig) (*SecretsHandler, error)

NewSecretsHandlerWithConfig creates a new SecretsHandler with custom configuration.

func (*SecretsHandler) ListDetectors

ListDetectors returns available secret detectors.

func (*SecretsHandler) RegisterDetector

RegisterDetector registers a custom detector (plugin support).

func (*SecretsHandler) Scan

Scan performs secret detection on a target.

func (*SecretsHandler) ScanDiff

ScanDiff scans changes between two git refs for secrets.

func (*SecretsHandler) ScanHistory

ScanHistory scans git history for secrets.

func (*SecretsHandler) StreamScan

StreamScan performs secret detection with streaming progress updates.

func (*SecretsHandler) Verify

Verify attempts to validate detected secrets.

type SecretsHandlerOption

type SecretsHandlerOption func(*SecretsHandler)

SecretsHandlerOption configures a SecretsHandler.

func WithSecretsLocalMode

func WithSecretsLocalMode() SecretsHandlerOption

WithSecretsLocalMode enables local mode which skips remote target validation. Use this for in-process clients that need to access local filesystems.

func WithSecretsTargetPolicy

func WithSecretsTargetPolicy(policy *targets.RemoteTargetPolicy) SecretsHandlerOption

WithSecretsTargetPolicy sets the remote target policy for server mode validation.

type SecurityConfig

type SecurityConfig struct {
	// AllowPublic permits binding to non-loopback addresses (e.g., 0.0.0.0).
	// This must be explicitly enabled for remote server deployments.
	AllowPublic bool

	// AllowInsecure permits starting the server without TLS/auth safeguards
	// or when configuration validation fails (e.g., policy load errors).
	// This should only be used for local development.
	AllowInsecure bool
}

SecurityConfig controls explicit opt-ins for unsafe server modes.

type Server

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

Server is the Deputy gRPC/Connect server.

func New

func New(cfg Config) (*Server, error)

New creates a new Deputy server with the given configuration.

func (*Server) Addr

func (s *Server) Addr() string

Addr returns the server address.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the HTTP handler for testing. This returns the fully wrapped handler including all middleware (auth, CORS, rate limiting, etc.).

func (*Server) IsTLS

func (s *Server) IsTLS() bool

IsTLS returns true if TLS is configured.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts the server and blocks until it stops.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server.

type StaticKeyConfig

type StaticKeyConfig struct {
	// KeyID is the key identifier (matches JWT header "kid").
	KeyID string

	// Algorithm specifies the signing algorithm (e.g., RS256, ES256, EdDSA).
	Algorithm string

	// PublicKey is the PEM-encoded public key.
	PublicKey string
}

StaticKeyConfig defines an inline public key.

type TLSConfig

type TLSConfig struct {
	// CertFile is the path to the TLS certificate file.
	CertFile string

	// KeyFile is the path to the TLS private key file.
	KeyFile string

	// MinVersion is the minimum TLS version (default: TLS 1.2).
	MinVersion uint16

	// ClientAuth specifies the policy for client certificate authentication.
	ClientAuth tls.ClientAuthType

	// ClientCAFile is the path to the CA certificate for client verification.
	ClientCAFile string
}

TLSConfig configures TLS for the server.

type VulnerabilityHandler

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

VulnerabilityHandler implements the VulnerabilityService gRPC handler.

func NewVulnerabilityHandler

func NewVulnerabilityHandler(opts ...VulnerabilityHandlerOption) *VulnerabilityHandler

NewVulnerabilityHandler creates a new Vulnerability service handler.

func (*VulnerabilityHandler) GetAdvisories

GetAdvisories retrieves multiple vulnerability advisories by ID.

func (*VulnerabilityHandler) GetAdvisory

GetAdvisory retrieves a single vulnerability advisory by ID.

type VulnerabilityHandlerOption

type VulnerabilityHandlerOption func(*VulnerabilityHandler)

VulnerabilityHandlerOption configures a VulnerabilityHandler.

func WithVulnerabilityOSVClient

func WithVulnerabilityOSVClient(client osv.Client) VulnerabilityHandlerOption

WithVulnerabilityOSVClient configures the OSV client for vulnerability lookups.

Jump to

Keyboard shortcuts

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