shared

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2026 License: MIT Imports: 20 Imported by: 0

README

Shared Tools (pkg/core/tools/shared)

This directory contains the foundational tools and managers used across Falcon. These tools provide the low-level capabilities for HTTP communication, authentication, assertion, state management, and .falcon artifact handling.

Core Services

  • ResponseManager: Stores and shares the last HTTP response across tools.
  • VariableStore: Manages session-scoped and global variables (with {{VAR}} substitution).
  • ConfirmationManager: Handles human-in-the-loop approval for destructive operations.

Core Tools (5)

Essential for every interaction:

  • http_request: Make HTTP requests (GET, POST, PUT, DELETE, PATCH) with headers, auth, body
  • variable: Get/set variables in session scope (cleared on exit) or global scope (persistent)
  • auth: Unified authentication — bearer, basic, OAuth2, JWT parsing, basic auth decoding
  • wait: Delay between requests (seconds, backoff, polling)
  • retry: Retry failed tool calls with exponential backoff

Validation & Extraction Tools (3)

Test individual responses:

  • assert_response: Validate HTTP status, response body content, JSON paths, headers
  • extract_value: Extract values from response (JSON path, header, cookie, regex) into variables for chaining
  • validate_json_schema: Strict JSON Schema validation against spec

.falcon Artifact Tools (3)

Manage persistent artifacts in the .falcon folder:

  • falcon_write: Write validated YAML/JSON/Markdown to .falcon/ (with path safety: blocks traversal, protected files, syntax validation)
  • falcon_read: Read artifacts from .falcon/ (reports, flows, specs) — scoped to .falcon only
  • session_log: Create session audit trail — start/end timestamps, summary, searchable history

Managers & Helpers

Tools rely on these internal managers for consistency:

  • ReportValidator: Validates reports (ValidateReportContent) and falcon.md (ValidateFalconMD) after writes
  • AuthManager: Delegates to BearerTool, BasicTool, OAuth2Tool internally

Usage

These tools are the building blocks for higher-level autonomous workflows. They ensure consistency in how Falcon interacts with APIs, validates responses, and persists knowledge.

Example Prompts

Trigger these tools by:

  • "Make a GET request to /health."
  • "Assert that the response status code is 200."
  • "Extract the token from the login response and save it as auth_token."
  • "Authenticate using Bearer token eyJ...."
  • "Save this response to .falcon/flows/unit_get_users.yaml."
  • "Recall what we know about the API from falcon.md."
  • "Log this session — we tested the auth endpoints and found a CORS bug."

Documentation

Overview

Package shared provides merged authentication tools for the Falcon agent. This file combines Bearer token, Basic auth, OAuth2, and auth helper tools.

Index

Constants

View Source
const DefaultHTTPTimeout = 30 * time.Second

DefaultHTTPTimeout is the default timeout for HTTP requests.

View Source
const ManifestFilename = "manifest.json"

ManifestFilename is the name of the manifest file

Variables

