Build Security Agents with Controlled Access to Scanning Tools

TL;DR

AI security agent tool access should expose a small set of approved assessment operations, not a shell wrapped in a tool description. Resolve registered assets and assessment profiles through trusted code, preserve the initiating identity, and recheck authorization immediately before execution. The model can propose work; it cannot choose its own credentials, expand target scope, or declare an interrupted scan successful.

This installment specifies the execution contract and assessment-job lifecycle. Offline scenarios cover out-of-scope denial, duplicate-request handling, queued revocation, and recovery after a lost worker response. A persistent fake worker can test these behaviors before a real scanner is connected, while Example Enterprise’s unresolved deployment evidence remains unchanged.

Authorize a specific operation, preserve its identity across retries, and reconcile uncertainty before starting more work.

In This Article

Introduction

A security agent submits an assessment request for the document portal. The worker accepts it, but the controller loses the response. The agent sees a timeout and asks to try again.

Did the assessment fail to start, remain active, or finish without its result reaching the controller? Another call cannot answer that question. It may create a second assessment against the same service.

The previous installment defined evaluation gates. This article implements a narrow part of the execution boundary those gates require: a constrained request, a durable job record, and explicit handling of uncertain downstream work. Scanner-specific commands and checks follow in the next installments.

The proposed offline implementation uses Python 3.11 or later, standard-library SQLite, synthetic identity and policy fixtures, and two local databases. Keep network connections, subprocesses, model calls, and credentials out of that first harness. The examples below are implementation contracts and expected outcomes, not a downloadable or independently verified controller.

Put the Model Beside the Controller, Not Above It

Separate analytical responsibilities from operational authority. Deterministic routing should handle known asset/profile relationships; a model call is unnecessary merely to select an already defined assessment path.

OWASP’s Excessive Agency guidance recommends narrowly scoped tools and permissions, with authorization enforced in downstream systems rather than entrusted to the language model. Apply that principle at both request admission and the execution boundary. OWASP Gen AI Security Project

ResponsibilityPermitted authority in the proposed designExplicit exclusion
Model-assisted analystRead permitted evidence and propose an assessmentNo credentials, approval rights, or arbitrary commands
Assessment controllerResolve policy, create jobs, enforce budgets, and reconcile executionCannot redefine approved policy or asset ownership
Worker and adapterPerform one approved profile against the resolved targetNo unrestricted discovery, deployment, or policy administration
Policy and credential servicesIssue bounded decisions and target-specific accessDo not accept model text as proof of identity or approval

These responsibilities can share a deployment initially, but do not give them one broadly privileged account. Preserve both the calling workload and any initiating user where delegated authority matters. Separately authorize reading job status and evidence; knowing a job ID must not reveal another tenant’s results.

The diagram shows where the proposal becomes an authorized job. The worker receives a resolved execution plan, not the model conversation.

Admission control and dispatch-time rechecks constrain a worker and scoped credential; uncertain execution is reconciled without a blind restart.

Expose an Assessment Contract, Not Scanner Syntax

Start with three logical operations: assessment.submit, assessment.status, and assessment.cancel. Submission returns a job reference. Status returns permitted observations. Cancellation requests a stop but does not certify that downstream work stopped.

Define assessment-request.schema.json to constrain submission arguments. This request selects a registered asset and a versioned local profile; it contains no address, command, credential, or output destination.

{
  "operation": "assessment.submit",
  "asset_id": "EE-APP-001",
  "profile_id": "fixture-observation-review",
  "profile_revision": "1",
  "expected_target_revision": "EE-DEP-002"
}

The controller attaches EE-EVT-001, EE-FIND-001, tenant, environment, caller, run, and action identifiers from protected workflow context. The model does not supply those authority-bearing fields. The expected deployment revision is a precondition, not evidence that its running artifact has been observed.

Use strict types, bounded sizes, enumerated operations, and rejection of unexpected fields. The example also rejects duplicate JSON keys. Schema validity establishes only that a request has the expected shape. OWASP’s Authorization Cheat Sheet recommends deny-by-default behavior and permission validation on every request; field validation does not replace that check. OWASP Cheat Sheet Series: Authorization Cheat Sheet

Resolve the Actual Target on the Server

