Eggsec intentionally supports two usage families with distinct enforcement postures:
- Manual operator posture (CLI/TUI): Human-directed security assessment. Operators may proceed through warnings and explicit confirmations where appropriate. This mode is designed to remain productive and should not inherit agent-grade strictness by default.
- Automated agent posture (MCP, security agent, CI, REST, gRPC): Programmatic noninteractive execution. Strict, explicitly scoped, non-overridable. Manual overrides are never honored.
The contract below is the source of truth for how enforcement behaves per execution surface. All later implementation phases must follow this contract to prevent drift in either direction: over-hardening manual use, or under-hardening agent use.
| Term | Definition |
|---|---|
| Execution surface | Where the request originates. ExecutionSurface has 9 variants: CliManual, TuiManual, CliManualStrict, TuiManualStrict, McpServer, SecurityAgent, Ci, RestApi, GrpcApi. |
| Execution profile | Enforcement behavior, represented by ExecutionProfile (ManualPermissive, ManualGuarded, CiStrict, McpStrict, AgentStrict). |
| Manual permissive | Human-directed default mode (ManualPermissive). Warnings and confirmation prompts are available; operator may override low-risk classes. |
| Manual guarded | Strict human mode (ManualGuarded). Equivalent to CLI --strict-scope and future TUI guarded toggle. No discretion path. |
| Agent strict | Noninteractive/model-controlled strict posture (AgentStrict). Cannot self-approve scope expansion or override any enforcement. Handler defensively rebuilds AgentStrict; runtime validates profile at construction. |
| Scope provenance | Whether scope came from an explicit manifest (ConfigFile, CliScopeFile, GeneratedPreset) versus DefaultEmpty (no manifest provided). |
| Scope specification | Declarative caller intent (eggsec-tool-core::ScopeSpec, Python ToolScopeSpec): transport data with no authorization semantics and no is_allowed() method. Must be converted via eggsec::config::scope_from_spec before any policy check. |
| Scope intersection | Effective authorization for tool requests carrying a specification: the engine scope and the converted declaration must both allow; either may deny. A permissive declaration can never widen a restrictive engine scope. |
| Manual override | Explicit operator acceptance of specific confirmation classes. Only valid in ManualPermissive contexts. Honored and audited only there. |
| Confirmation class | Machine-readable class (ConfirmationClass) requiring explicit operator action before dispatch. |
| Execution Surface | Intended Posture | ExecutionProfile |
Explicit Scope Manifest Required | Warn May Dispatch |
RequireConfirmation May Dispatch After Override |
Manual Override Flags Honored | Policy Re-evaluated Before Dispatch |
|---|---|---|---|---|---|---|---|
| CLI default | Manual permissive | ManualPermissive |
No (warnings for safe scope misses) | Yes | Yes (with matching ManualOverride) |
Yes | No (single evaluation) |
CLI --strict-scope |
Manual guarded | ManualGuarded |
Yes (networked operations) | No | No (treated as deny) | No | No (single evaluation) |
| TUI default | Manual permissive | ManualPermissive |
No (warnings for safe scope misses) | Yes | Yes (with matching ManualOverride) |
Yes | No (single evaluation) |
| TUI guarded | Manual guarded | ManualGuarded |
Yes (networked operations) | No | No (treated as deny) | No | No (single evaluation) |
| MCP server | Agent strict | McpStrict |
Yes (networked operations) | No (treated as deny) | No (treated as deny) | No | Yes |
| Security agent | Agent strict | AgentStrict |
Yes (networked operations) | No (treated as deny) | No (treated as deny) | No | Yes |
| CI | Agent strict | CiStrict |
Yes (target/networked operations) | No (treated as deny) | No (treated as deny) | No | No (single evaluation) |
| REST API | Agent strict | McpStrict or CiStrict |
Yes (networked operations) | No (treated as deny) | No (treated as deny) | No | Yes |
| gRPC API | Agent strict | McpStrict |
Yes (networked operations) | No (treated as deny) | No (treated as deny) | No | Yes |
| Daemon HTTP | Agent strict | McpStrict |
Yes (networked operations) | No (treated as deny) | No (treated as deny) | No | Yes |
Key invariant: ManualPermissive behavior must not bleed into MCP, security agent, CI, REST, or gRPC. Agent strict behavior must not become the default for normal CLI/TUI manual use.
REST enforcement specifics: REST API now constructs EnforcementContext::for_surface(ExecutionSurface::RestApi, ...) and dispatches every tool call through enforcement.evaluate() before execution. Only EnforcementOutcome::Allow permits dispatch. Warn, RequireConfirmation, and Deny all result in HTTP 403 Forbidden with a structured RestPolicyErrorResponse (code: POLICY_DENIED, includes serialized PolicyDecision). REST is noninteractive and programmatic — warning-class ambiguity must not dispatch. Metadata rest_exposable flags are enforced before policy evaluation; non-exposed tools fail closed. RestState carries EnforcementContext instead of Option<Scope>.
Daemon HTTP enforcement specifics: Daemon HTTP transport (feature-gated http-api) is noninteractive and adds no separate authorization gate of its own. HTTP routes map 1:1 to ClientCommand variants and go through DaemonHost::handle_command() with DaemonRequestContext; the shared runtime executor then runs EnforcementContext enforcement (approve_run_request → ApprovedOperation) before any I/O. The ExecutionProfile is derived from the RuntimeSurface carried in the submitted RunRequest (the HTTP body supplies surface), not hardcoded by the daemon. Because the surface is noninteractive, no manual override flags are accepted on this path. Loopback-only bind is enforced by default; public bind requires explicit configuration and emits a warning.
gRPC enforcement specifics: gRPC API now constructs GrpcService with EnforcementContext::for_surface(ExecutionSurface::GrpcApi, ...) and dispatches every tool call through EnforcementContext::approve() → EnforcedDispatcher::dispatch_checked(). Only EnforcementOutcome::Allow produces an ApprovedOperation token; Warn, RequireConfirmation, and Deny all fail with EnforcementError and return gRPC Status::permission_denied. Metadata grpc_exposable flags are enforced before policy evaluation; non-exposed tools fail closed. Audit events emitted for all enforcement outcomes including denials.
EnforcementOutcome wraps a PolicyDecision with profile-aware dispatch semantics:
| Outcome | Manual Permissive | Manual Guarded | Automated (CI/MCP/Agent) |
|---|---|---|---|
Allow |
Dispatch permitted | Dispatch permitted | Dispatch permitted |
Warn |
Dispatch permitted; warnings must be visible and audited | Treated as deny | Treated as deny |
RequireConfirmation |
Dispatch permitted only after matching ManualOverride classes are present |
Treated as deny | Treated as deny |
Deny |
Dispatch never permitted | Dispatch never permitted | Dispatch never permitted |
Invariant: Automated surfaces must treat Warn conservatively (as denial) and must treat RequireConfirmation as denial. Only ManualPermissive may dispatch on Warn or RequireConfirmation (with matching override). REST specifically: only Allow permits dispatch; Warn, RequireConfirmation, and Deny all return HTTP 403 with structured policy error.
ConfirmationClass variants represent categories of conditions that trigger RequireConfirmation under ManualPermissive:
| Class | as_str() |
Override Mechanism | Notes |
|---|---|---|---|
OutOfScope |
out-of-scope |
--allow-out-of-scope or --yes |
Low-risk scope confirmation |
TargetExpansion |
target-expansion |
--allow-out-of-scope or --yes |
Low-risk scope confirmation |
HighRisk |
high-risk |
--allow-high-risk or --allow-db-pentest |
Requires dedicated flag and reason |
NonBaselineCapability |
nonbaseline-capability |
--allow-nonbaseline-capability |
Requires dedicated flag |
PrivateResolution |
private-resolution |
--allow-private-resolution |
Requires dedicated flag |
CrossHostRedirect |
cross-host-redirect |
--allow-cross-host-redirect |
Requires dedicated flag |
TrafficInterception |
traffic-interception |
--allow-web-proxy |
Requires dedicated web-proxy flag |
ExplicitExclusion |
explicit-exclusion |
--allow-explicit-exclusion |
Requires dedicated flag and audit reason |
--yes (assume_yes) is intentionally narrow. It suppresses low-risk manual prompts for:
OutOfScopeTargetExpansion
--yes does not authorize:
HighRiskNonBaselineCapabilityPrivateResolutionCrossHostRedirectTrafficInterceptionExplicitExclusion
Those classes require their dedicated --allow-* flags. This prevents accidental authorization of high-risk or sensitive operations through prompt suppression.
The following conditions produce hard denial and must never be converted to manual confirmation:
| Condition | Rationale |
|---|---|
| Missing compile-time feature | Build configuration error; cannot proceed |
| Invalid target | Unresolvable or malformed target |
| Scope parse/check error | Scope configuration is broken |
| Capability explicitly denied by policy | Policy explicitly blocks this capability |
| Risk not allowed by execution policy | Operation exceeds policy risk limits |
| Missing explicit scope manifest in automated mode | Strict profiles require explicit scope for networked operations |
| Agent/model-supplied override attempt | Automated surfaces cannot self-approve scope expansion |
These invariants hold across all execution paths:
- Manual permissive isolation: Manual permissive behavior must not bleed into MCP, security agent, CI, REST, or gRPC.
- Agent strict isolation: Agent strict behavior must not become the default for normal CLI/TUI manual use.
- Override scope: Manual override flags are only honored in
ManualPermissivecontexts. - Scope provenance: Scope provenance for automated networked execution must come from
LoadedScope, not rawScope. - Shared evaluation: Every dispatch path must eventually flow through
EnforcementContext::evaluate(). - Re-evaluation: Agent/MCP dispatch must re-evaluate enforcement immediately before dispatch.
- Constructor intent: Programmatic constructors for agent-facing servers should require explicit enforcement context or be clearly test-only.
- Type-level dispatch: Strict programmatic surfaces (REST, MCP, Agent, gRPC) require an
ApprovedOperationtoken before dispatch viaEnforcedDispatcher::dispatch_checked(). RawToolDispatcher::dispatch()is not reachable from these surfaces. - Single authorizer: Only
eggsec::config::Scopeevaluated throughEnforcementContext(or itsis_target_allowedpolicy implementation) decides whether a network target is authorized. Protocol-neutral DTOs (ScopeSpec) carry intent only. - Specification intersection: A tool request carrying a
ScopeSpecis additionally constrained at dispatch (enforce_request_scope_spec): the converted declaration must also allow the effective target. Conversion failures deny (fail closed).
All protocol surfaces now derive OperationDescriptor from the canonical OperationMetadata registry:
- REST: Uses
metadata_for_tool_id(tool_id)with fallback for unknown tools. Always setsrequires_explicit_scope = true. - MCP: Uses
metadata_for_tool_id(tool_id)with profile-specificintended_usesandrequires_explicit_scopefromMcpProfilePolicy. - TUI: Uses
operation_metadata(op_id)from tab spec. Tab-specific overrides for wireless-advanced (DefenseLab mode) and db-pentest (DefenseLab mode). - Agent: Uses
metadata_for_tool_id(scan_type)for known scan types. Falls back to keyword-based classification for unknown scan types.
Missing metadata for an externally executable tool triggers a runtime warning (REST/MCP/agent) or uses a conservative fallback (agent only).
Scenario: Operator runs eggsec scan example.com without a scope file.
Expected: EnforcementOutcome::Warn (safe scope-selection miss for passive/safe-active StandardAssessment). Warning is visible. Scan proceeds. No hard denial.
Scenario: Scope has [[allowed_targets]] pattern = "*.lab.internal" but operator scans example.com.
Expected: EnforcementOutcome::RequireConfirmation with class out-of-scope. Operator must pass --allow-out-of-scope to proceed. --yes also suppresses this prompt.
Scenario: Same as above but with --strict-scope (ManualGuarded).
Expected: EnforcementOutcome::Deny. No discretion path. Hard denial.
Scenario: MCP server receives a networked tool call with DefaultEmpty scope.
Expected: EnforcementOutcome::Deny. LoadedScope::is_explicit_manifest() returns false for DefaultEmpty. Strict profiles require explicit manifest for networked operations.
Scenario: Agent requests an IntrusiveFuzz capability but policy has not added it to allowed_capabilities.
Expected: EnforcementOutcome::Deny. Non-baseline capabilities (IntrusiveFuzz, LoadTest, etc.) require explicit listing in allowed_capabilities for strict profiles. PassiveFingerprint, ActiveProbe, Crawl, WafDetect are baseline and allowed by default.
Scenario: Operator triggers a high-risk action in TUI (e.g., WAF stress test).
Expected: TUI preflight shows RequireConfirmation with class high-risk. Operator must pass --allow-high-risk flag with a reason. --yes does not suppress this prompt.
Phase 4 added regression tests to protect manual CLI/TUI discretion from agent-grade strictness leaking into default operation. Tests cover:
- Policy-level outcomes (
eggsec-policykernel tests +configfacade suites): pure evaluation tests verifyingevaluate_enforcementproduces correct outcomes (Allow/Warn/RequireConfirmation/Deny) for each profile, risk level, and scope configuration, evaluated over explicitEnabledFeaturesand suppliedTargetScopefacts (Phase C; legacyconfig::policy_decision::testspaths remain facades). - CommandContext override wiring (
commands::handlers::tests): 49 tests verifying CLI flags map correctly toManualOverride, error messages list exact flags needed, strict profiles ignore overrides, and audit fields are recorded.
Key invariants locked by tests:
| Invariant | Test Coverage |
|---|---|
--yes only covers OutOfScope/TargetExpansion |
manual_override_permits_narrow_yes_for_outofscope_targetexpansion_only, yes_alone_does_not_permit_high_risk, yes_alone_does_not_permit_explicit_exclusion |
| High-risk requires dedicated flag | allow_high_risk_permits_high_risk_without_explicit_exclusion, manual_permissive_high_risk_no_override_error_explains_yes_insufficient |
| Private/cross-host require dedicated flags | allow_private_resolution_permits_private_resolution_class, allow_cross_host_redirect_permits_cross_host_class, allow_out_of_scope_does_not_permit_private_or_cross_host |
| Strict profiles ignore overrides | manual_guarded_with_all_overrides_still_denies_require_confirmation, ci_strict_with_all_overrides_still_denies_require_confirmation, mcp_strict_via_command_context_ignores_overrides, agent_strict_via_command_context_ignores_overrides |
| TrafficInterception requires web-proxy flag | manual_override_traffic_interception_permits_only_web_proxy |
| Error messages name exact flags | command_context_error_messages_list_exact_dedicated_flags, manual_permissive_out_of_scope_no_override_error_suggests_allow_flag |
| Audit records use stable kebab strings | successful_override_records_stable_kebab_case_classes_on_decision_no_debug_no_dups, successful_out_of_scope_override_records_audit_fields |
| Explicit exclusions hard-deny in non-permissive | explicit_exclusion_denies_in_all_profiles, manual_permissive_does_not_downgrade_explicit_exclusion |
| Risk-policy/feature/capability denials stay hard-deny | manual_permissive_does_not_downgrade_risk_policy_denial, manual_permissive_does_not_downgrade_feature_missing_denial, manual_permissive_does_not_downgrade_capability_denial |
Phase 8 added a comprehensive enforcement matrix test suite (crates/eggsec/tests/enforcement_matrix.rs) that systematically tests all execution surfaces against scope states, risk tiers, capabilities, and override handling. The matrix protects the dual-mode contract by catching:
- Manual CLI/TUI becoming too strict to be useful.
- Agent/MCP/REST/CI becoming too permissive or honoring manual discretion.
172 tests covering:
- Surface mapping invariants: All 9
ExecutionSurfacevariants map to correctExecutionProfile. - Manual permissive invariants: Safe ops allow, scope misses require confirmation,
assume_yesis narrow, denied capabilities hard-deny, missing features hard-deny. - Manual guarded invariants: Scope misses deny, overrides ignored, high-risk with policy allows.
- MCP invariants: Missing scope denies, no confirmation path, baseline capabilities allowed, non-baseline requires explicit allow.
- Security agent invariants: Same as MCP, plus
AgentStrictprofile, warnings treated as denial. - REST invariants: Explicit manifest required, only
Allowdispatches, no confirmation/warn path, overrides ignored. - CI invariants: Matches automated strict behavior, no override honoring.
- Risk tier matrix: All risk tiers (Passive through C2Operation, including DbPentest and TrafficInterception) tested across all surfaces with and without policy flags.
- Capability matrix: Baseline vs non-baseline capabilities across all surfaces, denied capability hard-deny, all 6 nonbaseline capability variants (RawPacketProbe, CredentialTesting, DatabaseAssessment, TrafficInterception, RemoteExecution, C2Simulation).
- Override isolation:
ManualOverride::permits()tested for eachConfirmationClass, override flags don't leak across surfaces. - Scope state matrix: DefaultEmpty, explicit allow, allow miss, exclusion - tested across permissive and strict surfaces.
- Dual-mode contract: Permissive never hard-deny safe in-scope, strict never produce Warn/RequireConfirmation.
- Private/local target scope:
requires_private_or_local_targetdenies when no scope provided (all profiles), allows with explicit scope, scope miss behavior under permissive vs strict. - Metadata integration: Descriptors generated from
OperationMetadatafor recon, fuzz, db-pentest, proxy-intercept, and packet operations, verifying risk + capability + feature requirements.
Run:
cargo test --test enforcement_matrix -p eggsec
cargo test -p eggsec --features rest-api --test enforcement_matrixPhase 2 verified and hardened the enforcement invariants established in earlier phases:
| API | Status | Disposition |
|---|---|---|
CommandContext::with_execution_profile() |
Removed | Replaced by with_execution_surface() and direct EnforcementContext construction. |
CommandContext::ensure_scope() / ensure_scope_url() |
Removed | Scope checks are centralized in EnforcementContext::evaluate(). |
ToolDispatcher::dispatch() (raw) |
#[doc(hidden)], pub(crate) |
Internal implementation detail used by EnforcedDispatcher and pipeline orchestrator. Regression test guard (enforced_dispatch_regression.rs) enforces no raw dispatch in strict surfaces. |
- CI handler dispatch invariant (
ci_handler_has_no_dispatch_path): Verifies CI handler contains noToolDispatcher,EnforcedDispatcher,SecurityTool,ToolRegistry, ordispatch_checkedimports. Architecture Invariant #19.
Phase 2 confirmed that all acceptance criteria from the Phase 2 plan are satisfied by existing test infrastructure:
- Enforcement matrix: 172 tests in
enforcement_matrix.rscovering manual permissive, manual guarded, and strict automated surfaces. - Override isolation: Automated surfaces cannot use manual override flags to proceed.
- Scope provenance: Automated operations requiring explicit scope fail without explicit manifest provenance.
- Approval token mismatch:
dispatch_checkedrejects tool mismatch, target mismatch, and allows alias match. - Raw dispatch guard: Strict surfaces cannot reach raw
ToolDispatcher::dispatch(). - CI handler isolation: CI handler has no dispatch path (Architecture Invariant #19).
Run:
cargo test --test enforcement_matrix -p eggsec
cargo test --test enforced_dispatch_regression -p eggsecPhase 12 hardened enforcement from convention (call sites expected to evaluate first) to type-level structure. Strict programmatic surfaces cannot dispatch a tool without an ApprovedOperation token, enforced structurally rather than by discipline at call sites.
ApprovedOperation (eggsec-policy::approval; facade at config/policy_decision.rs): Proof-of-enforcement token with private fields. Produced exclusively by EnforcementContext::approve() or approve_manual(). Read-only accessors: descriptor(), decision(), surface(), profile(), audit_event_id(). Cannot be constructed outside enforcement code.
EnforcementError (eggsec-policy::decision; facade at config/policy_decision.rs): Structured error from approve()/approve_manual():
Denied { decision }- Policy denied the operation (DenyandWarnon strict surfaces).ConfirmationRequired { decision, required_classes }- Manual confirmation needed.ManualOverrideUnavailable { surface, decision }- Override not supported on this surface.
EnforcedDispatcher (tool/dispatcher.rs): Wrapper around ToolDispatcher requiring ApprovedOperation before dispatch via dispatch_checked(). Verifies request tool name and target match the approved descriptor; fails closed on mismatch.
EnforcementContext::approve(surface, descriptor)- Strict: onlyAllowproduces a token.Warn,RequireConfirmation, andDenyall fail withEnforcementError. Used by REST, MCP, Agent, CI.EnforcementContext::approve_manual(surface, descriptor, manual_override)- Manual permissive: supportsWarn(approved with warning) andRequireConfirmationwhen matching override flags are present. Strict/automated surfaces reject overrides. Used by CLI/TUI.
1. Build OperationDescriptor from OperationMetadata
2. let approved = enforcement.approve(surface, descriptor)?;
3. Build ToolRequest
4. dispatcher.dispatch_checked(&approved, request).await
| Surface | Status | Entry Point |
|---|---|---|
| REST | Complete | tool/protocol/rest.rs |
| MCP | Complete | tool/protocol/mcp/handlers/server.rs |
| Agent | Complete | agent/mod.rs |
| gRPC | Complete | tool/protocol/grpc.rs |
| TUI | Complete | eggsec-tui/src/app/mod.rs (direct-launch/high-risk tabs) |
| CLI | Via approve_manual() |
Command handlers via evaluate_and_enforce_operation() |
evaluate()is retained for preflight, diagnostics, and advisory checks.- Policy semantics are unchanged.
- Raw
ToolDispatcher::dispatch()is not removed butEnforcedDispatcheris required for all protocol/agent production code. Agent dispatch returns a hard invariant error ifenforced_dispatcheris present butApprovedOperationis missing.
Every meaningful enforcement decision produces a normalized EnforcementAuditEvent via audit.rs.
event_id: UUID v4 per decisiontimestamp: UTC timestampsurface:ExecutionSurface(CliManual, TuiManual, CliManualStrict, TuiManualStrict, McpServer, SecurityAgent, Ci, RestApi, GrpcApi)profile:ExecutionProfile(ManualPermissive, ManualGuarded, McpStrict, AgentStrict, CiStrict)operation_id: canonical operation nametarget: optional target stringoutcome:AuditOutcome(Allow, Warn, Confirmed, Deny, ConfirmationRequired)decision: fullPolicyDecisionwith decision_idconfirmation_classes: classes required for this decisionmanual_override: override details (only when confirmed)manual_override_ignored: true if override flags were present but surface does not honor themscope:ScopeAuditwith source, path, allow/exclusion counts, explicit_manifest flagcorrelation_id: optional request/correlation ID for REST/MCP
| Surface | Audit Emitted | Manual Override Record | Correlation ID |
|---|---|---|---|
| CLI | Yes | Accepted overrides include class+reason | None |
| TUI | Yes | Accepted overrides include class+reason | None |
| REST | Yes | Never (REST never confirms) | generate_correlation_id() |
| gRPC | Yes | Never (gRPC never confirms) | uuid::Uuid::new_v4() |
| MCP | Yes | Never (MCP never confirms) | JSON-RPC request id |
| Agent | Yes | Never (Agent never confirms) | None |
| CI | Via CLI handler | Never (CI never confirms) | None |
Allow,Warn,Confirmed:tracing::info!Deny,ConfirmationRequired:tracing::warn!