Documentation
¶
Overview ¶
Package permissions - Loader for permission rules from various sources.
This module provides functionality for loading permission rules from disk (settings files). Aligned with OpenClaude's permissionsLoader.ts.
Index ¶
- Constants
- Variables
- func AddPermissionRulesToSettings(source SettingsSource, rules []PermissionRule) error
- func CreateDenialTrackingState() *types.DenialTrackingState
- func DeletePermissionRuleFromSettings(source SettingsSource, toolName string, ruleContent string) error
- func HandleDenialLimitExceeded(state *types.DenialTrackingState, config *types.DenialLimitConfig, ...) *types.PermissionResult
- func IsPermissionDenied(err error) bool
- func IsValidRuleBehavior(behavior string) bool
- func RecordDenial(state *types.DenialTrackingState) *types.DenialTrackingState
- func RecordSuccess(state *types.DenialTrackingState) *types.DenialTrackingState
- func ShouldAllowManagedPermissionsOnly() bool
- func ShouldFallbackToPrompting(state *types.DenialTrackingState, config *types.DenialLimitConfig) bool
- func ShouldShowAlwaysAllowOptions() bool
- type Classification
- type Classifier
- type Engine
- func (e *Engine) AddHook(hook Hook)
- func (e *Engine) AddInterfaceHook(hook types.Hook)
- func (e *Engine) AddRule(rule PermissionRule) error
- func (e *Engine) AddRules(rules []PermissionRule) error
- func (e *Engine) CheckPermission(ctx context.Context, pctx *PermissionContext) (types.PermissionResult, error)
- func (e *Engine) GetAllRuleSources() []types.PermissionRuleSource
- func (e *Engine) GetEffectiveRules() []PermissionRule
- func (e *Engine) GetHooks() []Hook
- func (e *Engine) GetRuleCountBySource() map[types.PermissionRuleSource]int
- func (e *Engine) GetRuleSourcePriority(source types.PermissionRuleSource) int
- func (e *Engine) GetRulesBySource(source types.PermissionRuleSource) []PermissionRule
- func (e *Engine) IsAutoModeAvailable() bool
- func (e *Engine) MergeRulesFromSources(sourceRules map[types.PermissionRuleSource][]PermissionRule) error
- func (e *Engine) RemoveHook(name string)
- func (e *Engine) RemoveRulesBySource(source types.PermissionRuleSource)
- func (e *Engine) RunPostPermissionHooks(ctx context.Context, pctx *PermissionContext, result *types.PermissionResult) error
- func (e *Engine) SetAdvancedClassifier(classifier auto.AdvancedClassifierInterface)
- func (e *Engine) SetClassifier(classifier Classifier)
- func (e *Engine) UpdateRules(update types.PermissionUpdate) error
- type Hook
- type HookAdapter
- type HookHandler
- type Integrator
- func (i *Integrator) AutoModeAvailable() bool
- func (i *Integrator) BatchCheckToolUses(ctx context.Context, toolUses []types.ToolUseContent, ...) ([]types.PermissionResult, error)
- func (i *Integrator) CanUseTool(sessionID types.SessionID, turnID types.TurnID, mode types.PermissionMode) types.CanUseToolFn
- func (i *Integrator) CheckToolUse(ctx context.Context, toolUse types.ToolUseContent, toolDef tool.Definition, ...) (types.PermissionResult, error)
- func (i *Integrator) FilterAllowedToolUses(ctx context.Context, toolUses []types.ToolUseContent, ...) ([]types.ToolUseContent, []types.PermissionResult, error)
- func (i *Integrator) PermissionMiddleware(sessionID types.SessionID, turnID types.TurnID, mode types.PermissionMode) func(ctx context.Context, toolName string, toolInput map[string]any) error
- func (i *Integrator) Resolver(sessionID types.SessionID, turnID types.TurnID, mode types.PermissionMode) types.PermissionResolver
- func (i *Integrator) ResolverWithContext(sessionID types.SessionID, turnID types.TurnID, ...) types.PermissionResolver
- func (i *Integrator) SetAutoModeProviderClient(apiClient *providers.Client, model types.ModelIdentifier)
- func (i *Integrator) SetPromptFn(fn types.PromptFn)
- type PermissionContext
- type PermissionDeniedError
- type PermissionRule
- type PermissionRuleValue
- type SettingsJSON
- type SettingsSource
- type StoredPermissionRule
Constants ¶
const ( RuleBehaviorAllow = "allow" RuleBehaviorDeny = "deny" RuleBehaviorAsk = "ask" )
Variables ¶
var RuleSourcePriority = map[types.PermissionRuleSource]int{ types.PermissionSourceCliArg: 100, types.PermissionSourceSession: 90, types.PermissionSourceProjectSettings: 80, types.PermissionSourceUserSettings: 70, types.PermissionSourceLocalSettings: 60, types.PermissionSourceStatic: 50, types.PermissionSourceDynamic: 40, types.PermissionSourceClassifier: 30, types.PermissionSourceHook: 20, }
RuleSourcePriority defines the priority order for rule sources. Higher priority sources override lower priority sources. Aligned with OpenClaude's SETTING_SOURCES order (permissions.ts:109-114).
Functions ¶
func AddPermissionRulesToSettings ¶
func AddPermissionRulesToSettings(source SettingsSource, rules []PermissionRule) error
AddPermissionRulesToSettings adds rules to settings.
func CreateDenialTrackingState ¶
func CreateDenialTrackingState() *types.DenialTrackingState
CreateDenialTrackingState creates a new denial tracking state. Aligned with OpenClaude's createDenialTrackingState (denialTracking.ts:17-22).
func DeletePermissionRuleFromSettings ¶
func DeletePermissionRuleFromSettings(source SettingsSource, toolName string, ruleContent string) error
DeletePermissionRuleFromSettings deletes a rule from settings.
func HandleDenialLimitExceeded ¶
func HandleDenialLimitExceeded( state *types.DenialTrackingState, config *types.DenialLimitConfig, isHeadless bool, classifierReason string, ) *types.PermissionResult
HandleDenialLimitExceeded checks if denial limits were exceeded and returns an appropriate permission result. Returns nil if no limit was hit. Aligned with OpenClaude's handleDenialLimitExceeded (permissions.ts:984-1049).
func IsPermissionDenied ¶
IsPermissionDenied returns true if an error is a permission denied error.
func IsValidRuleBehavior ¶
IsValidRuleBehavior checks if a behavior is valid.
func RecordDenial ¶
func RecordDenial(state *types.DenialTrackingState) *types.DenialTrackingState
RecordDenial records a classifier denial and returns the updated state. Uses the existing RecordDenial method from the DenialTrackingState struct.
func RecordSuccess ¶
func RecordSuccess(state *types.DenialTrackingState) *types.DenialTrackingState
RecordSuccess records a successful classification and resets consecutive denials. Uses the existing RecordSuccess method from the DenialTrackingState struct.
func ShouldAllowManagedPermissionsOnly ¶
func ShouldAllowManagedPermissionsOnly() bool
ShouldAllowManagedPermissionsOnly returns true if only managed rules should be used.
func ShouldFallbackToPrompting ¶
func ShouldFallbackToPrompting(state *types.DenialTrackingState, config *types.DenialLimitConfig) bool
ShouldFallbackToPrompting checks if denial limits were exceeded. Uses the existing DenialLimitConfig and ShouldFallback method.
func ShouldShowAlwaysAllowOptions ¶
func ShouldShowAlwaysAllowOptions() bool
ShouldShowAlwaysAllowOptions returns true if "always allow" should be shown.
Types ¶
type Classification ¶
type Classification struct {
// Allowed is true if the classifier predicts the action is safe.
Allowed bool `json:"allowed"`
// Confidence is 0-1.
Confidence float64 `json:"confidence"`
// Reason explains the classification.
Reason string `json:"reason,omitempty"`
}
Classification represents a classifier's prediction.
type Classifier ¶
type Classifier interface {
// Classify predicts if a tool use should be allowed.
Classify(ctx context.Context, toolName string, input map[string]any) (Classification, error)
}
Classifier predicts permission decisions.
type Engine ¶
type Engine struct {
// FailClosed controls classifier unavailability behavior.
// When true (default), classifier errors result in deny (fail-closed).
// When false, classifier errors fall back to ask (fail-open).
FailClosed bool
// contains filtered or unexported fields
}
Engine checks permissions for tool usage.
func (*Engine) AddInterfaceHook ¶
AddInterfaceHook adds a types.Hook interface to the engine. This allows external hooks to be registered with the engine.
func (*Engine) AddRule ¶
func (e *Engine) AddRule(rule PermissionRule) error
AddRule adds a permission rule.
func (*Engine) AddRules ¶
func (e *Engine) AddRules(rules []PermissionRule) error
AddRules adds multiple permission rules.
func (*Engine) CheckPermission ¶
func (e *Engine) CheckPermission(ctx context.Context, pctx *PermissionContext) (types.PermissionResult, error)
CheckPermission checks if a tool can be used.
func (*Engine) GetAllRuleSources ¶
func (e *Engine) GetAllRuleSources() []types.PermissionRuleSource
GetAllRuleSources returns all rule sources currently in use.
func (*Engine) GetEffectiveRules ¶
func (e *Engine) GetEffectiveRules() []PermissionRule
GetEffectiveRules returns rules sorted by priority (highest first). This ensures that higher-priority sources (cliArg, session) take precedence.
func (*Engine) GetRuleCountBySource ¶
func (e *Engine) GetRuleCountBySource() map[types.PermissionRuleSource]int
GetRuleCountBySource returns the count of rules for each source.
func (*Engine) GetRuleSourcePriority ¶
func (e *Engine) GetRuleSourcePriority(source types.PermissionRuleSource) int
GetRuleSourcePriority returns the priority for a given source.
func (*Engine) GetRulesBySource ¶
func (e *Engine) GetRulesBySource(source types.PermissionRuleSource) []PermissionRule
GetRulesBySource returns all rules from a specific source.
func (*Engine) IsAutoModeAvailable ¶
IsAutoModeAvailable returns whether auto mode has a working classifier path configured.
func (*Engine) MergeRulesFromSources ¶
func (e *Engine) MergeRulesFromSources(sourceRules map[types.PermissionRuleSource][]PermissionRule) error
MergeRulesFromSources merges rules from multiple sources, respecting priority. This is useful when loading rules from different configuration sources.
func (*Engine) RemoveHook ¶
RemoveHook removes a hook by name.
func (*Engine) RemoveRulesBySource ¶
func (e *Engine) RemoveRulesBySource(source types.PermissionRuleSource)
RemoveRulesBySource removes all rules from a specific source.
func (*Engine) RunPostPermissionHooks ¶
func (e *Engine) RunPostPermissionHooks(ctx context.Context, pctx *PermissionContext, result *types.PermissionResult) error
RunPostPermissionHooks runs hooks after a permission decision has been made. This is useful for logging, analytics, or modifying the result based on policy.
func (*Engine) SetAdvancedClassifier ¶
func (e *Engine) SetAdvancedClassifier(classifier auto.AdvancedClassifierInterface)
SetAdvancedClassifier wires a transcript-aware classifier into auto mode.
func (*Engine) SetClassifier ¶
func (e *Engine) SetClassifier(classifier Classifier)
SetClassifier sets the classifier and initializes autoMode.
func (*Engine) UpdateRules ¶
func (e *Engine) UpdateRules(update types.PermissionUpdate) error
UpdateRules applies permission updates from various sources. Aligned with OpenClaude's permission update system (permissions.ts:1420-1447).
type Hook ¶
type Hook struct {
// Stage is when this hook is called.
Stage types.HookStage `json:"stage"`
// Handler is the hook function.
Handler HookHandler `json:"-"`
// Priority determines order (higher = earlier).
Priority int `json:"priority"`
// ID uniquely identifies this hook.
ID string `json:"id"`
}
Hook is called before or after permission checks.
type HookAdapter ¶
type HookAdapter struct {
// contains filtered or unexported fields
}
HookAdapter adapts the internal Hook type to implement the types.Hook interface. This allows both internal and external hooks to coexist.
func NewHookAdapter ¶
func NewHookAdapter(hook Hook) *HookAdapter
NewHookAdapter creates a new hook adapter.
type HookHandler ¶
type HookHandler func(ctx context.Context, pctx *PermissionContext) (types.PermissionResult, error)
HookHandler is a function that handles a hook.
type Integrator ¶
type Integrator struct {
// contains filtered or unexported fields
}
Integrator integrates permission checking with tool execution. The Orchestrator is the primary execution path and has its own safety checks via SafetyChecker. The Integrator provides a PermissionResolver for contexts that need standalone permission resolution (e.g. the query loop).
func NewIntegrator ¶
func NewIntegrator(engine *Engine) *Integrator
NewIntegrator creates a new permission integrator.
func (*Integrator) AutoModeAvailable ¶
func (i *Integrator) AutoModeAvailable() bool
AutoModeAvailable reports whether the underlying permission engine has an operational auto-mode classifier configured.
func (*Integrator) BatchCheckToolUses ¶
func (i *Integrator) BatchCheckToolUses( ctx context.Context, toolUses []types.ToolUseContent, tools map[string]tool.Tool, sessionID types.SessionID, turnID types.TurnID, mode types.PermissionMode, ) ([]types.PermissionResult, error)
BatchCheckToolUses checks permissions for multiple tool uses.
func (*Integrator) CanUseTool ¶
func (i *Integrator) CanUseTool(sessionID types.SessionID, turnID types.TurnID, mode types.PermissionMode) types.CanUseToolFn
CanUseTool creates a CanUseToolFn that integrates with the permission engine.
func (*Integrator) CheckToolUse ¶
func (i *Integrator) CheckToolUse( ctx context.Context, toolUse types.ToolUseContent, toolDef tool.Definition, sessionID types.SessionID, turnID types.TurnID, mode types.PermissionMode, ) (types.PermissionResult, error)
CheckToolUse checks permissions for a specific tool use. This is a convenience method that builds the request from tool use content.
func (*Integrator) FilterAllowedToolUses ¶
func (i *Integrator) FilterAllowedToolUses( ctx context.Context, toolUses []types.ToolUseContent, tools map[string]tool.Tool, sessionID types.SessionID, turnID types.TurnID, mode types.PermissionMode, ) ([]types.ToolUseContent, []types.PermissionResult, error)
FilterAllowedToolUses filters tool uses to only those allowed.
func (*Integrator) PermissionMiddleware ¶
func (i *Integrator) PermissionMiddleware( sessionID types.SessionID, turnID types.TurnID, mode types.PermissionMode, ) func(ctx context.Context, toolName string, toolInput map[string]any) error
PermissionMiddleware creates a middleware that checks permissions before tool execution.
func (*Integrator) Resolver ¶
func (i *Integrator) Resolver(sessionID types.SessionID, turnID types.TurnID, mode types.PermissionMode) types.PermissionResolver
Resolver creates a typed PermissionResolver that integrates with the permission engine.
func (*Integrator) ResolverWithContext ¶
func (i *Integrator) ResolverWithContext( sessionID types.SessionID, turnID types.TurnID, permissionContext *types.PermissionContext, transcript []types.Message, ) types.PermissionResolver
ResolverWithContext creates a typed PermissionResolver that carries the live session permission context and transcript into the permission engine.
func (*Integrator) SetAutoModeProviderClient ¶
func (i *Integrator) SetAutoModeProviderClient(apiClient *providers.Client, model types.ModelIdentifier)
SetAutoModeProviderClient wires the auto-mode classifier to the given provider client.
func (*Integrator) SetPromptFn ¶
func (i *Integrator) SetPromptFn(fn types.PromptFn)
SetPromptFn sets the prompt function for asking users.
type PermissionContext ¶
type PermissionContext struct {
// Mode is the current permission mode.
Mode types.PermissionMode `json:"mode"`
// ExecutionMode is the current execution mode.
ExecutionMode string `json:"execution_mode,omitempty"`
// ToolName is the tool being called.
ToolName string `json:"tool_name"`
// ToolInput is the input to the tool.
ToolInput map[string]any `json:"tool_input"`
// SessionID identifies the session.
SessionID types.SessionID `json:"session_id"`
// TurnID identifies the turn.
TurnID types.TurnID `json:"turn_id"`
// ToolUseID identifies the specific tool use when available.
ToolUseID string `json:"tool_use_id,omitempty"`
// Stage identifies which permission stage is being resolved.
Stage types.ToolPermissionStage `json:"stage,omitempty"`
// Intent identifies the decision kind requested for this stage.
Intent types.ToolPermissionIntent `json:"intent,omitempty"`
// IsConcurrent indicates if this tool will run concurrently.
IsConcurrent bool `json:"is_concurrent"`
// ToolDefinition is the tool's definition (if available).
ToolDefinition *tool.Definition `json:"tool_definition,omitempty"`
// Tool provides access to optional content-specific permission matching.
Tool tool.Tool `json:"-"`
// ShouldAvoidPermissionPrompts is true for headless/background agents
// that cannot display UI prompts. When true, ask decisions are
// automatically denied with an asyncAgent decision reason.
ShouldAvoidPermissionPrompts bool `json:"should_avoid_permission_prompts,omitempty"`
// IsBypassPermissionsModeAvailable indicates whether bypass mode was
// available at the start of the session. Used by plan mode to determine
// whether it should behave like bypass mode or ask for permissions.
IsBypassPermissionsModeAvailable bool `json:"is_bypass_permissions_mode_available,omitempty"`
// IsToolRunningInSandbox indicates whether the tool will run inside a sandbox.
// This is used by canSandboxAutoAllow to determine if a command can be auto-approved.
IsToolRunningInSandbox bool `json:"is_tool_running_in_sandbox,omitempty"`
// Additional context.
Additional map[string]any `json:"additional,omitempty"`
}
PermissionContext provides context for permission checking.
type PermissionDeniedError ¶
PermissionDeniedError represents a permission denied error.
func (*PermissionDeniedError) Error ¶
func (e *PermissionDeniedError) Error() string
type PermissionRule ¶
type PermissionRule struct {
// Value is the structured rule target.
Value PermissionRuleValue `json:"value"`
// Pattern is the legacy serialized form, kept for compatibility.
Pattern string `json:"pattern,omitempty"`
// Behavior is the allow/deny/ask decision.
Behavior types.PermissionBehavior `json:"behavior"`
// Priority determines rule precedence (higher = more important).
Priority int `json:"priority"`
// Reason explains why this rule exists.
Reason string `json:"reason,omitempty"`
// Source indicates where this rule came from.
Source types.PermissionRuleSource `json:"source"`
}
PermissionRule represents a permission rule.
func LoadRulesFromDisk ¶
func LoadRulesFromDisk() ([]PermissionRule, error)
LoadRulesFromDisk loads all permission rules from disk. Aligned with OpenClaude's loadAllPermissionRulesFromDisk.
func NewDefaultRules ¶
func NewDefaultRules() []PermissionRule
NewDefaultRules returns default permission rules.
type PermissionRuleValue ¶
type PermissionRuleValue struct {
// ToolName identifies the tool this rule targets.
ToolName string `json:"tool_name"`
// RuleContent carries optional content-specific matching handled by the tool.
RuleContent string `json:"rule_content,omitempty"`
}
PermissionRuleValue is the structured value of a permission rule.
type SettingsJSON ¶
type SettingsJSON struct {
PermissionRules []StoredPermissionRule `json:"permission_rules,omitempty"`
AllowManagedPermissionRulesOnly bool `json:"allow_managed_permission_rules_only,omitempty"`
}
SettingsJSON represents the structure of a settings file.
type SettingsSource ¶
type SettingsSource string
SettingsSource represents where settings come from.
const ( SourceUserSettings SettingsSource = "userSettings" SourceProjectSettings SettingsSource = "projectSettings" SourceLocalSettings SettingsSource = "localSettings" SourceCliArg SettingsSource = "cliArg" SourceManagedSettings SettingsSource = "policySettings" )