View Source
var SecretPatterns = []*regexp.Regexp{

	regexp.MustCompile(`(?i)^(sk|pk|api|key|token|secret|password|passwd|pwd|auth|bearer|jwt|access|refresh)[-_]?[a-zA-Z0-9]{8,}`),
	regexp.MustCompile(`(?i)[a-zA-Z0-9]{32,}`),

	regexp.MustCompile(`sk-[a-zA-Z0-9]{20,}`),
	regexp.MustCompile(`(?i)^bearer\s+[a-zA-Z0-9_\-\.]+`),
	regexp.MustCompile(`(?i)^basic\s+[a-zA-Z0-9+/=]+`),
	regexp.MustCompile(`ghp_[a-zA-Z0-9]{36}`),
	regexp.MustCompile(`gho_[a-zA-Z0-9]{36}`),
	regexp.MustCompile(`github_pat_[a-zA-Z0-9_]{22,}`),
	regexp.MustCompile(`xox[baprs]-[a-zA-Z0-9\-]+`),
	regexp.MustCompile(`(?i)^ey[a-zA-Z0-9_\-]+\.[a-zA-Z0-9_\-]+\.`),
	regexp.MustCompile(`AKIA[0-9A-Z]{16}`),
	regexp.MustCompile(`(?i)^[a-z0-9]{32}$`),
	regexp.MustCompile(`(?i)^[a-f0-9]{40}$`),
	regexp.MustCompile(`(?i)^[a-f0-9]{64}$`),
	regexp.MustCompile(`AIza[0-9A-Za-z_\-]{35}`),
	regexp.MustCompile(`(?i)^SG\.[a-zA-Z0-9_\-]+\.[a-zA-Z0-9_\-]+`),
	regexp.MustCompile(`(?i)^sk_live_[a-zA-Z0-9]{24,}`),
	regexp.MustCompile(`(?i)^sk_test_[a-zA-Z0-9]{24,}`),
	regexp.MustCompile(`(?i)^rk_live_[a-zA-Z0-9]{24,}`),
	regexp.MustCompile(`(?i)^rk_test_[a-zA-Z0-9]{24,}`),
	regexp.MustCompile(`sq0[a-z]{3}-[a-zA-Z0-9_\-]{22,}`),
	regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`),
}

SecretPatterns contains regex patterns for detecting sensitive values

View Source
var SensitiveKeyPatterns = []*regexp.Regexp{
	regexp.MustCompile(`(?i)(api[_-]?key|apikey)`),
	regexp.MustCompile(`(?i)(secret[_-]?key|secretkey)`),
	regexp.MustCompile(`(?i)(access[_-]?key|accesskey)`),
	regexp.MustCompile(`(?i)(auth[_-]?token|authtoken)`),
	regexp.MustCompile(`(?i)(bearer[_-]?token|bearertoken)`),
	regexp.MustCompile(`(?i)(password|passwd|pwd)`),
	regexp.MustCompile(`(?i)(private[_-]?key|privatekey)`),
	regexp.MustCompile(`(?i)(client[_-]?secret|clientsecret)`),
	regexp.MustCompile(`(?i)(jwt[_-]?token|jwttoken)`),
	regexp.MustCompile(`(?i)(refresh[_-]?token|refreshtoken)`),
	regexp.MustCompile(`(?i)(access[_-]?token|accesstoken)`),
	regexp.MustCompile(`(?i)^token$`),
	regexp.MustCompile(`(?i)^secret$`),
	regexp.MustCompile(`(?i)^credentials?$`),
	regexp.MustCompile(`(?i)authorization`),
}

SensitiveKeyPatterns contains patterns for keys that typically hold sensitive values

View Source
var VariablePlaceholderPattern = regexp.MustCompile(`\{\{[A-Za-z_][A-Za-z0-9_]*\}\}`)

VariablePlaceholderPattern matches {{VAR}} placeholders

Functions

func ContainsVariablePlaceholder

func ContainsVariablePlaceholder(text string) bool

ContainsVariablePlaceholder checks if text contains {{VAR}} syntax

func CreateManifest

func CreateManifest(falconDir string) error

CreateManifest creates a new manifest.json file in the .falcon directory.

func GetManifestSummary

func GetManifestSummary(falconDir string) string

GetManifestSummary returns a human-readable summary of the manifest for the agent

func HasPlaintextSecret

func HasPlaintextSecret(text string) bool

HasPlaintextSecret checks if text contains hardcoded secrets without {{VAR}} placeholders. This is used to validate that saved requests use environment variables instead of hardcoded secrets.

func IsSecret

func IsSecret(key, value string) bool

IsSecret checks if a key/value pair appears to be sensitive. Returns true if: - The key matches a sensitive key pattern, OR - The value matches a known secret pattern

func MaskSecret

func MaskSecret(value string) string

MaskSecret returns a masked version of a secret value. For values 12+ chars: shows first 4 and last 4 chars (e.g., "sk-12...cdef") For shorter values: shows "****"

func StatusCodeMeaning

func StatusCodeMeaning(code int) string

StatusCodeMeaning returns a human-readable explanation of HTTP status codes.

func UpdateManifestCounts

func UpdateManifestCounts(falconDir string) error

UpdateManifestCounts scans the .falcon directory and updates file counts.

func ValidateExpectations

func ValidateExpectations(expected TestExpectation, resp *HTTPResponse, durationMs int64) []string

ValidateExpectations checks an HTTPResponse against a TestExpectation. Returns a list of validation error strings. Empty list means all passed. This is exported so tools with custom execution can reuse assertion logic.

func ValidateFalconMD

func ValidateFalconMD(path string) error

ValidateFalconMD checks that falcon.md is well-formed after an update_knowledge write. It verifies the file has the two required section headings and that the updated section is non-empty. Returns a descriptive error so the memory tool can alert the agent.

func ValidatePathWithinWorkDir

func ValidatePathWithinWorkDir(filePath, workDir string) (absPath string, err error)

ValidatePathWithinWorkDir checks if a given path is within the allowed work directory. This prevents path traversal attacks (e.g., "../../../etc/passwd").

func ValidateReport

func ValidateReport(path string) error

ValidateReport checks that a report file exists and is non-empty. Call this immediately after writing any report file.

func ValidateReportContent

func ValidateReportContent(path string) error

ValidateReportContent performs a deeper content check on a report file. It verifies the file has a heading, at least one result indicator, and no unresolved template placeholders. Returns a descriptive error if validation fails so the calling tool can surface it to the agent for a retry.

func ValidateRequestForSecrets

func ValidateRequestForSecrets(url string, headers map[string]string, body interface{}) string

ValidateRequestForSecrets checks a request's URL, headers, and body for plaintext secrets. Returns an error message describing what was found, or empty string if clean.

Types

type APIKnowledgeGraph

type APIKnowledgeGraph struct {
	Endpoints map[string]EndpointAnalysis `json:"endpoints"`
	Models    map[string]ModelDefinition  `json:"models"`
	Context   ProjectContext              `json:"context"`
	Version   string                      `json:"version"`
}

APIKnowledgeGraph is the core intelligence of Falcon, storing everything it knows about the API

type AssertParams

type AssertParams struct {
	StatusCode        *int                   `json:"status_code,omitempty"`
	StatusCodeNot     *int                   `json:"status_code_not,omitempty"`
	Headers           map[string]string      `json:"headers,omitempty"`
	HeadersNotPresent []string               `json:"headers_not_present,omitempty"`
	BodyContains      []string               `json:"body_contains,omitempty"`
	BodyNotContains   []string               `json:"body_not_contains,omitempty"`
	BodyEquals        interface{}            `json:"body_equals,omitempty"`
	BodyMatchesRegex  string                 `json:"body_matches_regex,omitempty"`
	JSONPath          map[string]interface{} `json:"json_path,omitempty"` // path -> expected value
	ResponseTimeMaxMs *int                   `json:"response_time_max_ms,omitempty"`
	ContentType       string                 `json:"content_type,omitempty"`
}

AssertParams defines validation criteria

type AssertTool

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

AssertTool provides response validation capabilities

func NewAssertTool

func NewAssertTool(responseManager *ResponseManager) *AssertTool

NewAssertTool creates a new assertion tool

func (*AssertTool) Description

func (t *AssertTool) Description() string

Description returns the tool description

func (*AssertTool) Execute

func (t *AssertTool) Execute(args string) (string, error)

Execute performs assertions on the last HTTP response

func (*AssertTool) Name

func (t *AssertTool) Name() string

Name returns the tool name

func (*AssertTool) Parameters

func (t *AssertTool) Parameters() string

Parameters returns the tool parameter description

type AssertionResult

type AssertionResult struct {
	Passed       bool     `json:"passed"`
	TotalChecks  int      `json:"total_checks"`
	PassedChecks int      `json:"passed_checks"`
	FailedChecks int      `json:"failed_checks"`
	Failures     []string `json:"failures,omitempty"`
}

AssertionResult represents the outcome of assertions

type AuthParams

type AuthParams struct {
	// Action is required: "bearer", "basic", "oauth2", "parse_jwt", "decode_basic"
	Action string `json:"action"`

	// For "bearer": token, save_as
	Token  string `json:"token,omitempty"`
	SaveAs string `json:"save_as,omitempty"`

	// For "basic": username, password, save_as
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`

	// For "oauth2": flow, token_url, client_id, client_secret, scopes, save_token_as
	Flow         string   `json:"flow,omitempty"`
	TokenURL     string   `json:"token_url,omitempty"`
	ClientID     string   `json:"client_id,omitempty"`
	ClientSecret string   `json:"client_secret,omitempty"`
	Scopes       []string `json:"scopes,omitempty"`
	SaveTokenAs  string   `json:"save_token_as,omitempty"`

	// For "parse_jwt" / "decode_basic": token
	FromBody string `json:"from_body,omitempty"`
}