Resolve the asset inside the authenticated tenant and environment, then obtain its approved endpoints or immutable input objects. An asset identifier is an indirection, not an exemption from authorization.

Bind the job to the relevant deployment, configuration, commit, or artifact revision. Recheck that relationship before dispatch. A changed deployment should cause a new applicability and authorization decision, not silently redirect an old job to whatever now occupies the address.

For EE-APP-001, the current artifact remains unresolved. The local scenario can review that evidence gap, but it cannot establish deployed software contents or repair a missing observation by inventing a digest.

Keep Arguments Separate from Execution Configuration

A live adapter should construct the supported invocation from a reviewed profile and validated inputs. Do not accept arbitrary flags, script locations, plugin URLs, environment variables, or caller-selected configuration files.

OWASP’s OS Command Injection Defense guidance distinguishes argument injection from shell metacharacter injection. Avoiding shell interpretation is necessary when using a command-line adapter, but it does not make arbitrary tool arguments safe. Prefer a supported bounded API; where a command is required, control the executable, argument structure, working directory, configuration discovery, and environment. OWASP Cheat Sheet Series: OS Command Injection Defense Cheat Sheet

The same contract can wrap an existing enterprise assessment product. Replacing its implementation should not change what the agent is authorized to request.

Make the Profile the Unit of Operational Permission

A profile should identify the assessment method, supported target class, exact adapter/tool configuration, required authentication, expected checks, and acceptable operational impact. Store tool and rule-feed identities separately because either can change the result.

Bind standing authorization or a specific approval to the target set, profile revision, environment, validity interval, and operating limits. Do not grant permission to “run Trivy” or “use ZAP” without defining the operation. This installment installs neither product and makes no claim about their check coverage.

The executable profile is intentionally smaller:

profile_id: fixture-observation-review
profile_revision: "1"
adapter: fake-worker/0.1.0
network_enabled: false
credentials_required: false
expected_checks:
  - current-deployment-evidence
max_dispatch_attempts: 1
queue_ttl_seconds: 60
execution_deadline_seconds: 30
max_active_global: 2
max_active_per_asset: 1
max_queued_per_subject: 4

These are teaching limits, not production sizing guidance. The controller enforces queue and start limits in its local state. Its deadline handling records a stop request; it does not terminate a real process.

For a live profile, add independently enforced request rates, total-request budgets, CPU, memory, disk, output-size, and maintenance-window limits. Apply limits across the logical job and its child work, not afresh for every retry. An unresolved job must retain its concurrency reservation until the system establishes whether work still exists.

Require an explicit authentication check before accepting authenticated assessment coverage. A login redirect, expired session, or permission error must not become an empty successful report. Fragile appliances, operational technology, and critical management systems need owner-approved methods rather than inheriting a general active-scanning profile.

Enforce Scope Where Network Connections Occur

A permitted starting address does not authorize every redirect, discovered link, imported API definition, or dependent service. Use exact destination and protocol rules, preserve hostname and certificate validation, and verify resolved addresses within the approved network boundary.

OWASP’s Server Side Request Forgery Prevention guidance recommends application and network controls, including care around redirects and DNS resolution. In this design, an out-of-scope destination becomes an exclusion or separately proposed target, not an automatic extension of the assessment. OWASP Cheat Sheet Series: Server Side Request Forgery Prevention Cheat Sheet

For web profiles, enforce relevant paths and methods as well as network destinations. A firewall rule allowing a shared service address cannot distinguish permitted application functions from prohibited ones.

Isolate workers by trust boundary and job. Provide only their required input mounts, scratch storage, network access, and evidence-write path. Keep package installation, rule downloads, and scanner updates on a reviewed intake path rather than allowing untrusted scan content to trigger them.

Kubernetes NetworkPolicy can contribute network controls when the installed networking solution implements it. Kubernetes documents that creating a policy without an implementing controller has no effect. Its transport-level controls also do not replace application-level scope validation. Test permitted and forbidden traffic from the actual worker environment before enabling a live profile. Kubernetes

Deliver credentials through the approved broker or workload-identity mechanism immediately before use. Keep them out of model context, queue bodies, command logs, and results. A read-only account still needs service-impact limits; permission to read does not define a safe request rate.

Give the Request, Job, and Attempt Different Identities

