Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 120 additions & 0 deletions agent/src/approval_requests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

"""IAM-signed requests to the control-plane approval writer."""

import json
import os
import re
from http import HTTPStatus
from urllib.parse import urlsplit

import requests
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.exceptions import ClientError

from aws_session import get_session
from ua import sanitize_ua_value, static_user_agent_extra

API_ENV = "APPROVAL_REQUESTS_API_URL"


def configured() -> bool:
available = bool(os.environ.get(API_ENV))
if not available and os.environ.get("AGENT_SESSION_ROLE_ARN"):
raise RuntimeError(
"APPROVAL_REQUESTS_API_URL is required for cloud approval requests; "
"deploy matching CDK and worker images"
)
return available


def record_request(
operation: str,
task_id: str,
request_id: str,
*,
approval: dict | None = None,
reason: str | None = None,
) -> None:
"""Sign the task path with scoped credentials; never follow redirects."""
endpoint = os.environ.get(API_ENV, "").rstrip("/")
parsed = urlsplit(endpoint)
match = re.fullmatch(
r"[a-z0-9]+\.execute-api\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?", parsed.hostname or ""
)
if (
parsed.scheme != "https"
or not match
or parsed.username
or parsed.password
or parsed.port not in (None, 443)
or parsed.query
or parsed.fragment
or not re.fullmatch(r"/[A-Za-z0-9_-]+", parsed.path)
or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", task_id)
or operation not in {"create", "timeout"}
):
raise ValueError("Invalid approval request endpoint, task id or operation")
payload = {"operation": operation, "task_id": task_id, "request_id": request_id}
if approval is not None:
# Retention is set by the trusted writer, never by the worker.
payload["approval"] = {key: value for key, value in approval.items() if key != "ttl"}
if reason is not None:
payload["reason"] = reason
body = json.dumps(payload, separators=(",", ":")).encode()
user_agent = static_user_agent_extra()
app_id = os.environ.get("AWS_SDK_UA_APP_ID")
if app_id:
user_agent += f" app/{sanitize_ua_value(app_id)}"
url = f"{endpoint}/tasks/{task_id}"
request = AWSRequest(
method="POST",
url=url,
data=body,
headers={"Content-Type": "application/json", "User-Agent": user_agent},
)
credentials = get_session().get_credentials()
if credentials is None:
raise RuntimeError("Approval request credentials unavailable")
SigV4Auth(credentials.get_frozen_credentials(), "execute-api", match.group(1)).add_auth(request)
response = requests.post(
url,
data=body,
headers=dict(request.headers),
timeout=(5, 20),
allow_redirects=False,
)
try:
result = response.json()
except ValueError as exc:
raise RuntimeError(
f"Approval service returned invalid JSON (HTTP {response.status_code})"
) from exc
data = result.get("data") if isinstance(result, dict) else None
if response.status_code == HTTPStatus.OK and isinstance(data, dict) and data.get("ok") is True:
return
error = result.get("error") if isinstance(result, dict) else None
code = (
error.get("code", "ApprovalServiceUnavailable")
if isinstance(error, dict)
else "ApprovalServiceUnavailable"
)
details = error.get("details") if isinstance(error, dict) else None
reasons = details.get("cancellation_reasons", []) if isinstance(details, dict) else []
message = "Control plane did not acknowledge the approval write"
raise ClientError(
{
"Error": {
"Code": code,
"Message": message,
},
"CancellationReasons": reasons,
"ResponseMetadata": {
"HTTPStatusCode": response.status_code,
"RequestId": error.get("request_id") if isinstance(error, dict) else None,
},
},
"RecordApprovalRequest",
)
13 changes: 12 additions & 1 deletion agent/src/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import re
import time
from collections.abc import Callable
from datetime import UTC
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any

import nudge_reader
Expand Down Expand Up @@ -627,6 +627,17 @@ async def _handle_require_approval( # noqa: C901 -- 35 when the ceiling of 15 w
"user_id": user_id or "",
"repo": engine.repo,
}
# The trusted approval writer cross-checks the deadline against
# created_at + timeout_s, so the row carries it explicitly.
if effective_timeout > 0:
row["deadline_epoch"] = (
int(
datetime.strptime(row["created_at"], "%Y-%m-%dT%H:%M:%SZ")
.replace(tzinfo=UTC)
.timestamp()
)
+ effective_timeout
)

# Step 6 — bump counters BEFORE the write so cap/rate checks on
# subsequent gates reflect the attempt even if the DDB write itself
Expand Down
40 changes: 39 additions & 1 deletion agent/src/task_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import os
import time
from typing import TypedDict
from typing import NotRequired, TypedDict