AuthParams dispatches to the correct auth implementation based on action.

type AuthTool

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

AuthTool is the unified authentication tool that replaces auth_bearer, auth_basic, auth_oauth2, and auth_helper. Use the "action" field to select the auth method.

func NewAuthTool

func NewAuthTool(responseManager *ResponseManager, varStore *VariableStore) *AuthTool

NewAuthTool creates the unified auth tool backed by the existing auth implementations.

func (*AuthTool) Description

func (t *AuthTool) Description() string

func (*AuthTool) Execute

func (t *AuthTool) Execute(args string) (string, error)

func (*AuthTool) Name

func (t *AuthTool) Name() string

func (*AuthTool) Parameters

func (t *AuthTool) Parameters() string

type Baseline

type Baseline struct {
	Name      string            `json:"name"`
	CreatedAt time.Time         `json:"created_at"`
	Response  string            `json:"response"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

Baseline stores a saved response

type BasicParams

type BasicParams struct {
	// Username for authentication
	Username string `json:"username"`
	// Password for authentication
	Password string `json:"password"`
	// SaveAs is the optional variable name to save the Authorization header
	SaveAs string `json:"save_as,omitempty"`
}

BasicParams defines the parameters for HTTP Basic authentication.

type BasicTool

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

BasicTool creates HTTP Basic authentication headers with base64 encoding. It encodes username:password and wraps it in the standard "Basic <encoded>" format.

func NewBasicTool

func NewBasicTool(varStore *VariableStore) *BasicTool

NewBasicTool creates a new Basic auth tool with the given variable store.

func (*BasicTool) Description

func (t *BasicTool) Description() string

Description returns a human-readable description of the tool.

func (*BasicTool) Execute

func (t *BasicTool) Execute(args string) (string, error)

Execute creates a Basic authentication header from the provided credentials. The credentials are base64-encoded in the format "username:password". If save_as is specified, the header is saved to a variable for later use.

func (*BasicTool) Name

func (t *BasicTool) Name() string

Name returns the tool name.

func (*BasicTool) Parameters

func (t *BasicTool) Parameters() string

Parameters returns an example of the JSON parameters this tool accepts.

type BearerParams

type BearerParams struct {
	// Token is the actual token value (can use {{VAR}} for variable substitution)
	Token string `json:"token"`
	// SaveAs is the optional variable name to save the Authorization header
	SaveAs string `json:"save_as,omitempty"`
}

BearerParams defines the parameters for Bearer token authentication.

type BearerTool

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

BearerTool creates Bearer token authorization headers for JWT, API tokens, etc. It wraps a token in the standard "Bearer <token>" format and optionally saves it to a variable.

func NewBearerTool

func NewBearerTool(varStore *VariableStore) *BearerTool

NewBearerTool creates a new Bearer auth tool with the given variable store.

func (*BearerTool) Description

func (t *BearerTool) Description() string

Description returns a human-readable description of the tool.

func (*BearerTool) Execute

func (t *BearerTool) Execute(args string) (string, error)

Execute creates a Bearer authorization header from the provided token. If save_as is specified, the header is saved to a variable for later use.

func (*BearerTool) Name

func (t *BearerTool) Name() string

Name returns the tool name.

func (*BearerTool) Parameters

func (t *BearerTool) Parameters() string

Parameters returns an example of the JSON parameters this tool accepts.

type CapturedRequest

type CapturedRequest struct {
	Method    string            `json:"method"`
	Path      string            `json:"path"`
	Headers   map[string]string `json:"headers"`
	Body      string            `json:"body"`
	Timestamp time.Time         `json:"timestamp"`
}

CapturedRequest represents a captured webhook request

type CompareParams

type CompareParams struct {
	Baseline     string   `json:"baseline"`                // Baseline response ID or "last_response"
	Current      string   `json:"current,omitempty"`       // Current response or "last_response"
	IgnoreFields []string `json:"ignore_fields,omitempty"` // Fields to ignore (e.g., "timestamp")
	IgnoreOrder  bool     `json:"ignore_order,omitempty"`  // Ignore array order
	Tolerance    float64  `json:"tolerance,omitempty"`     // Numeric tolerance (0.01 = 1%)
	SaveBaseline bool     `json:"save_baseline,omitempty"` // Save current as new baseline
}

CompareParams defines comparison parameters

type CompareResponsesTool

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

CompareResponsesTool compares API responses for regression testing

func NewCompareResponsesTool

func NewCompareResponsesTool(responseManager *ResponseManager, falconDir string) *CompareResponsesTool

NewCompareResponsesTool creates a new response comparison tool

func (*CompareResponsesTool) Description

func (t *CompareResponsesTool) Description() string

Description returns the tool description

func (*CompareResponsesTool) Execute

func (t *CompareResponsesTool) Execute(args string) (string, error)

Execute compares two responses

func (*CompareResponsesTool) Name

func (t *CompareResponsesTool) Name() string

Name returns the tool name

func (*CompareResponsesTool) Parameters

func (t *CompareResponsesTool) Parameters() string

Parameters returns the tool parameter description

type ComparisonResult

type ComparisonResult struct {
	Match       bool     `json:"match"`
	Differences []string `json:"differences,omitempty"`
	Summary     string   `json:"summary"`
}

ComparisonResult represents the comparison outcome

type ConfirmationManager

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

ConfirmationManager handles thread-safe channel-based communication between tools that require user confirmation and the TUI.

func NewConfirmationManager

func NewConfirmationManager() *ConfirmationManager

NewConfirmationManager creates a new ConfirmationManager with default timeout.

func (*ConfirmationManager) Cancel

func (cm *ConfirmationManager) Cancel()

Cancel cancels any pending confirmation request.

func (*ConfirmationManager) IsPending

func (cm *ConfirmationManager) IsPending() bool

IsPending returns whether a confirmation request is waiting for response.

func (*ConfirmationManager) RequestConfirmation

func (cm *ConfirmationManager) RequestConfirmation() bool

RequestConfirmation blocks until the user responds or timeout occurs. Returns true if approved, false if rejected or timed out.

func (*ConfirmationManager) SendResponse

func (cm *ConfirmationManager) SendResponse(approved bool)

SendResponse sends the user's response to the waiting tool.

func (*ConfirmationManager) SetTimeout

func (cm *ConfirmationManager) SetTimeout(timeout time.Duration)

SetTimeout sets the confirmation timeout duration.

func (*ConfirmationManager) SetTimeoutCallback

func (cm *ConfirmationManager) SetTimeoutCallback(callback TimeoutCallback)

SetTimeoutCallback sets the callback to invoke when a confirmation times out.

type EndpointAnalysis

type EndpointAnalysis struct {
	Summary    string          `json:"summary"`
	Parameters []Parameter     `json:"parameters"`
	AuthType   string          `json:"auth_type"`
	Responses  []Response      `json:"responses"`
	Security   []SecurityRisks `json:"security_risks"`
}

EndpointAnalysis represents the structured output of analysis

type ExtractParams

type ExtractParams struct {
	JSONPath   string `json:"json_path,omitempty"`   // e.g., "$.data.user.id"
	Header     string `json:"header,omitempty"`      // e.g., "X-Request-Id"
	Cookie     string `json:"cookie,omitempty"`      // e.g., "session_token"
	Regex      string `json:"regex,omitempty"`       // e.g., "token=([a-z0-9]+)"
	RegexGroup int    `json:"regex_group,omitempty"` // Which capture group to use (default: 1)
	SaveAs     string `json:"save_as"`               // Variable name to save extracted value
}

ExtractParams defines what to extract and where to save it

type ExtractTool

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

ExtractTool extracts values from HTTP responses for use in subsequent requests

func NewExtractTool

func NewExtractTool(responseManager *ResponseManager, varStore *VariableStore) *ExtractTool

NewExtractTool creates a new extraction tool

func (*ExtractTool) Description

func (t *ExtractTool) Description() string

Description returns the tool description

func (*ExtractTool) Execute

func (t *ExtractTool) Execute(args string) (string, error)

Execute extracts a value from the last response

func (*ExtractTool) Name

func (t *ExtractTool) Name() string

Name returns the tool name

func (*ExtractTool) Parameters

func (t *ExtractTool) Parameters() string

Parameters returns the tool parameter description

type FalconReadParams

type FalconReadParams struct {
	// Path relative to .falcon/ — e.g. "flows/unit_get_users.yaml"
	Path string `json:"path"`
	// Format: "yaml", "json", or "raw" (default). Parsed output returned as formatted string.
	Format string `json:"format,omitempty"`
}

type FalconReadTool

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

FalconReadTool reads any file inside .falcon/ with path safety enforcement. Use this instead of read_file when accessing .falcon artifacts.

func NewFalconReadTool

func NewFalconReadTool(falconDir string) *FalconReadTool

func (*FalconReadTool) Description

func (t *FalconReadTool) Description() string

func (*FalconReadTool) Execute

func (t *FalconReadTool) Execute(args string) (string, error)

func (*FalconReadTool) Name

func (t *FalconReadTool) Name() string

func (*FalconReadTool) Parameters

func (t *FalconReadTool) Parameters() string

type FalconWriteParams

type FalconWriteParams struct {
	// Path relative to .falcon/ — e.g. "flows/unit_get_users.yaml"
	Path    string `json:"path"`
	Content string `json:"content"`
	// Format: "yaml", "json", or "markdown" (default). Parsed before writing.
	Format string `json:"format,omitempty"`
}

type FalconWriteTool

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

FalconWriteTool is a validated writer for .falcon/ artifacts (flows, spec, etc.). It enforces path safety, format validation, and protects critical config files.

func NewFalconWriteTool

func NewFalconWriteTool(falconDir string) *FalconWriteTool

func (*FalconWriteTool) Description

func (t *FalconWriteTool) Description() string

func (*FalconWriteTool) Execute

func (t *FalconWriteTool) Execute(args string) (string, error)

func (*FalconWriteTool) Name

func (t *FalconWriteTool) Name() string

func (*FalconWriteTool) Parameters

func (t *FalconWriteTool) Parameters() string

type HTTPRequest

type HTTPRequest struct {
	Method  string            `json:"method"`
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
	Body    interface{}       `json:"body,omitempty"`
	Timeout int               `json:"timeout,omitempty"`
}

HTTPRequest represents an HTTP request.

type HTTPResponse

type HTTPResponse struct {
	StatusCode int               `json:"status_code"`
	Status     string            `json:"status"`
	Headers    map[string]string `json:"headers"`
	Body       string            `json:"body"`
	Duration   time.Duration     `json:"duration"`
}

HTTPResponse represents an HTTP response.

func (*HTTPResponse) FormatResponse

func (r *HTTPResponse) FormatResponse() string

FormatResponse formats the HTTP response for display.

type HTTPTool

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

HTTPTool provides HTTP request capabilities.

func NewHTTPTool

func NewHTTPTool(responseManager *ResponseManager, varStore *VariableStore) *HTTPTool

NewHTTPTool creates a new HTTP tool with the default 30-second timeout.

func (*HTTPTool) Description

func (t *HTTPTool) Description() string

Description returns the tool description.

func (*HTTPTool) Execute

func (t *HTTPTool) Execute(args string) (string, error)

Execute performs an HTTP request (implements core.Tool).

func (*HTTPTool) Name

func (t *HTTPTool) Name() string

Name returns the tool name.

func (*HTTPTool) Parameters

func (t *HTTPTool) Parameters() string

Parameters returns the tool parameter description.

func (*HTTPTool) Run

func (t *HTTPTool) Run(req HTTPRequest) (*HTTPResponse, error)

Run performs an HTTP request and returns the response.

func (*HTTPTool) SetTimeout

func (t *HTTPTool) SetTimeout(timeout time.Duration)

SetTimeout sets the default timeout for HTTP requests.

type HelperParams

type HelperParams struct {
	// Action specifies the operation: "parse_jwt", "decode_basic"
	Action string `json:"action"`
	// Token is the token to parse or decode
	Token string `json:"token,omitempty"`
	// FromBody extracts the token from a response body field (optional)
	FromBody string `json:"from_body,omitempty"`
}

HelperParams defines the parameters for auth helper operations.

type HelperTool

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

HelperTool provides authentication utilities including JWT parsing and Basic auth decoding. It helps developers inspect and debug authentication tokens.

func NewHelperTool

func NewHelperTool(responseManager *ResponseManager, varStore *VariableStore) *HelperTool

NewHelperTool creates a new auth helper tool.

func (*HelperTool) Description

func (t *HelperTool) Description() string

Description returns a human-readable description of the tool.

func (*HelperTool) Execute

func (t *HelperTool) Execute(args string) (string, error)

Execute performs the requested auth helper action. Supported actions:

  • parse_jwt: Decode and display JWT token claims (header, payload, signature)
  • decode_basic: Decode Base64-encoded Basic auth credentials

func (*HelperTool) Name

func (t *HelperTool) Name() string

Name returns the tool name.

func (*HelperTool) Parameters

func (t *HelperTool) Parameters() string

Parameters returns an example of the JSON parameters this tool accepts.

type Manifest

type Manifest struct {
	Version     int            `json:"version"`
	Description string         `json:"description"`
	Counts      map[string]int `json:"counts"`
	LastUpdated string         `json:"last_updated"`
}

Manifest represents the .falcon folder manifest file. It helps the agent understand the knowledge base structure.

func LoadManifest

func LoadManifest(falconDir string) (*Manifest, error)

LoadManifest reads the manifest file from the .falcon directory. Returns nil if the file doesn't exist.

type ModelDefinition

type ModelDefinition struct {
	Name        string              `json:"name"`
	Fields      map[string]Variable `json:"fields"`
	Description string              `json:"description"`
}

ModelDefinition describes a data structure used in the API

type OAuth2Params

type OAuth2Params struct {
	// Flow specifies the OAuth2 grant type: "client_credentials", "password"
	Flow string `json:"flow"`
	// TokenURL is the OAuth2 token endpoint URL
	TokenURL string `json:"token_url"`
	// ClientID is the OAuth2 client identifier
	ClientID string `json:"client_id"`
	// ClientSecret is the OAuth2 client secret
	ClientSecret string `json:"client_secret"`
	// Scopes are the requested OAuth2 scopes (optional)
	Scopes []string `json:"scopes,omitempty"`
	// Username is required for password flow
	Username string `json:"username,omitempty"`
	// Password is required for password flow
	Password string `json:"password,omitempty"`
	// AuthURL is for authorization_code flow (not supported in CLI mode)
	AuthURL string `json:"auth_url,omitempty"`
	// RedirectURL is for authorization_code flow (not supported in CLI mode)
	RedirectURL string `json:"redirect_url,omitempty"`
	// Code is for authorization_code flow (not supported in CLI mode)
	Code string `json:"code,omitempty"`
	// SaveTokenAs is the variable name to save the access token
	SaveTokenAs string `json:"save_token_as,omitempty"`
}

OAuth2Params defines the parameters for OAuth2 authentication.

type OAuth2Tool

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

OAuth2Tool handles OAuth2 authentication flows. It supports client_credentials and password grant types, obtaining access tokens and automatically saving them as variables for use in subsequent requests.

func NewOAuth2Tool

func NewOAuth2Tool(varStore *VariableStore) *OAuth2Tool

NewOAuth2Tool creates a new OAuth2 auth tool with the given variable store.

func (*OAuth2Tool) Description

func (t *OAuth2Tool) Description() string

Description returns a human-readable description of the tool.

func (*OAuth2Tool) Execute

func (t *OAuth2Tool) Execute(args string) (string, error)

Execute performs the OAuth2 authentication flow. Supported flows:

  • client_credentials: Server-to-server authentication using client ID and secret
  • password: User authentication using username and password (Resource Owner Password Credentials)

func (*OAuth2Tool) Name

func (t *OAuth2Tool) Name() string

Name returns the tool name.

func (*OAuth2Tool) Parameters

func (t *OAuth2Tool) Parameters() string

Parameters returns an example of the JSON parameters this tool accepts.

type Parameter

type Parameter struct {
	Name        string `json:"name"`
	Type        string `json:"type"`
	Required    bool   `json:"required"`
	Description string `json:"description"`
}

type ProjectContext

type ProjectContext struct {
	Framework string `json:"framework"`
	SpecPath  string `json:"spec_path"`
	RootPath  string `json:"root_path"`
	Language  string `json:"language"`
}

ProjectContext stores metadata about the project itself

type ReportWriter

type ReportWriter struct {
	FalconDir string
}

ReportWriter handles the boilerplate of writing Markdown reports to .falcon/reports/.

func NewReportWriter

func NewReportWriter(falconDir string) *ReportWriter

NewReportWriter creates a new ReportWriter.

func (*ReportWriter) Write

func (w *ReportWriter) Write(reportName, defaultPrefix, content string) (string, error)

Write creates a report file in .falcon/reports/ with the given content. If reportName is empty, a name is generated from defaultPrefix + timestamp. Returns the full path to the written report file.

type Response

type Response struct {
	StatusCode  int    `json:"status_code"`
	Description string `json:"description"`
}

type ResponseManager

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

ResponseManager manages shared state between tools. This allows tools like assert_response and extract_value to access the last HTTP response from http_request tool.

func NewResponseManager

func NewResponseManager() *ResponseManager

NewResponseManager creates a new response manager.

func (*ResponseManager) GetHTTPResponse

func (rm *ResponseManager) GetHTTPResponse() *HTTPResponse

GetHTTPResponse retrieves the last HTTP response.

func (*ResponseManager) SetHTTPResponse

func (rm *ResponseManager) SetHTTPResponse(resp *HTTPResponse)

SetHTTPResponse stores the last HTTP response.

type RetryParams

type RetryParams struct {
	Tool          string `json:"tool"`
	Args          string `json:"args"`
	MaxAttempts   int    `json:"max_attempts"`
	RetryDelayMs  int    `json:"retry_delay_ms"`
	Backoff       string `json:"backoff,omitempty"` // "linear" or "exponential"
	RetryOnStatus []int  `json:"retry_on_status,omitempty"`
}

RetryParams defines retry parameters

type RetryTool

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

RetryTool provides retry logic with exponential backoff

func NewRetryTool

func NewRetryTool(executor ToolExecutor) *RetryTool

NewRetryTool creates a new retry tool

func (*RetryTool) Description

func (t *RetryTool) Description() string

Description returns the tool description

func (*RetryTool) Execute

func (t *RetryTool) Execute(args string) (string, error)

Execute retries a tool execution

func (*RetryTool) Name

func (t *RetryTool) Name() string

Name returns the tool name

func (*RetryTool) Parameters

func (t *RetryTool) Parameters() string

Parameters returns the tool parameter description

type SchemaParams

type SchemaParams struct {
	Schema       interface{} `json:"schema"`                  // Inline schema or file path
	SchemaURL    string      `json:"schema_url,omitempty"`    // Schema from URL
	ResponseBody string      `json:"response_body,omitempty"` // Or use last_response
}

SchemaParams defines schema validation parameters

type SchemaValidationTool

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

SchemaValidationTool validates JSON responses against JSON Schema

func NewSchemaValidationTool

func NewSchemaValidationTool(responseManager *ResponseManager) *SchemaValidationTool

NewSchemaValidationTool creates a new schema validation tool

func (*SchemaValidationTool) Description

func (t *SchemaValidationTool) Description() string

Description returns the tool description

func (*SchemaValidationTool) Execute

func (t *SchemaValidationTool) Execute(args string) (string, error)

Execute validates the response against the schema

func (*SchemaValidationTool) Name

func (t *SchemaValidationTool) Name() string

Name returns the tool name

func (*SchemaValidationTool) Parameters

func (t *SchemaValidationTool) Parameters() string

Parameters returns the tool parameter description

type SecurityRisks

type SecurityRisks struct {
	Risk        string `json:"risk"`
	Severity    string `json:"severity"`
	Description string `json:"description"`
}

type SessionLogParams

type SessionLogParams struct {
	// Action: "start", "end", "list", "read"
	Action  string `json:"action"`
	Summary string `json:"summary,omitempty"` // for "end": what was accomplished
	Session string `json:"session,omitempty"` // for "read": session ID (timestamp prefix)
}

type SessionLogTool

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

SessionLogTool writes and reads session audit records in .falcon/sessions/. Each session records which tools were used, when, and a user-provided summary.

func NewSessionLogTool

func NewSessionLogTool(falconDir string) *SessionLogTool

func (*SessionLogTool) Description

func (t *SessionLogTool) Description() string

func (*SessionLogTool) Execute

func (t *SessionLogTool) Execute(args string) (string, error)

func (*SessionLogTool) Name

func (t *SessionLogTool) Name() string

func (*SessionLogTool) Parameters

func (t *SessionLogTool) Parameters() string

type StatusCodeRange

type StatusCodeRange struct {
	Min int `json:"min"`
	Max int `json:"max"`
}

StatusCodeRange allows matching a range of status codes.

type SuiteResult

type SuiteResult struct {
	Name       string            `json:"name"`
	StartTime  time.Time         `json:"start_time"`
	EndTime    time.Time         `json:"end_time"`
	Duration   time.Duration     `json:"duration"`
	TotalTests int               `json:"total_tests"`
	Passed     int               `json:"passed"`
	Failed     int               `json:"failed"`
	Tests      []SuiteTestResult `json:"tests"`
}

SuiteResult represents the result of an entire suite

type SuiteTestResult

type SuiteTestResult struct {
	Name       string        `json:"name"`
	Passed     bool          `json:"passed"`
	Duration   time.Duration `json:"duration"`
	Error      string        `json:"error,omitempty"`
	StatusCode int           `json:"status_code,omitempty"`
}

SuiteTestResult represents the result of a single test in a manual suite

type TestDefinition

type TestDefinition struct {
	Name       string            `json:"name"`
	Request    HTTPRequest       `json:"request"`
	Assertions *AssertParams     `json:"assertions,omitempty"`
	Extract    map[string]string `json:"extract,omitempty"` // var_name -> json_path
}

TestDefinition defines a single test in a suite

type TestExecutor

type TestExecutor struct {
	HTTPTool *HTTPTool
}

TestExecutor provides reusable test scenario execution with standard assertions. Tools with custom execution logic can use ValidateExpectations directly without going through RunScenario/RunScenarios.

func NewTestExecutor

func NewTestExecutor(httpTool *HTTPTool) *TestExecutor

NewTestExecutor creates a new TestExecutor backed by the given HTTPTool.

func (*TestExecutor) RunScenario

func (e *TestExecutor) RunScenario(scenario TestScenario, baseURL string) TestResult

RunScenario executes a single TestScenario against baseURL and returns a TestResult. The baseURL is prepended to the scenario's URL path.

func (*TestExecutor) RunScenarios

func (e *TestExecutor) RunScenarios(scenarios []TestScenario, baseURL string, concurrency int) []TestResult

RunScenarios executes multiple scenarios with configurable concurrency. Results are returned in the same order as the input scenarios. If concurrency <= 0, defaults to 5.

type TestExpectation

type TestExpectation struct {
	StatusCode      int                    `json:"status_code"`
	StatusCodeRange *StatusCodeRange       `json:"status_code_range,omitempty"`
	BodyContains    []string               `json:"body_contains,omitempty"`
	BodyNotContains []string               `json:"body_not_contains,omitempty"`
	HeaderContains  map[string]string      `json:"header_contains,omitempty"`
	MaxDurationMs   int                    `json:"max_duration_ms,omitempty"`
	JSONPath        map[string]interface{} `json:"json_path,omitempty"`
}

TestExpectation defines what a test expects from the response.

type TestResult

type TestResult struct {
	ScenarioID     string   `json:"scenario_id"`
	ScenarioName   string   `json:"scenario_name"`
	Category       string   `json:"category"`
	Passed         bool     `json:"passed"`
	ActualStatus   int      `json:"actual_status"`
	ExpectedStatus int      `json:"expected_status"`
	Error          string   `json:"error,omitempty"`
	DurationMs     int64    `json:"duration_ms"`
	ResponseBody   string   `json:"response_body,omitempty"`
	Logs           []string `json:"logs"`
	Severity       string   `json:"severity,omitempty"`
	OWASPRef       string   `json:"owasp_ref,omitempty"`
	Timestamp      string   `json:"timestamp"`
}

TestResult represents the outcome of executing a test scenario.

type TestScenario

type TestScenario struct {
	ID          string            `json:"id"`
	Name        string            `json:"name"`
	Category    string            `json:"category"`
	Severity    string            `json:"severity"`
	Description string            `json:"description"`
	Method      string            `json:"method"`
	URL         string            `json:"url"`
	Headers     map[string]string `json:"headers,omitempty"`
	Body        interface{}       `json:"body,omitempty"`
	Expected    TestExpectation   `json:"expected"`
	OWASPRef    string            `json:"owasp_ref,omitempty"`
	CWERef      string            `json:"cwe_ref,omitempty"`
}

TestScenario represents a single test case with full categorization.

type TestSuiteParams

type TestSuiteParams struct {
	Name        string           `json:"name"`
	Tests       []TestDefinition `json:"tests"`
	OnFailure   string           `json:"on_failure,omitempty"`   // "stop" or "continue"
	SaveResults bool             `json:"save_results,omitempty"` // Save to .falcon/test-results/
}

TestSuiteParams defines a test suite

type TestSuiteTool

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

TestSuiteTool runs organized test suites

func NewTestSuiteTool

func NewTestSuiteTool(httpTool *HTTPTool, assertTool *AssertTool, extractTool *ExtractTool, responseManager *ResponseManager, varStore *VariableStore, falconDir string) *TestSuiteTool

NewTestSuiteTool creates a new test suite tool

func (*TestSuiteTool) Description

func (t *TestSuiteTool) Description() string

Description returns the tool description

func (*TestSuiteTool) Execute

func (t *TestSuiteTool) Execute(args string) (string, error)

Execute runs the test suite

func (*TestSuiteTool) Name

func (t *TestSuiteTool) Name() string

Name returns the tool name

func (*TestSuiteTool) Parameters

func (t *TestSuiteTool) Parameters() string

Parameters returns the tool parameter description

type TimeoutCallback

type TimeoutCallback func()

TimeoutCallback is called when a confirmation request times out. This allows the TUI to be notified and exit confirmation mode.

type ToolExecutor

type ToolExecutor interface {
	ExecuteTool(toolName string, args string) (string, error)
}

ToolExecutor interface for executing tools (to avoid circular dependency)

type Variable

type Variable struct {
	Type        string `json:"type"`
	Format      string `json:"format,omitempty"`
	Required    bool   `json:"required"`
	Description string `json:"description,omitempty"`
}

Variable represents a schema field or parameter

type VariableStore

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

VariableStore manages session and global variables

func NewVariableStore

func NewVariableStore(falconDir string) *VariableStore

NewVariableStore creates a new variable store

func (*VariableStore) Delete

func (vs *VariableStore) Delete(name string)

Delete removes a variable

func (*VariableStore) Get

func (vs *VariableStore) Get(name string) (string, bool)

Get retrieves a variable (checks session first, then global)

func (*VariableStore) List

func (vs *VariableStore) List() map[string]string

List returns all variables (session + global)

func (*VariableStore) Set

func (vs *VariableStore) Set(name, value string)

Set stores a variable (default: session scope)

func (*VariableStore) SetGlobal

func (vs *VariableStore) SetGlobal(name, value string) (warning string, err error)

SetGlobal stores a global variable (persisted to disk) Warns if the value appears to be a secret (should use session scope instead)

func (*VariableStore) Substitute

func (vs *VariableStore) Substitute(text string) string

Substitute replaces {{VAR}} placeholders in text with variable values

type WaitParams

type WaitParams struct {
	DurationMs int    `json:"duration_ms"`
	Reason     string `json:"reason,omitempty"`
}

WaitParams defines wait parameters

type WaitTool

type WaitTool struct{}

WaitTool provides delay functionality

func NewWaitTool

func NewWaitTool() *WaitTool

NewWaitTool creates a new wait tool

func (*WaitTool) Description

func (t *WaitTool) Description() string

Description returns the tool description

func (*WaitTool) Execute

func (t *WaitTool) Execute(args string) (string, error)

Execute waits for the specified duration

func (*WaitTool) Name

func (t *WaitTool) Name() string

Name returns the tool name

func (*WaitTool) Parameters

func (t *WaitTool) Parameters() string

Parameters returns the tool parameter description

type WebhookListenerParams

type WebhookListenerParams struct {
	Action         string `json:"action"`
	Port           int    `json:"port,omitempty"`
	Path           string `json:"path,omitempty"`
	TimeoutSeconds int    `json:"timeout_seconds,omitempty"`
	ListenerID     string `json:"listener_id,omitempty"`
}

WebhookListenerParams defines parameters for webhook listener

type WebhookListenerTool

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

WebhookListenerTool provides webhook capture capabilities

func NewWebhookListenerTool

func NewWebhookListenerTool(varStore *VariableStore) *WebhookListenerTool

NewWebhookListenerTool creates a new webhook listener tool

func (*WebhookListenerTool) Cleanup

func (t *WebhookListenerTool) Cleanup()

Cleanup stops all running listeners (call on shutdown)

func (*WebhookListenerTool) Description

func (t *WebhookListenerTool) Description() string

Description returns the tool description

func (*WebhookListenerTool) Execute

func (t *WebhookListenerTool) Execute(args string) (string, error)

Execute runs the webhook listener command

func (*WebhookListenerTool) Name

func (t *WebhookListenerTool) Name() string

Name returns the tool name

func (*WebhookListenerTool) Parameters

func (t *WebhookListenerTool) Parameters() string

Parameters returns the tool parameter description

Jump to

Keyboard shortcuts

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