Use a stable logical action identity across repeated delivery, a durable job ID for its lifecycle, and a separate attempt identity when a genuinely new execution attempt is justified. Preserve remote operation IDs where the scanner supplies them.

Derive the idempotency key from protected workflow context. Bind it to the canonical request fingerprint. An identical replay returns the existing job; different parameters under the same action produce a conflict. A legitimate reassessment gets a new action through the workflow, not a model-generated key intended to evade deduplication.

AWS’s Making retries safe with idempotent APIs describes storing request parameters with the client request identifier and rejecting reuse with different intent. The lab applies that pattern to assessment admission. Amazon Web Services, Inc.

Commit the job before publishing work. A production design can use a transactional outbox, a database record committed with the job and later delivered to the queue, to avoid losing the handoff between those systems. Consumers still need duplicate handling: RabbitMQ documents redelivery and the possibility of duplicates after lost confirmations. rabbitmq.com

An offline implementation can use SQLite transactions and a unique operation-key constraint instead of a message broker. SQLite permits a single simultaneous write transaction; use that serialization to reserve job state and concurrency slots together. This design is not a demonstrated multi-node queue implementation. SQLite: Transaction

Likewise, a scheduler is not an exactly-once execution guarantee. Kubernetes explicitly warns that a Job’s program can sometimes start twice even with parallelism and completions set to one. Keep downstream operation identity and reconciliation inside the adapter contract. Kubernetes

Track Execution Separately from Findings

Do not compress the lifecycle into pending, success, and failure. The following states distinguish what the controller knows from what the worker may be doing.

Job stateMeaningNext permitted action
QUEUEDAccepted, not startedRecheck authority, target, profile, window, and budgets
DISPATCHINGStart intent persisted; acceptance may be uncertainObserve the same operation after interruption
RUNNINGMatching downstream operation observedMonitor deadline and collect bounded results
RECONCILE_REQUIREDActual execution state unresolvedQuery authoritative state; do not restart blindly
CANCEL_REQUESTEDStop requested, termination unconfirmedReconcile worker and delegated work
COMPLETEDRequired assessment evidence acceptedInterpret findings separately
PARTIAL or FAILEDCoverage or execution requirements unmetPreserve usable evidence and the gap
DENIED, EXPIRED, or CANCELLEDNo further execution under this jobPreserve whether work never started or stopped partway

Keep assessment_execution, coverage, authentication, and applicability distinct. A completed assessment can identify an affected asset. A completed review of missing observations can leave applicability unknown. An unavailable check needs an explicit coverage gap before a supported alternative is considered.

Validate returned job and target identities, profile/tool/rule revisions, check completeness, authentication outcome, and evidence references. Bound parser resources and output size. Neither exit code zero nor zero findings establishes that the required checks ran against the intended target.

Store raw permitted evidence separately from the model-facing summary. Scanner output is untrusted content; it cannot alter the policy, request another tool, or close EE-FIND-001 merely by saying that it should.

Validate Denial and Interrupted-Job Outcomes

Implement a controller, a persistent fake worker, the request schema, and lifecycle records as separate components. Build the denial and interruption cases below into automated tests before registering any real scanner adapter.

Give the controller and fake worker separate local databases, and retain reports without overwriting earlier runs. A worker ledger should record each accepted operation independently from controller state. Running both components under one local user tests persistence and state transitions; it does not create an independent security boundary.

The following fixture outcomes are acceptance criteria for that implementation. Execute them and retain the resulting records before claiming that the controller behaves correctly. Injected timestamps express logical test time, not performance measurements.

Deny the Unapproved Asset Before Dispatch

The first request substitutes EE-OUT-001 for EE-APP-001. Policy rejects it with NOT_AUTHORIZED. No job is admitted, and the fake-worker store records zero starts.

Submit the prohibited request directly to the boundary instead of relying on the model to refuse an instruction. Also test unexpected command and tenant fields, stale target revisions, and unapproved profiles.

A real integration must repeat the denial test with worker-side and network evidence. The local start counter does not prove that a deployed scanner cannot bypass its gateway.

Recover a Lost Acceptance Response Without Restarting

The allowed request creates a job linked to the existing event and finding. Repeating that request returns the same job.