from shell import log, log_error_cw

Expand All @@ -34,6 +34,7 @@ class ApprovalRow(TypedDict):
created_at: str
timeout_s: int
ttl: int
deadline_epoch: NotRequired[int]
user_id: str
repo: str

Expand Down Expand Up @@ -665,6 +666,9 @@ def transact_write_approval_request(
) -> None:
"""Atomically record a pending approval + transition the task to AWAITING_APPROVAL.

The trusted approval service performs the transaction when configured. Direct
DynamoDB is retained only for unscoped local/legacy deployments.

Two items:
1. Put on ``TaskApprovalsTable`` with ``ConditionExpression:
attribute_not_exists(request_id)`` — guards against ULID collisions
Expand All @@ -681,6 +685,23 @@ def transact_write_approval_request(
DDB-layer exceptions propagate so the hook's outer try/except can
fail-closed with a specific reason.
"""
import approval_requests

if approval_requests.configured():
try:
approval_requests.record_request(
"create", task_id, request_id, approval=dict(approval_row)
)
return
except Exception as exc:
if _extract_error_code(exc) == "TransactionCanceledException":
reasons = _extract_cancellation_reasons(exc)
raise ApprovalWriteError(
f"approval write cancelled: reasons={reasons}", cancellation_reasons=reasons
) from exc
raise
# Compatibility with unscoped legacy/local deployments. configured() rejects
# a missing service URL for cloud workers that use the session role.
task_table, approvals_table = _require_tables()
ddb = _get_ddb_client(client=client)