The controller commits DISPATCHING. The fake worker records one accepted operation. The harness then simulates loss of the acceptance response, leaving the controller at RECONCILE_REQUIRED with unknown execution.

Close and reopen the controller database connection, query the existing operation, and require reconciliation to observe RUNNING. After the harness supplies fixture completion, require COMPLETED with exactly one accepted start in the worker ledger.

Only the evidence review completed. Applicability remains unknown because EE-DEP-002 still lacks established deployment evidence. Neither EE-CHG-001 nor EE-VER-001 is approved, deployed, or closed by this exercise.

An empty remote lookup must not automatically trigger a retry. It may reflect delay, an incomplete lookup, or a request still in transit. The example holds that uncertainty. A real adapter needs authoritative non-execution evidence and a mechanism preventing a late old request from starting before a replacement is safe.

Revoke Queued Authority and Preserve Late Results

A separate accepted job is revoked in the synthetic policy before dispatch. The recheck changes it to DENIED without another worker start. Policy-service failure similarly prevents dispatch; it does not fall back to a cached unconditional allow.

Keep cancellation after start in CANCEL_REQUESTED until the worker supplies a terminal receipt. Test a conservative local policy that retains late completion as partial. That policy is an explicit acceptance choice, not a rule requiring every late scanner result to be discarded.

Retry Only When the Previous Attempt Is Understood

Classify retries by where failure occurred. An explicitly unaccepted request may be eligible for a bounded retry after current authorization is checked. Invalid arguments, revoked authority, unsupported methods, and changed targets require correction or a new decision, not repeated submission.

After possible acceptance, query the existing operation. Retrying a status read and restarting an assessment are different actions. Use bounded backoff for observation failures while retaining the original execution identity and cumulative budget.

For production workers, use bounded leases, meaning permission to continue for a limited interval, and local deadline enforcement. Where the execution service supports fencing tokens, reject older generations at that service. A token checked only in the controller cannot stop an old worker that still has direct access to the target.

If the scanner cannot provide compatible idempotency, authoritative lookup, or safe cancellation, keep the profile single-owner and require manual reconciliation after ambiguous failure. Do not advertise exactly-once scanning around an interface that cannot support the claim.

Operate Revocation Beyond the Agent Process

Emergency control must stop new admission and dispatch, prevent credential renewal, request worker and child-job termination, and reconcile accepted external operations. Preserve evidence and distinguish a requested stop from confirmed cessation.

Do not assume a network-policy update closes every existing connection. Kubernetes documents that behavior for existing connections is implementation-dependent. Establish the actual termination and session-revocation behavior of the selected worker platform and target service. Kubernetes

Record the principal, environment, action/job/attempt identities, target revision, profile fingerprint, policy decision, timestamps, limits, remote receipts, and result validation. Keep credentials and unnecessary source bodies out of routine logs. Protect audit records separately from workers that could otherwise rewrite their history.

The platform owner operates the controller and reconciliation queue. Security engineering owns profile admission and policy. Application owners define safe operating windows and service-impact limits. Every unresolved execution needs an owner; monitor its age alongside queue delay, authentication failures, coverage gaps, and blocked requests.

Identity-provider validation, distributed delivery, real credential revocation, worker isolation, network limits, and scanner supervision require separate integration work and evidence. A passing local state-machine test must not mark those controls complete.

Conclusion

Controlled tool access is an execution contract that survives uncertain model output, repeated requests, and missing responses. It identifies the permitted asset and assessment, binds authority to current conditions, and preserves enough state to establish what actually happened.

Begin with the offline denial and interruption cases. Then admit one supported scanner adapter with verified scope, authentication, rate limits, cancellation behavior, and result handling. Expand only after the actual worker boundary passes its allowed and denied tests.

The next installment, Scan Source Code, Dependencies, Containers, and Infrastructure as Code, applies this contract to commit- and artifact-bound assessment in the build pipeline.

A timeout is a reason to establish execution state, not permission to run the assessment again.

External References

Continue reading

Cyberattack Tracker 2026: Confirmed Incidents, Attribution, and Connections

Track documented cyber incidents through November 18, 2026, separating confirmed exploitation, attempted access, AI involvement, attribution, and shared defensive patterns. Read the article

Leave a Comment