Expand Down Expand Up @@ -809,6 +830,23 @@ def best_effort_update_approval_status(
Returns ``True`` on successful write, ``False`` on
``ConditionalCheckFailedException``. All other errors propagate.
"""
import approval_requests

if new_status != "TIMED_OUT":
raise ValueError("Workers may record only non-human timeouts")
if approval_requests.configured():
try:
approval_requests.record_request("timeout", task_id, request_id, reason=reason)
return True
except Exception as exc:
reasons = _extract_cancellation_reasons(exc)
if _extract_error_code(exc) == "TransactionCanceledException" and (
reasons
and reasons[0].get("Code") == "ConditionalCheckFailed"
and all(reason.get("Code") == "None" for reason in reasons[1:])
):
return False
raise
_, approvals_table = _require_tables()
ddb = _get_ddb_client(client=client)

Expand Down
140 changes: 140 additions & 0 deletions agent/tests/test_approval_requests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

import json
from types import SimpleNamespace
from unittest.mock import MagicMock

import pytest
from botocore.credentials import Credentials
from botocore.exceptions import ClientError

import approval_requests as broker
import task_state


def pending_request() -> task_state.ApprovalRow:
return {
"task_id": "task",
"request_id": "request",
"tool_name": "Bash",
"tool_input_preview": '{"command":"git push"}',
"tool_input_sha256": "a" * 64,
"reason": "Protected operation",
"severity": "high",
"matching_rule_ids": ["protected"],
"status": "PENDING",
"created_at": "2026-09-18T00:00:00Z",
"timeout_s": 0,
"ttl": 1_800_000_000,
"user_id": "owner",
"repo": "owner/repo",
}


@pytest.fixture
def transport(monkeypatch):
monkeypatch.setenv(broker.API_ENV, "https://fixture.execute-api.us-east-1.amazonaws.com/v1/")
session = MagicMock()
session.get_credentials.return_value = Credentials(
"testing", "testing-secret", "testing-session"
)
monkeypatch.setattr(broker, "get_session", lambda: session)
post = MagicMock(
return_value=SimpleNamespace(status_code=200, json=lambda: {"data": {"ok": True}})
)
monkeypatch.setattr(broker.requests, "post", post)
return post


def test_scoped_signature_binds_the_task_path_and_does_not_redirect(transport):
broker.record_request("create", "task", "request", approval={"status": "PENDING"})
args, kwargs = transport.call_args
assert args == ("https://fixture.execute-api.us-east-1.amazonaws.com/v1/tasks/task",)
assert "execute-api/aws4_request" in kwargs["headers"]["Authorization"]
assert kwargs["headers"]["X-Amz-Security-Token"] == "testing-session"
assert "md/uksb-wt64nei4u6#agent" in kwargs["headers"]["User-Agent"]
assert kwargs["allow_redirects"] is False
assert json.loads(kwargs["data"])["task_id"] == "task"


@pytest.mark.parametrize(
"url",
[
"http://fixture.execute-api.us-east-1.amazonaws.com/v1",
"https://attacker.example/v1",
"https://fixture.execute-api.us-east-1.amazonaws.com/v1?redirect=elsewhere",
],
)
def test_rejects_untrusted_endpoints_before_signing(transport, monkeypatch, url):
monkeypatch.setenv(broker.API_ENV, url)
with pytest.raises(ValueError):
broker.record_request("create", "task", "request")
transport.assert_not_called()


def test_new_writers_use_service_instead_of_direct_dynamodb(transport, monkeypatch):
direct = MagicMock()
monkeypatch.setattr(task_state, "_get_ddb_client", direct)
task_state.transact_write_approval_request("task", "request", pending_request())
assert task_state.best_effort_update_approval_status("task", "request", "TIMED_OUT")
assert transport.call_count == 2
direct.assert_not_called()


@pytest.mark.parametrize("operation", ["create", "timeout"])
def test_cloud_worker_missing_endpoint_reports_configuration_error(monkeypatch, operation):
monkeypatch.delenv(broker.API_ENV, raising=False)
monkeypatch.setenv("AGENT_SESSION_ROLE_ARN", "arn:aws:iam::123456789012:role/session")
direct = MagicMock()
monkeypatch.setattr(task_state, "_get_ddb_client", direct)
with pytest.raises(RuntimeError, match=r"APPROVAL_REQUESTS_API_URL.*matching CDK"):
if operation == "create":
task_state.transact_write_approval_request("task", "request", pending_request())
else:
task_state.best_effort_update_approval_status("task", "request", "TIMED_OUT")
direct.assert_not_called()


@pytest.mark.parametrize("status", ["APPROVED", "DENIED", "PENDING", "CANCELLED"])
def test_worker_api_cannot_record_a_human_decision(transport, status):
with pytest.raises(ValueError, match="non-human timeouts"):
task_state.best_effort_update_approval_status("task", "request", status)
transport.assert_not_called()


def test_uncertain_service_write_does_not_fall_back_to_direct_dynamodb(transport, monkeypatch):
direct = MagicMock()
monkeypatch.setattr(task_state, "_get_ddb_client", direct)
transport.side_effect = TimeoutError("reply lost")
with pytest.raises(TimeoutError):
task_state.transact_write_approval_request("task", "request", pending_request())
direct.assert_not_called()


def test_timeout_race_preserves_human_winner_but_task_check_failure_is_not_benign(transport):
# Item 0 is the approval row (still PENDING?), item 1 the task check.
reasons = [{"Code": "ConditionalCheckFailed"}, {"Code": "None"}]
transport.return_value = SimpleNamespace(
status_code=409,
json=lambda: {
"error": {
"code": "TransactionCanceledException",
"details": {"cancellation_reasons": reasons},
},
},
)
# A human decision already replaced PENDING: the caller re-reads and honors it.
assert not task_state.best_effort_update_approval_status("task", "request", "TIMED_OUT")
# The task left AWAITING_APPROVAL: never silently treated as "human won".
reasons[:] = [{"Code": "None"}, {"Code": "ConditionalCheckFailed"}]
with pytest.raises(ClientError, match="did not acknowledge") as failure:
task_state.best_effort_update_approval_status("task", "request", "TIMED_OUT")
assert failure.value.response["Error"]["Code"] == "TransactionCanceledException"


def test_worker_never_sends_retention(transport):
broker.record_request("create", "task", "request", approval=dict(pending_request()))
sent = json.loads(transport.call_args.kwargs["data"])["approval"]
assert "ttl" not in sent
assert sent["status"] == "PENDING"
4 changes: 3 additions & 1 deletion agent/tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1823,6 +1823,7 @@ def test_wire_contract_is_exactly_the_documented_key_set(self):
"task_table_name": "TASK_TABLE_NAME",
"task_events_table_name": "TASK_EVENTS_TABLE_NAME",
"task_approvals_table_name": "TASK_APPROVALS_TABLE_NAME",
"approval_requests_api_url": "APPROVAL_REQUESTS_API_URL",
"nudges_table_name": "NUDGES_TABLE_NAME",
"log_group_name": "LOG_GROUP_NAME",
"artifacts_bucket_name": "ARTIFACTS_BUCKET_NAME",
Expand All @@ -1845,12 +1846,13 @@ def test_wire_contract_is_exactly_the_documented_key_set(self):
"linear_workload_identity_name": "LINEAR_WORKLOAD_IDENTITY_NAME",
}

def test_required_subset_is_exactly_the_four_run_blocking_keys(self):
def test_required_subset_is_exactly_the_run_blocking_keys(self):
assert (
frozenset(
{
"task_table_name",
"task_events_table_name",
"approval_requests_api_url",
"github_token_secret_arn",
"agent_session_role_arn",
}
Expand Down
Loading
Loading