Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(trading): opt-in TAP mode β€” full Alpaca key isolation (reads + orders + cancel) (#377)

0xZKnwfb6713e303b0
diff --git a/README.md b/README.md
index d4e7200f2..01d3ed779 100644
--- a/README.md
+++ b/README.md
@@ -1127,6 +1127,70 @@ The agent exposes connector-scoped tools named `trading_connections`,
Live-broker raw MCP tools are not registered directly as `mcp_<broker>_*`.
No IBKR order-placement tool is registered.
+### πŸ” TAP Mode β€” full credential isolation & human-approved writes
+
+**Opt-in, off by default.** If the `TAP_*` variables below are unset, the
+connector behaves exactly as before (direct broker SDK) β€” nothing changes.
+
+[TAP](https://tap.human.tech) (Tool Authorization Protocol) is a credential
+proxy: the agent never holds the raw broker API secret, and consequential writes
+are gated on **human approval**. With TAP mode on, **every** Alpaca call β€” order
+placement, cancel, and the reads (account/positions/orders/quote/bars) β€” is sent
+to the TAP proxy's `/forward` endpoint instead of the broker SDK; TAP injects the
+real key server-side, then forwards upstream.
+
+- The agent process holds **no Alpaca key at all** β€” and doesn't even need
+ `alpaca-py` β€” because the whole egress goes through TAP. The secret is
+ referenced by name (`<CREDENTIAL:alpaca.key_id>`) and TAP substitutes it.
+- **Writes block on human approval.** An order or cancel cannot reach the broker
+ without a human approving it; even a prompt-injected "buy now" is held, and
+ denying it means it never reaches Alpaca. Orders carry a deterministic
+ `client_order_id`, so an approval-race retry is deduplicated rather than
+ double-placed.
+- **Reads auto-approve.** Account/positions/orders/quote/bars are GETs that TAP
+ forwards without a human step β€” this is credential *isolation* (no key in the
+ process), not a gate, so there's ~zero added friction.
+- `allowed_hosts` on the TAP credential pins where the key may be sent, so a
+ tampered target is rejected (403) before injection.
+
+**Enable it:**
+
+1. In the TAP dashboard, create a **multi-secret** credential named `alpaca`
+ holding your Alpaca key pair as fields `key_id` and `secret_key`, assigned to
+ your agent, with allowed hosts `paper-api.alpaca.markets` (or the live host
+ `api.alpaca.markets`) **and** `data.alpaca.markets` (the market-data host used
+ by quote/bars). Use **separate TAP credentials for paper and live** (e.g.
+ `alpaca-paper` / `alpaca-live`, selected via `TAP_ALPACA_CREDENTIAL`), each
+ with `allowed_hosts` pinned to its own API host β€” TAP then structurally
+ refuses to send the paper key to the live host and vice versa, keeping the
+ paper/live separation crisp end to end.
+2. Add to `agent/.env`:
+
+| Variable | Required | Description |
+|----------|:--------:|-------------|
+| `TAP_PROXY_URL` | Yes | TAP proxy base URL (e.g. `https://proxy.tap.human.tech`) |
+| `TAP_AGENT_KEY` | Yes | Your TAP agent API key (secret) |
+| `TAP_ALPACA_CREDENTIAL` | No | TAP credential name for Alpaca (default `alpaca`) |
+| `TAP_APPROVAL_TIMEOUT` | No | Seconds to wait for a human decision (default `300`) |
+
+When a write is placed, approve or deny it in your TAP channel (Telegram /
+dashboard). An approved order/cancel is forwarded to Alpaca; a denied or
+timed-out one returns an error and is **never sent**.
+
+> **Known limitation β€” approval race.** If the human approves right at the
+> `TAP_APPROVAL_TIMEOUT` boundary, TAP may forward the order while the poll has
+> already given up: the gate then reports an error even though the order reached
+> the broker, and the `max_trades_per_day` counter under-counts by one. The
+> deterministic `client_order_id` keeps a retry from double-placing that order;
+> if you rely on a tight trades-per-day cap, check open orders after a TAP
+> timeout error before retrying.
+
+**Scope:** covers Alpaca **order placement, cancel, and all five reads** β€” the
+full connector egress, so the process holds no key on any path. HMAC-signed
+brokers (Binance/OKX) are follow-ups (client-side signing doesn't fit pure egress
+injection). The hooks are additive β€” they live inside the Alpaca connector and
+leave the live mandate gate unchanged.
+
### Config reference
| Field | Type | Default | Description |
diff --git a/agent/.env.example b/agent/.env.example
index b42f4950f..6ba52a2ff 100644
--- a/agent/.env.example
+++ b/agent/.env.example
@@ -194,3 +194,22 @@ TUSHARE_TOKEN=your-tushare-token
# When the ratio of LLM responses blocked by content moderation exceeds this
# threshold, the run card will warn you to switch providers.
# CONTENT_FILTER_WARNING_THRESHOLD=0.05
+
+# ============================================================================
+# TAP Mode β€” credential isolation for broker orders (optional, OFF by default)
+# ============================================================================
+# Route Alpaca order placement through the TAP proxy (https://tap.human.tech)
+# instead of the local broker SDK: the agent process holds no Alpaca key, and
+# every order is held for HUMAN APPROVAL before it reaches the broker. Leave
+# these unset for the default (direct broker SDK) behaviour.
+#
+# Setup: in the TAP dashboard create a multi-secret credential named `alpaca`
+# with fields `key_id` + `secret_key`, allowed host `paper-api.alpaca.markets`,
+# assigned to your agent. See the README "TAP Mode" section for details.
+#
+# TAP_PROXY_URL=https://proxy.tap.human.tech
+# TAP_AGENT_KEY=your-tap-agent-key
+# Credential name configured in TAP (default: alpaca)
+# TAP_ALPACA_CREDENTIAL=alpaca
+# Seconds to wait for a human approval decision (default: 300)
+# TAP_APPROVAL_TIMEOUT=300
diff --git a/agent/src/trading/connectors/alpaca/sdk.py b/agent/src/trading/connectors/alpaca/sdk.py
index 92e57ad59..26c55185e 100644
--- a/agent/src/trading/connectors/alpaca/sdk.py
+++ b/agent/src/trading/connectors/alpaca/sdk.py
@@ -1,28 +1,44 @@
-"""Read-only Alpaca connector via the official ``alpaca-py`` SDK.
-
-Wraps ``TradingClient`` (account/positions/orders) and
-``StockHistoricalDataClient`` (quote/bars) for the five read operations. No
-order-placement method is exposed here.
-
-Paper-vs-live is structural: ``profile == "paper"`` constructs the client with
-``paper=True`` (host ``paper-api.alpaca.markets``) using the paper key pair; a
-live profile uses ``paper=False`` (host ``api.alpaca.markets``) with the live
-key pair. A paper key cannot reach the live host, so the configured profile β€”
-recorded as ``paper`` in every payload β€” is the authoritative discriminator.
+"""Alpaca connector via the official ``alpaca-py`` SDK β€” with opt-in TAP routing.
+
+Exposes the five reads (account/positions/orders via ``TradingClient``,
+quote/bars via ``StockHistoricalDataClient``) plus order placement and cancel.
+
+Credential isolation (opt-in): when TAP is configured (``TAP_PROXY_URL`` +
+``TAP_AGENT_KEY``), the **entire** broker egress β€” reads, order placement, and
+cancel β€” is routed through the TAP proxy instead of the SDK. Writes (place /
+cancel) block on human approval; reads are GETs that TAP auto-approves. The
+Alpaca secret then lives only in TAP (referenced by ``<CREDENTIAL:...>``
+placeholders, injected server-side), so the agent process holds no key and needs
+no ``alpaca-py``. With no TAP env the connector keeps its unchanged direct-SDK
+path.
+
+Paper-vs-live is structural: ``profile == "paper"`` uses host
+``paper-api.alpaca.markets`` and the paper key pair; a live profile uses
+``api.alpaca.markets`` and the live key pair. A paper key cannot reach the live
+host, so the configured profile β€” recorded as ``paper`` in every payload β€” is the
+authoritative discriminator.
"""
from __future__ import annotations
+import hashlib
import json
+import os
from dataclasses import asdict, dataclass
from pathlib import Path
from types import ModuleType
from typing import Any, Mapping
from src.config.paths import get_runtime_root
+from src.trading import tap_forward
CONFIG_FILENAME = "alpaca.json"
+# Name of the TAP credential holding the Alpaca {key_id, secret_key} pair.
+# Overridable so a deployment can use a differently-named credential.
+TAP_ALPACA_CREDENTIAL_ENV = "TAP_ALPACA_CREDENTIAL"
+DEFAULT_TAP_ALPACA_CREDENTIAL = "alpaca"
+
PROFILE_ENVIRONMENTS = {
"paper": "paper",
"live-readonly": "live",
@@ -31,6 +47,11 @@ PROFILE_ENVIRONMENTS = {
PAPER_HOST = "https://paper-api.alpaca.markets"
LIVE_HOST = "https://api.alpaca.markets"
+# Market-data API host (quote/bars). Same host for paper and live β€” only the
+# trading API splits paper/live β€” reached with the same key pair, so the one
+# ``alpaca`` TAP credential covers it (with ``data.alpaca.markets`` as a second
+# ``allowed_hosts`` entry).
+DATA_HOST = "https://data.alpaca.markets"
class AlpacaDependencyError(RuntimeError):
@@ -158,6 +179,75 @@ def save_config(config: AlpacaConfig) -> Path:
return path
+# ---------------------------------------------------------------------------
+# TAP routing (opt-in credential isolation)
+# ---------------------------------------------------------------------------
+
+# The REST market-data API abbreviates quote/bar keys where the alpaca-py models
+# expose full names; the mappers read the full names, so quote/bars responses
+# fetched via TAP are aliased back before mapping. The trading API (account /
+# positions / orders) already uses the full names, so it needs no aliasing.
+_QUOTE_KEY_ALIASES = {"bp": "bid_price", "ap": "ask_price", "bs": "bid_size", "as": "ask_size", "t": "timestamp"}
+_BAR_KEY_ALIASES = {"t": "timestamp", "o": "open", "h": "high", "l": "low", "c": "close", "v": "volume"}
+
+
+def _tap_cred_headers() -> dict[str, str]:
+ """Placeholder headers TAP resolves server-side β€” never a raw key.
+
+ The one multi-secret ``alpaca`` credential (fields ``key_id`` + ``secret_key``)
+ backs both the order write and every read; the name is overridable via
+ ``TAP_ALPACA_CREDENTIAL``.
+ """
+ credential = os.environ.get(TAP_ALPACA_CREDENTIAL_ENV, DEFAULT_TAP_ALPACA_CREDENTIAL) # noqa: env-gate β€” mirrors tap_forward.py, bootstrap-order independent
+ return {
+ "APCA-API-KEY-ID": f"<CREDENTIAL:{credential}.key_id>",
+ "APCA-API-SECRET-KEY": f"<CREDENTIAL:{credential}.secret_key>",
+ }
+
+
+def _read_via_tap(target: str) -> Any:
+ """GET ``target`` through the TAP proxy and return the parsed JSON body.
+
+ Reads are GET, which TAP auto-approves (no human step): this path is for
+ *credential isolation*, not gating β€” the agent process holds no Alpaca key,
+ TAP injects the secret from ``<CREDENTIAL:alpaca.*>`` placeholders server-side.
+ Fails closed: raises on any TAP/upstream error, mirroring the direct-SDK path
+ (which also raises on an API error), so read callers handle failure uniformly.
+ """
+ result = tap_forward.forward(target, "GET", None, _tap_cred_headers())
+ if not result.get("ok"):
+ reason = result.get("error") or result.get("decision") or "read not forwarded by TAP"
+ raise RuntimeError(f"TAP read failed: {reason}")
+ payload = result.get("body")
+ if isinstance(payload, str):
+ try:
+ payload = json.loads(payload)
+ except ValueError as exc:
+ raise RuntimeError(f"TAP read returned a non-JSON body: {exc}") from exc
+ return payload
+
+
+def _rename_keys(item: Any, aliases: Mapping[str, str]) -> dict[str, Any]:
+ """Alias Alpaca market-data short keys to the model names the mappers expect
+ (``bp`` -> ``bid_price``, ``o`` -> ``open`` …); non-mappings become ``{}``."""
+ if not isinstance(item, Mapping):
+ return {}
+ out = dict(item)
+ for short, full in aliases.items():
+ if short in item:
+ out[full] = item[short]
+ return out
+
+
+def _rest_timeframe(period: str) -> str:
+ """Canonical period token -> Alpaca REST timeframe string (mirrors
+ :func:`_timeframe`). Case-sensitive: ``1m`` is one minute, ``1M`` one month."""
+ return {
+ "1m": "1Min", "5m": "5Min", "15m": "15Min", "30m": "30Min",
+ "1h": "1Hour", "4h": "4Hour", "1w": "1Week", "1M": "1Month",
+ }.get(period.strip(), "1Day")
+
+
def alpaca_available() -> bool:
"""Return whether the optional ``alpaca-py`` SDK can be imported."""
try:
@@ -174,6 +264,7 @@ def check_status(config: AlpacaConfig | None = None) -> dict[str, Any]:
"status": "ok",
"config": _public_config(cfg),
"sdk": {"package": "alpaca-py", "installed": alpaca_available()},
+ "tap": tap_forward.tap_enabled(),
"paper_guard": "host_separated",
"host": cfg.host,
}
@@ -184,7 +275,7 @@ def check_status(config: AlpacaConfig | None = None) -> dict[str, Any]:
report["error"] = f"Alpaca connector not configured: missing {', '.join(missing)}."
return report
- if not report["sdk"]["installed"]:
+ if not tap_forward.tap_enabled() and not report["sdk"]["installed"]:
report["status"] = "error"
report["error"] = "Optional dependency missing: install with `pip install alpaca-py`."
return report
@@ -207,8 +298,10 @@ def check_status(config: AlpacaConfig | None = None) -> dict[str, Any]:
def get_account_snapshot(config: AlpacaConfig | None = None) -> dict[str, Any]:
"""Fetch account summary for the configured account."""
cfg = config or load_config()
- client = _trading_client(cfg)
- account = client.get_account()
+ if tap_forward.tap_enabled():
+ account = _read_via_tap(f"{cfg.host}/v2/account")
+ else:
+ account = _trading_client(cfg).get_account()
return {
"status": "ok",
"profile": cfg.profile,
@@ -231,8 +324,10 @@ def get_account_snapshot(config: AlpacaConfig | None = None) -> dict[str, Any]:
def get_positions(config: AlpacaConfig | None = None) -> dict[str, Any]:
"""Fetch current positions for the configured account."""
cfg = config or load_config()
- client = _trading_client(cfg)
- positions = client.get_all_positions()
+ if tap_forward.tap_enabled():
+ positions = _read_via_tap(f"{cfg.host}/v2/positions")
+ else:
+ positions = _trading_client(cfg).get_all_positions()
rows = [_position_to_dict(item) for item in _as_iter(positions)]
return {"status": "ok", "profile": cfg.profile, "is_paper": cfg.is_paper, "positions": rows}
@@ -240,13 +335,21 @@ def get_positions(config: AlpacaConfig | None = None) -> dict[str, Any]:
def get_open_orders(config: AlpacaConfig | None = None, *, include_executions: bool = False) -> dict[str, Any]:
"""Fetch open orders and, optionally, recently filled orders."""
cfg = config or load_config()
- client = _trading_client(cfg)
- _require_alpaca()
- from alpaca.trading.requests import GetOrdersRequest # type: ignore
- from alpaca.trading.enums import QueryOrderStatus # type: ignore
-
- open_req = GetOrdersRequest(status=QueryOrderStatus.OPEN)
- open_orders = client.get_orders(filter=open_req)
+ if tap_forward.tap_enabled():
+ open_orders = _read_via_tap(f"{cfg.host}/v2/orders?status=open")
+ closed = _read_via_tap(f"{cfg.host}/v2/orders?status=closed") if include_executions else []
+ else:
+ client = _trading_client(cfg)
+ _require_alpaca()
+ from alpaca.trading.requests import GetOrdersRequest # type: ignore
+ from alpaca.trading.enums import QueryOrderStatus # type: ignore
+
+ open_orders = client.get_orders(filter=GetOrdersRequest(status=QueryOrderStatus.OPEN))
+ closed = (
+ client.get_orders(filter=GetOrdersRequest(status=QueryOrderStatus.CLOSED))
+ if include_executions
+ else []
+ )
result: dict[str, Any] = {
"status": "ok",
"profile": cfg.profile,
@@ -254,22 +357,26 @@ def get_open_orders(config: AlpacaConfig | None = None, *, include_executions: b
"open_orders": [_order_to_dict(item) for item in _as_iter(open_orders)],
}
if include_executions:
- closed_req = GetOrdersRequest(status=QueryOrderStatus.CLOSED)
- closed = client.get_orders(filter=closed_req)
- result["executions"] = [_order_to_dict(item) for item in _as_iter(closed) if _obj_get(item, "filled_qty")]
+ result["executions"] = [
+ _order_to_dict(item) for item in _as_iter(closed) if _obj_get(item, "filled_qty")
+ ]
return result
def get_quote(symbol: str, *, config: AlpacaConfig | None = None, **_: Any) -> dict[str, Any]:
"""Fetch a latest quote snapshot for ``symbol``."""
cfg = config or load_config()
- client = _data_client(cfg)
- from alpaca.data.requests import StockLatestQuoteRequest # type: ignore
-
clean = symbol.strip().upper()
- req = StockLatestQuoteRequest(symbol_or_symbols=clean, feed=_data_feed(cfg))
- quotes = client.get_stock_latest_quote(req)
- quote = quotes.get(clean) if isinstance(quotes, Mapping) else _obj_get(quotes, clean)
+ if tap_forward.tap_enabled():
+ payload = _read_via_tap(f"{DATA_HOST}/v2/stocks/{clean}/quotes/latest?feed={cfg.feed}")
+ quote: Any = _rename_keys(_obj_get(payload, "quote"), _QUOTE_KEY_ALIASES)
+ else:
+ client = _data_client(cfg)
+ from alpaca.data.requests import StockLatestQuoteRequest # type: ignore
+
+ req = StockLatestQuoteRequest(symbol_or_symbols=clean, feed=_data_feed(cfg))
+ quotes = client.get_stock_latest_quote(req)
+ quote = quotes.get(clean) if isinstance(quotes, Mapping) else _obj_get(quotes, clean)
return {
"status": "ok",
"symbol": clean,
@@ -293,15 +400,23 @@ def get_historical_bars(
) -> dict[str, Any]:
"""Fetch historical bars for ``symbol`` (``period`` is a canonical token)."""
cfg = config or load_config()
- client = _data_client(cfg)
- from alpaca.data.requests import StockBarsRequest # type: ignore
- from alpaca.data.timeframe import TimeFrame, TimeFrameUnit # type: ignore
-
clean = symbol.strip().upper()
- timeframe = _timeframe(period, TimeFrame, TimeFrameUnit)
- req = StockBarsRequest(symbol_or_symbols=clean, timeframe=timeframe, limit=int(limit), feed=_data_feed(cfg))
- bars = client.get_stock_bars(req)
- rows = bars.data.get(clean, []) if hasattr(bars, "data") else _as_iter(bars)
+ if tap_forward.tap_enabled():
+ url = (
+ f"{DATA_HOST}/v2/stocks/{clean}/bars"
+ f"?timeframe={_rest_timeframe(period)}&limit={int(limit)}&feed={cfg.feed}"
+ )
+ payload = _read_via_tap(url)
+ rows: Any = [_rename_keys(item, _BAR_KEY_ALIASES) for item in _as_iter(_obj_get(payload, "bars") or [])]
+ else:
+ client = _data_client(cfg)
+ from alpaca.data.requests import StockBarsRequest # type: ignore
+ from alpaca.data.timeframe import TimeFrame, TimeFrameUnit # type: ignore
+
+ timeframe = _timeframe(period, TimeFrame, TimeFrameUnit)
+ req = StockBarsRequest(symbol_or_symbols=clean, timeframe=timeframe, limit=int(limit), feed=_data_feed(cfg))
+ bars = client.get_stock_bars(req)
+ rows = bars.data.get(clean, []) if hasattr(bars, "data") else _as_iter(bars)
return {
"status": "ok",
"symbol": clean,
@@ -394,6 +509,22 @@ def place_order(
if limit_value <= 0:
return {"status": "error", "error": "limit_price must be positive"}
+ # Credential isolation (opt-in): when TAP is configured, route the order
+ # through the TAP proxy β€” human-approved, with the broker secret injected
+ # server-side β€” instead of the local Alpaca SDK. No TAP env => unchanged
+ # direct-SDK path below. All input validation above still applies.
+ if tap_forward.tap_enabled():
+ return _submit_via_tap(
+ cfg,
+ symbol=clean_symbol,
+ side=side_token,
+ quantity=qty_value,
+ notional=notional_value,
+ order_type=type_token,
+ limit_price=limit_value,
+ time_in_force=tif_token,
+ )
+
try:
client = _trading_client(cfg)
from alpaca.trading.enums import OrderSide, TimeInForce # type: ignore
@@ -445,6 +576,94 @@ def place_order(
}
+def _submit_via_tap(
+ cfg: AlpacaConfig,
+ *,
+ symbol: str,
+ side: str,
+ quantity: float | None,
+ notional: float | None,
+ order_type: str,
+ limit_price: float | None,
+ time_in_force: str,
+) -> dict[str, Any]:
+ """Place the order through the TAP proxy instead of the Alpaca SDK.
+
+ The agent process holds no Alpaca secret on this path: the order is POSTed to
+ TAP ``/forward`` with ``<CREDENTIAL:alpaca.key_id>`` / ``.secret_key``
+ placeholders, which TAP injects into the ``APCA-API-*`` headers server-side
+ after a human approves. The upstream host is the connector's own
+ ``cfg.host`` (operator-controlled, not agent-controlled), and the TAP
+ credential's ``allowed_hosts`` pins it β€” a tampered target is rejected before
+ injection. Returns the same envelope as the direct-SDK path, so the paper
+ path and the live mandate gate are unchanged.
+ """
+ order: dict[str, Any] = {
+ "symbol": symbol,
+ "side": side,
+ "type": order_type,
+ "time_in_force": time_in_force,
+ }
+ if quantity is not None:
+ order["qty"] = str(quantity)
+ else:
+ order["notional"] = str(notional)
+ if order_type == "limit":
+ order["limit_price"] = str(limit_price)
+
+ # Idempotency: a deterministic client_order_id derived from the order
+ # content, so a retry after an approval-race / poll timeout (where TAP
+ # forwarded the order but the agent saw a timeout) is deduplicated by Alpaca
+ # β€” a duplicate id is rejected, never double-placed. Trade-off: two
+ # intentionally-identical orders collide; vary any field for a real duplicate.
+ order["client_order_id"] = "tap-" + hashlib.sha256(
+ "|".join(
+ str(x)
+ for x in (cfg.profile, symbol, side, quantity, notional, order_type, limit_price, time_in_force)
+ ).encode()
+ ).hexdigest()[:24]
+
+ cred_headers = _tap_cred_headers()
+ target = f"{cfg.host}/v2/orders"
+
+ result = tap_forward.forward(target, "POST", json.dumps(order), cred_headers)
+
+ if not result.get("ok"):
+ decision = result.get("decision")
+ reason = result.get("error") or {
+ "denied": "order denied by approver",
+ "timeout": "approval timed out",
+ "timed_out": "approval timed out",
+ }.get(decision, "order not forwarded by TAP")
+ return {"status": "error", "error": f"TAP: {reason}", "tap_decision": decision}
+
+ payload = result.get("body")
+ if isinstance(payload, str):
+ try:
+ payload = json.loads(payload)
+ except ValueError:
+ payload = {}
+ if not isinstance(payload, dict):
+ payload = {}
+
+ return {
+ "status": "ok",
+ "order_id": str(payload.get("id", "")),
+ "symbol": symbol,
+ "side": side,
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "order_type": order_type,
+ "time_in_force": time_in_force,
+ "quantity": quantity,
+ "notional": notional,
+ "limit_price": limit_price,
+ "order_status": str(payload.get("status", "")),
+ "filled_qty": payload.get("filled_qty"),
+ "via": "tap",
+ }
+
+
def cancel_order(
config: AlpacaConfig | None = None,
order_id: str = "",
@@ -470,6 +689,14 @@ def cancel_order(
if not clean_id:
return {"status": "error", "error": "order_id is required"}
+ clean_symbol = symbol.strip().upper() if isinstance(symbol, str) and symbol.strip() else None
+
+ # Credential isolation (opt-in): a cancel mutates broker state, so β€” like
+ # order placement β€” route it through TAP for human approval + server-side key
+ # injection when configured. No TAP env => unchanged direct-SDK path below.
+ if tap_forward.tap_enabled():
+ return _cancel_via_tap(cfg, clean_id, clean_symbol)
+
try:
client = _trading_client(cfg)
client.cancel_order_by_id(clean_id)
@@ -481,7 +708,7 @@ def cancel_order(
return {
"status": "ok",
"order_id": clean_id,
- "symbol": symbol.strip().upper() if isinstance(symbol, str) and symbol.strip() else None,
+ "symbol": clean_symbol,
"side": None,
"profile": cfg.profile,
"is_paper": cfg.is_paper,
@@ -489,6 +716,37 @@ def cancel_order(
}
+def _cancel_via_tap(cfg: AlpacaConfig, order_id: str, symbol: str | None) -> dict[str, Any]:
+ """Cancel an order through the TAP proxy instead of the Alpaca SDK.
+
+ A cancel mutates broker state (``DELETE /v2/orders/{id}``), so β€” like order
+ placement β€” it is human-approved and the broker secret is injected
+ server-side; the agent process holds no key. Alpaca returns 204 No Content on
+ success. Fails closed on deny/timeout, mirroring :func:`_submit_via_tap`.
+ """
+ target = f"{cfg.host}/v2/orders/{order_id}"
+ result = tap_forward.forward(target, "DELETE", None, _tap_cred_headers())
+ if not result.get("ok"):
+ decision = result.get("decision")
+ reason = result.get("error") or {
+ "denied": "cancel denied by approver",
+ "timeout": "approval timed out",
+ "timed_out": "approval timed out",
+ }.get(decision, "cancel not forwarded by TAP")
+ return {"status": "error", "error": f"TAP: {reason}", "tap_decision": decision}
+
+ return {
+ "status": "ok",
+ "order_id": order_id,
+ "symbol": symbol,
+ "side": None,
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "cancelled": True,
+ "via": "tap",
+ }
+
+
def _timeframe(period: str, time_frame_cls: Any, unit_cls: Any) -> Any:
"""Map a canonical period token to an Alpaca ``TimeFrame``.
@@ -543,6 +801,10 @@ def _data_feed(cfg: AlpacaConfig):
def _missing_fields(cfg: AlpacaConfig) -> list[str]:
+ # On the TAP path the process holds no key β€” the secret lives in TAP and is
+ # injected server-side β€” so the local key pair is not required for readiness.
+ if tap_forward.tap_enabled():
+ return []
missing = []
if not cfg.api_key:
missing.append("api_key")
diff --git a/agent/src/trading/tap_forward.py b/agent/src/trading/tap_forward.py
new file mode 100644
index 000000000..e520ebd31
--- /dev/null
+++ b/agent/src/trading/tap_forward.py
@@ -0,0 +1,233 @@
+"""Route a broker request through the TAP proxy (Tool Authorization Protocol).
+
+Credential-isolation hook. When TAP is configured (``TAP_PROXY_URL`` +
+``TAP_AGENT_KEY`` present in the environment β€” e.g. loaded from the project
+``.env``), outbound broker calls are sent to TAP's ``/forward`` endpoint
+instead of hitting the broker directly. The real
+broker secret lives inside TAP and is referenced only by
+``<CREDENTIAL:name.field>`` placeholders; TAP substitutes the real value
+server-side after policy enforcement + human approval, then forwards upstream.
+
+Security properties this gives the agent process:
+ * it never holds the broker API secret β€” only a policy-scoped TAP agent key;
+ * writes (POST/PUT/PATCH/DELETE) block on human approval before reaching the
+ broker, so a prompt-injected order cannot execute without a human;
+ * ``allowed_hosts`` on the TAP credential pins where the secret may be sent,
+ so a tampered target is rejected (403) before injection.
+
+Additive and opt-in: if TAP is not configured, :func:`tap_enabled` returns
+False and callers keep their existing direct-SDK path unchanged.
+
+Stdlib only β€” no new dependencies.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+import urllib.error
+import urllib.request
+from pathlib import Path
+from typing import Any, Mapping
+
+_DEFAULT_APPROVAL_TIMEOUT = 300 # seconds to wait for a human approval decision
+_FORWARD_POST_TIMEOUT = 60 # the POST returns 202 fast; approval is polled async
+_POLL_INTERVAL = 2
+
+
+# Project .env locations, mirroring Vibe-Trading's own loader
+# (src/providers/llm.py ``_ENV_CANDIDATES``): first existing file wins.
+# tap_forward.py lives at agent/src/trading/ -> parents[2] is the agent dir.
+_ENV_CANDIDATES = (
+ Path.home() / ".vibe-trading" / ".env",
+ Path(__file__).resolve().parents[2] / ".env", # agent/.env
+ Path.cwd() / ".env",
+)
+
+
+def _load_env_into_environ() -> None:
+ """Populate ``os.environ`` with ``TAP_*`` vars from the project ``.env`` files.
+
+ Scans **every** candidate (not just the first that exists) and only sets keys
+ prefixed ``TAP_`` β€” so if one ``.env`` holds the app's config while a
+ different one holds the TAP vars, both are honoured. (Returning after the
+ first existing file would leave TAP silently disabled when e.g.
+ ``~/.vibe-trading/.env`` exists without the TAP vars but ``agent/.env`` has
+ them.) ``setdefault`` never overrides a real environment variable β€” e.g. one
+ injected by docker-compose ``env_file`` β€” and scoping to ``TAP_`` leaves the
+ app's own env loading untouched. Secret values are not logged.
+ """
+ for candidate in _ENV_CANDIDATES:
+ try:
+ if not candidate.exists():
+ continue
+ for raw in candidate.read_text(encoding="utf-8").splitlines():
+ line = raw.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ name, value = line.split("=", 1)
+ name = name.strip()
+ if name.startswith("TAP_"):
+ os.environ.setdefault(name, value.strip().strip('"').strip("'"))
+ except (OSError, UnicodeDecodeError):
+ # An unreadable or non-UTF-8 .env must not take down every
+ # read/order call β€” skip it, exactly like a missing file.
+ continue
+
+
+def _resolve_config() -> tuple[str, str]:
+ """Return ``(base_url, agent_key)`` from the environment / project ``.env``.
+
+ Reads ``TAP_PROXY_URL`` + ``TAP_AGENT_KEY`` from ``os.environ``. If they are
+ not already present (e.g. when invoked outside the app's normal startup),
+ the project ``.env`` is loaded once. The agent key is a secret β€” read here,
+ never logged.
+ """
+ # Deliberately independent of EnvConfig: this module must keep working
+ # when invoked outside the app's normal startup/config bootstrap (see
+ # module docstring + _load_env_into_environ above).
+ base = os.environ.get("TAP_PROXY_URL") # noqa: env-gate β€” bootstrap-order independent, see docstring
+ key = os.environ.get("TAP_AGENT_KEY") # noqa: env-gate β€” bootstrap-order independent, see docstring
+ if not (base and key):
+ _load_env_into_environ()
+ base = os.environ.get("TAP_PROXY_URL") # noqa: env-gate β€” bootstrap-order independent, see docstring
+ key = os.environ.get("TAP_AGENT_KEY") # noqa: env-gate β€” bootstrap-order independent, see docstring
+ return (base or "").rstrip("/"), (key or "")
+
+
+def tap_enabled() -> bool:
+ """True when a TAP proxy URL and agent key are both configured."""
+ base, key = _resolve_config()
+ return bool(base and key)
+
+
+def forward(
+ target_url: str,
+ method: str,
+ body: str | None,
+ credential_headers: Mapping[str, str],
+ *,
+ extra_headers: Mapping[str, str] | None = None,
+ timeout: float | None = None,
+) -> dict[str, Any]:
+ """Send one request to upstream ``target_url`` via TAP ``/forward``.
+
+ ``credential_headers`` carry ``<CREDENTIAL:name.field>`` placeholders (never
+ real secrets) that TAP resolves server-side. Writes block on human approval;
+ this polls until the request is forwarded, denied, timed out, or errors.
+
+ Never raises for a broker/approval outcome β€” returns a structured result::
+
+ {"ok": bool, "decision": str | None, "status": int | None,
+ "body": str | dict | None, "error": str | None}
+
+ ``ok`` is True only when TAP forwarded the request upstream AND the upstream
+ returned a 2xx. Fail-closed otherwise.
+ """
+ base, key = _resolve_config()
+ if not (base and key):
+ return _result(False, error="TAP not configured")
+
+ timeout = timeout if timeout is not None else _env_timeout()
+ headers = {
+ "X-TAP-Key": key,
+ "X-TAP-Target": target_url,
+ "X-TAP-Method": method.upper(),
+ "Content-Type": "application/json",
+ }
+ headers.update(dict(credential_headers or {}))
+ headers.update(dict(extra_headers or {}))
+
+ data = body.encode("utf-8") if body else None
+ code, text = _http("POST", f"{base}/forward", headers, data, _FORWARD_POST_TIMEOUT)
+ parsed = _json(text)
+
+ # Immediate result (auto-approved read) or an error from TAP itself.
+ if code != 202:
+ ok = 200 <= code < 300
+ return _result(ok, decision="immediate", status=code, body=parsed,
+ error=None if ok else _err(parsed))
+
+ # Write path: approval required -> poll until a terminal decision.
+ # Build the poll URL against the CONFIGURED base only. We never send the
+ # agent key (X-TAP-Key) to an absolute URL taken from the response body β€”
+ # a tampered/malicious response could otherwise exfiltrate the key. We
+ # accept a server-provided path only if it is relative (starts with "/").
+ txn = parsed.get("txn_id") if isinstance(parsed, dict) else None
+ poll = parsed.get("poll_url") if isinstance(parsed, dict) else None
+ if isinstance(txn, str) and txn:
+ poll_url = f"{base}/agent/approvals/{txn}"
+ elif isinstance(poll, str) and poll.startswith("/") and not poll.startswith("//"):
+ # A single leading "/" only: "//host/path" is protocol-relative and
+ # would resolve to the attacker's host under URL joining.
+ poll_url = f"{base}{poll}"
+ else:
+ return _result(False, decision="pending", status=code, body=parsed,
+ error="approval response missing a usable txn_id / relative poll path")
+
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ time.sleep(_POLL_INTERVAL)
+ _, ptext = _http("GET", poll_url, {"X-TAP-Key": key}, None, 30)
+ pr = _json(ptext)
+ state = (pr.get("status") if isinstance(pr, dict) else "") or ""
+ if state == "forwarded":
+ inner = (pr.get("response") if isinstance(pr, dict) else None) or {}
+ up_status = inner.get("status")
+ ok = isinstance(up_status, int) and 200 <= up_status < 300
+ return _result(ok, decision="forwarded", status=up_status,
+ body=inner.get("body"), error=None if ok else "upstream error")
+ if state in ("denied", "timed_out", "error"):
+ return _result(False, decision=state, body=pr, error=_err(pr) or state)
+ # Known race: an approval landing right at this deadline may have been
+ # forwarded upstream even though we report an error here (so any caller-side
+ # counter, e.g. max_trades_per_day, can under-count by one). Callers dedup
+ # retries via a deterministic client_order_id; see README "TAP Mode".
+ return _result(False, decision="timeout",
+ error=f"no approval decision within {int(timeout)}s")
+
+
+# --------------------------------------------------------------------------- #
+# Internals
+# --------------------------------------------------------------------------- #
+
+
+def _http(method: str, url: str, headers: dict[str, str], data: bytes | None, timeout: float):
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ return resp.status, resp.read().decode("utf-8", "replace")
+ except urllib.error.HTTPError as exc:
+ return exc.code, exc.read().decode("utf-8", "replace")
+ except urllib.error.URLError as exc:
+ return 0, json.dumps({"error": f"connection failed: {exc.reason}"})
+
+
+def _json(text: str) -> Any:
+ try:
+ return json.loads(text)
+ except (ValueError, TypeError):
+ return text
+
+
+def _result(ok: bool, *, decision: str | None = None, status: int | None = None,
+ body: Any = None, error: str | None = None) -> dict[str, Any]:
+ return {"ok": ok, "decision": decision, "status": status, "body": body, "error": error}
+
+
+def _env_timeout() -> float:
+ raw = os.environ.get("TAP_APPROVAL_TIMEOUT", "") # noqa: env-gate β€” bootstrap-order independent, see module docstring
+ try:
+ return float(raw) if raw else float(_DEFAULT_APPROVAL_TIMEOUT)
+ except ValueError:
+ return float(_DEFAULT_APPROVAL_TIMEOUT)
+
+
+def _err(payload: Any) -> str | None:
+ if isinstance(payload, dict):
+ for k in ("error", "error_detail", "message", "detail"):
+ value = payload.get(k)
+ if isinstance(value, str) and value:
+ return value
+ return None
diff --git a/agent/tests/test_alpaca_tap_routing.py b/agent/tests/test_alpaca_tap_routing.py
new file mode 100644
index 000000000..61d4cb873
--- /dev/null
+++ b/agent/tests/test_alpaca_tap_routing.py
@@ -0,0 +1,451 @@
+"""Tests for the opt-in TAP routing of Alpaca order placement.
+
+When TAP is enabled, ``alpaca.sdk.place_order`` must route the order through the
+TAP proxy (``tap_forward.forward``) instead of the broker SDK, map the upstream
+response into the standard envelope, and fail closed on a denied/timed-out
+order. When TAP is disabled, the connector keeps its existing direct-SDK path.
+
+These tests mock ``tap_forward`` so they need no network, no approval, and no
+``alpaca-py`` SDK.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from src.trading.connectors.alpaca import sdk as al
+
+pytestmark = pytest.mark.unit
+
+
+def _paper_cfg() -> "al.AlpacaConfig":
+ # No keys needed on the TAP path β€” placeholders are injected by TAP.
+ return al.AlpacaConfig(profile="paper")
+
+
+def _ok(body: str) -> dict:
+ """A TAP forward result for an auto-approved read (GET) β€” 200 + JSON body."""
+ return {"ok": True, "decision": "immediate", "status": 200, "body": body, "error": None}
+
+
+def test_place_order_routes_through_tap_when_enabled(monkeypatch) -> None:
+ captured: dict = {}
+
+ def fake_forward(target, method, body, cred_headers, **_):
+ captured["target"] = target
+ captured["method"] = method
+ captured["body"] = body
+ captured["cred_headers"] = dict(cred_headers)
+ return {
+ "ok": True,
+ "decision": "forwarded",
+ "status": 200,
+ "body": json.dumps({"id": "ord-123", "status": "pending_new", "filled_qty": "0"}),
+ "error": None,
+ }
+
+ monkeypatch.setattr(al.tap_forward, "tap_enabled", lambda: True)
+ monkeypatch.setattr(al.tap_forward, "forward", fake_forward)
+
+ result = al.place_order(
+ _paper_cfg(),
+ symbol="AAPL",
+ side="buy",
+ quantity=1,
+ order_type="limit",
+ limit_price=1,
+ time_in_force="day",
+ )
+
+ # Envelope is mapped from the upstream response, marked as TAP-routed.
+ assert result["status"] == "ok"
+ assert result["order_id"] == "ord-123"
+ assert result["order_status"] == "pending_new"
+ assert result["via"] == "tap"
+
+ # The request was aimed at Alpaca's orders endpoint via TAP, with the secret
+ # referenced by placeholders (never a raw key) β€” not an Authorization header.
+ assert captured["method"] == "POST"
+ assert captured["target"].endswith("/v2/orders")
+ assert captured["cred_headers"]["APCA-API-KEY-ID"] == "<CREDENTIAL:alpaca.key_id>"
+ assert captured["cred_headers"]["APCA-API-SECRET-KEY"] == "<CREDENTIAL:alpaca.secret_key>"
+ sent = json.loads(captured["body"])
+ assert sent["symbol"] == "AAPL" and sent["side"] == "buy" and sent["qty"] == "1.0"
+ assert sent["type"] == "limit" and sent["limit_price"] == "1.0"
+ # Idempotency: the order carries a deterministic client_order_id so an
+ # approval-race retry is deduplicated by the broker rather than double-placed.
+ assert sent["client_order_id"].startswith("tap-")
+
+
+def test_denied_order_is_blocked(monkeypatch) -> None:
+ monkeypatch.setattr(al.tap_forward, "tap_enabled", lambda: True)
+ monkeypatch.setattr(
+ al.tap_forward,
+ "forward",
+ lambda *a, **k: {"ok": False, "decision": "denied", "status": None,
+ "body": None, "error": "denied"},
+ )
+
+ result = al.place_order(
+ _paper_cfg(), symbol="TSLA", side="buy", notional=10000, order_type="market"
+ )
+
+ # Fail closed: a denied order is an error and carries no order_id.
+ assert result["status"] == "error"
+ assert result["tap_decision"] == "denied"
+ assert "order_id" not in result
+
+
+def test_client_order_id_is_deterministic_for_idempotency(monkeypatch) -> None:
+ """Same order content -> same client_order_id (so an approval-race retry is
+ deduplicated by the broker); a changed field -> a different id (so a genuine
+ second order is not accidentally blocked as a duplicate)."""
+ ids: list[str] = []
+
+ def fake_forward(target, method, body, cred_headers, **_):
+ ids.append(json.loads(body)["client_order_id"])
+ return {"ok": True, "decision": "forwarded", "status": 200,
+ "body": json.dumps({"id": "ord", "status": "new"}), "error": None}
+
+ monkeypatch.setattr(al.tap_forward, "tap_enabled", lambda: True)
+ monkeypatch.setattr(al.tap_forward, "forward", fake_forward)
+
+ kw = dict(symbol="AAPL", side="buy", quantity=1, order_type="limit",
+ limit_price=1, time_in_force="day")
+ al.place_order(_paper_cfg(), **kw) # first submit
+ al.place_order(_paper_cfg(), **kw) # identical retry
+ al.place_order(_paper_cfg(), **{**kw, "quantity": 2}) # genuinely different
+
+ assert ids[0] == ids[1] # retry -> broker dedups it
+ assert ids[2] != ids[0] # different order -> new id
+ assert all(i.startswith("tap-") for i in ids)
+
+
+def test_tap_credential_name_is_overridable(monkeypatch) -> None:
+ captured: dict = {}
+ monkeypatch.setattr(al.tap_forward, "tap_enabled", lambda: True)
+ monkeypatch.setattr(al.tap_forward, "forward",
+ lambda target, method, body, cred_headers, **_: captured.update(
+ cred_headers=dict(cred_headers)) or {
+ "ok": True, "decision": "forwarded", "status": 200,
+ "body": json.dumps({"id": "x", "status": "new"}), "error": None})
+ monkeypatch.setenv("TAP_ALPACA_CREDENTIAL", "alpaca-paper")
+
+ al.place_order(_paper_cfg(), symbol="AAPL", side="buy", quantity=1)
+
+ assert captured["cred_headers"]["APCA-API-KEY-ID"] == "<CREDENTIAL:alpaca-paper.key_id>"
+
+
+def test_tap_disabled_does_not_route_through_tap(monkeypatch) -> None:
+ monkeypatch.setattr(al.tap_forward, "tap_enabled", lambda: False)
+
+ def boom(*a, **k): # forward must never be called when TAP is off
+ raise AssertionError("tap_forward.forward called while TAP disabled")
+
+ monkeypatch.setattr(al.tap_forward, "forward", boom)
+
+ # With TAP off and no alpaca-py SDK available, the connector takes its
+ # direct-SDK path and reports the missing dependency β€” never via=tap.
+ result = al.place_order(_paper_cfg(), symbol="AAPL", side="buy", quantity=1)
+
+ assert result.get("via") != "tap"
+
+
+# --------------------------------------------------------------------------- #
+# M1b: reads routed through TAP (credential isolation β€” a read is a GET, which
+# TAP auto-approves, so there is no human gate; the process just holds no key).
+# Trading reads reuse the SDK field names; the market-data API abbreviates keys,
+# so quote/bars are aliased back before mapping.
+# --------------------------------------------------------------------------- #
+
+
+def _enable_tap(monkeypatch, fake_forward) -> None:
+ monkeypatch.setattr(al.tap_forward, "tap_enabled", lambda: True)
+ monkeypatch.setattr(al.tap_forward, "forward", fake_forward)
+
+
+def test_get_account_snapshot_routes_through_tap(monkeypatch) -> None:
+ captured: dict = {}
+
+ def fake_forward(target, method, body, cred_headers, **_):
+ captured.update(target=target, method=method, cred_headers=dict(cred_headers))
+ return _ok(json.dumps({
+ "account_number": "PA123", "status": "ACTIVE", "currency": "USD",
+ "cash": "1000", "equity": "1500", "buying_power": "3000",
+ "portfolio_value": "1500", "pattern_day_trader": False, "trading_blocked": False,
+ }))
+
+ _enable_tap(monkeypatch, fake_forward)
+ result = al.get_account_snapshot(_paper_cfg())
+
+ assert captured["method"] == "GET"
+ assert captured["target"] == "https://paper-api.alpaca.markets/v2/account"
+ # Secret referenced by placeholder only β€” never a raw key on the wire.
+ assert captured["cred_headers"]["APCA-API-KEY-ID"] == "<CREDENTIAL:alpaca.key_id>"
+ assert captured["cred_headers"]["APCA-API-SECRET-KEY"] == "<CREDENTIAL:alpaca.secret_key>"
+ assert result["account"]["account_number"] == "PA123"
+ assert result["account"]["equity"] == "1500"
+
+
+def test_get_positions_routes_through_tap(monkeypatch) -> None:
+ captured: dict = {}
+
+ def fake_forward(target, method, body, cred_headers, **_):
+ captured.update(target=target, method=method)
+ return _ok(json.dumps([{
+ "symbol": "AAPL", "side": "long", "qty": "10", "avg_entry_price": "100",
+ "market_value": "1100", "current_price": "110", "unrealized_pl": "100",
+ "cost_basis": "1000",
+ }]))
+
+ _enable_tap(monkeypatch, fake_forward)
+ result = al.get_positions(_paper_cfg())
+
+ assert captured["method"] == "GET"
+ assert captured["target"] == "https://paper-api.alpaca.markets/v2/positions"
+ row = result["positions"][0]
+ assert row["symbol"] == "AAPL"
+ assert row["quantity"] == "10" # qty -> quantity
+ assert row["unrealized_pnl"] == "100" # unrealized_pl -> unrealized_pnl
+
+
+def test_get_open_orders_routes_through_tap(monkeypatch) -> None:
+ calls: list = []
+
+ def fake_forward(target, method, body, cred_headers, **_):
+ calls.append(target)
+ if "status=open" in target:
+ return _ok(json.dumps([{
+ "id": "o1", "symbol": "AAPL", "side": "buy", "type": "limit",
+ "qty": "1", "limit_price": "10", "status": "new", "submitted_at": "t",
+ }]))
+ return _ok(json.dumps([
+ {"id": "o2", "symbol": "TSLA", "side": "sell", "type": "market",
+ "qty": "2", "filled_qty": "2", "status": "filled", "submitted_at": "t"},
+ {"id": "o3", "symbol": "MSFT", "side": "buy", "type": "market",
+ "qty": "1", "filled_qty": None, "status": "canceled", "submitted_at": "t"},
+ ]))
+
+ _enable_tap(monkeypatch, fake_forward)
+ result = al.get_open_orders(_paper_cfg(), include_executions=True)
+
+ assert all(t.startswith("https://paper-api.alpaca.markets/v2/orders?status=") for t in calls)
+ assert any("status=open" in t for t in calls)
+ assert any("status=closed" in t for t in calls)
+ assert result["open_orders"][0]["order_id"] == "o1"
+ # Only filled orders count as executions (o3 has no filled_qty).
+ assert [e["order_id"] for e in result["executions"]] == ["o2"]
+
+
+def test_get_quote_routes_through_tap_and_normalizes_keys(monkeypatch) -> None:
+ captured: dict = {}
+
+ def fake_forward(target, method, body, cred_headers, **_):
+ captured.update(target=target, method=method)
+ # Market-data REST abbreviates: bp/ap/bs/as/t (the SDK exposes full names).
+ return _ok(json.dumps({
+ "symbol": "AAPL",
+ "quote": {"bp": 100.0, "ap": 100.5, "bs": 3, "as": 4, "t": "2026-01-01T00:00:00Z"},
+ }))
+
+ _enable_tap(monkeypatch, fake_forward)
+ result = al.get_quote("aapl", config=_paper_cfg())
+
+ assert captured["method"] == "GET"
+ assert captured["target"].startswith("https://data.alpaca.markets/v2/stocks/AAPL/quotes/latest")
+ assert "feed=iex" in captured["target"]
+ q = result["quote"]
+ assert q["bid"] == 100.0 # bp -> bid_price -> bid
+ assert q["ask"] == 100.5 # ap -> ask_price -> ask
+ assert q["bid_size"] == 3
+ assert q["ask_size"] == 4
+
+
+def test_get_historical_bars_routes_through_tap_and_normalizes_keys(monkeypatch) -> None:
+ captured: dict = {}
+
+ def fake_forward(target, method, body, cred_headers, **_):
+ captured.update(target=target, method=method)
+ return _ok(json.dumps({
+ "symbol": "AAPL",
+ "bars": [{"t": "2026-01-01T00:00:00Z", "o": 1.0, "h": 2.0, "l": 0.5, "c": 1.5, "v": 1000}],
+ }))
+
+ _enable_tap(monkeypatch, fake_forward)
+ result = al.get_historical_bars("aapl", config=_paper_cfg(), period="1d", limit=5)
+
+ assert captured["target"].startswith("https://data.alpaca.markets/v2/stocks/AAPL/bars")
+ assert "timeframe=1Day" in captured["target"]
+ assert "limit=5" in captured["target"]
+ bar = result["bars"][0]
+ assert bar["open"] == 1.0 # o -> open
+ assert bar["high"] == 2.0
+ assert bar["low"] == 0.5
+ assert bar["close"] == 1.5 # c -> close
+ assert bar["volume"] == 1000 # v -> volume
+
+
+def test_read_fails_closed_when_tap_errors(monkeypatch) -> None:
+ # A host-pin rejection / TAP error must not silently yield empty data β€” the
+ # read raises, mirroring the SDK path raising on an API error.
+ monkeypatch.setattr(al.tap_forward, "tap_enabled", lambda: True)
+ monkeypatch.setattr(
+ al.tap_forward, "forward",
+ lambda *a, **k: {"ok": False, "decision": "error", "status": 403,
+ "body": None, "error": "host not allowed"},
+ )
+ with pytest.raises(RuntimeError):
+ al.get_positions(_paper_cfg())
+
+
+def test_reads_do_not_route_through_tap_when_disabled(monkeypatch) -> None:
+ # TAP off: the read must take the direct-SDK path and never call forward.
+ monkeypatch.setattr(al.tap_forward, "tap_enabled", lambda: False)
+
+ def boom(*a, **k):
+ raise AssertionError("tap_forward.forward called while TAP disabled")
+
+ monkeypatch.setattr(al.tap_forward, "forward", boom)
+
+ class _FakeClient:
+ def get_all_positions(self):
+ return [{"symbol": "NVDA", "side": "long", "qty": "1", "avg_entry_price": "1",
+ "market_value": "1", "current_price": "1", "unrealized_pl": "0", "cost_basis": "1"}]
+
+ monkeypatch.setattr(al, "_trading_client", lambda cfg: _FakeClient())
+ result = al.get_positions(_paper_cfg())
+
+ assert result["positions"][0]["symbol"] == "NVDA" # came from the SDK path
+
+
+# --------------------------------------------------------------------------- #
+# M1b: cancel routed through TAP (a write β€” human-approved, not auto-approved).
+# --------------------------------------------------------------------------- #
+
+
+def test_cancel_order_routes_through_tap(monkeypatch) -> None:
+ captured: dict = {}
+
+ def fake_forward(target, method, body, cred_headers, **_):
+ captured.update(target=target, method=method, cred_headers=dict(cred_headers))
+ # A cancel is a write: TAP forwards after approval; Alpaca returns 204.
+ return {"ok": True, "decision": "forwarded", "status": 204, "body": None, "error": None}
+
+ _enable_tap(monkeypatch, fake_forward)
+ result = al.cancel_order(_paper_cfg(), order_id="ord-1", symbol="aapl")
+
+ assert captured["method"] == "DELETE"
+ assert captured["target"] == "https://paper-api.alpaca.markets/v2/orders/ord-1"
+ assert captured["cred_headers"]["APCA-API-SECRET-KEY"] == "<CREDENTIAL:alpaca.secret_key>"
+ assert result["status"] == "ok"
+ assert result["cancelled"] is True
+ assert result["via"] == "tap"
+ assert result["symbol"] == "AAPL"
+
+
+def test_denied_cancel_is_blocked(monkeypatch) -> None:
+ monkeypatch.setattr(al.tap_forward, "tap_enabled", lambda: True)
+ monkeypatch.setattr(
+ al.tap_forward, "forward",
+ lambda *a, **k: {"ok": False, "decision": "denied", "status": None,
+ "body": None, "error": None},
+ )
+ result = al.cancel_order(_paper_cfg(), order_id="ord-1")
+
+ # Fail closed: a denied cancel is an error and did not cancel anything.
+ assert result["status"] == "error"
+ assert result["tap_decision"] == "denied"
+ assert result.get("cancelled") is not True
+
+
+# --------------------------------------------------------------------------- #
+# Red line: the live mandate gate strictly precedes TAP. TAP is transport under
+# `connector.place_order`; a mandate DENY must block the order with
+# `tap_forward.forward` never called, and an ALLOW must route it through TAP.
+# These run the REAL alpaca connector module through the REAL gate.
+# --------------------------------------------------------------------------- #
+
+from src.live import sdk_order_gate as gate # noqa: E402
+from tests.test_sdk_order_gate import _intent, _mandate, _patch_gate # noqa: E402
+
+
+def test_live_mandate_deny_blocks_before_any_tap_call(monkeypatch) -> None:
+ calls: list = []
+ monkeypatch.setattr(al.tap_forward, "tap_enabled", lambda: True)
+ monkeypatch.setattr(al.tap_forward, "forward",
+ lambda *a, **k: calls.append(a) or {"ok": False})
+ _patch_gate(monkeypatch, mandate=None) # no valid mandate on file β†’ DENY
+
+ out = gate.execute_live_order(
+ broker="alpaca",
+ connector_module=al,
+ config=al.AlpacaConfig(profile="live"),
+ intent=_intent(notional=500.0),
+ place_kwargs={"symbol": "AAPL", "side": "buy", "notional": 500.0,
+ "order_type": "market"},
+ )
+
+ assert out["status"] == "blocked" and out["decision"] == "deny"
+ assert calls == [] # nothing β€” not even a read β€” reached TAP
+
+
+def test_live_mandate_halt_blocks_before_any_tap_call(monkeypatch) -> None:
+ calls: list = []
+ monkeypatch.setattr(al.tap_forward, "tap_enabled", lambda: True)
+ monkeypatch.setattr(al.tap_forward, "forward",
+ lambda *a, **k: calls.append(a) or {"ok": False})
+ _patch_gate(monkeypatch, mandate=_mandate(), halted=True) # kill switch tripped
+
+ out = gate.execute_live_order(
+ broker="alpaca",
+ connector_module=al,
+ config=al.AlpacaConfig(profile="live"),
+ intent=_intent(notional=500.0),
+ place_kwargs={"symbol": "AAPL", "side": "buy", "notional": 500.0,
+ "order_type": "market"},
+ )
+
+ assert out["status"] == "blocked"
+ assert calls == []
+
+
+def test_live_mandate_allow_routes_order_through_tap(monkeypatch) -> None:
+ order_posts: list[str] = []
+
+ def fake_forward(target, method, body, cred_headers, **_):
+ if method == "GET" and target.endswith("/v2/positions"):
+ return _ok(json.dumps([]))
+ if method == "GET" and target.endswith("/v2/account"):
+ return _ok(json.dumps({
+ "account_number": "LA123", "status": "ACTIVE", "currency": "USD",
+ "cash": "100000", "equity": "100000", "buying_power": "200000",
+ "portfolio_value": "100000", "pattern_day_trader": False,
+ "trading_blocked": False,
+ }))
+ assert method == "POST" and target.endswith("/v2/orders")
+ order_posts.append(target)
+ return {"ok": True, "decision": "forwarded", "status": 200,
+ "body": json.dumps({"id": "ord-live-1", "status": "accepted"}),
+ "error": None}
+
+ monkeypatch.setattr(al.tap_forward, "tap_enabled", lambda: True)
+ monkeypatch.setattr(al.tap_forward, "forward", fake_forward)
+ _patch_gate(monkeypatch, mandate=_mandate()) # in-bounds β†’ ALLOW
+
+ out = gate.execute_live_order(
+ broker="alpaca",
+ connector_module=al,
+ config=al.AlpacaConfig(profile="live"),
+ intent=_intent(notional=500.0),
+ place_kwargs={"symbol": "AAPL", "side": "buy", "notional": 500.0,
+ "order_type": "market"},
+ )
+
+ # Same gate, same ordering β€” the ALLOW went out through TAP, to the live host.
+ assert out["status"] == "ok"
+ assert out["via"] == "tap"
+ assert out["order_id"] == "ord-live-1"
+ assert "live_action" in out # the gate audited the allowed order
+ assert order_posts == ["https://api.alpaca.markets/v2/orders"]
diff --git a/agent/tests/test_tap_forward.py b/agent/tests/test_tap_forward.py
new file mode 100644
index 000000000..61d461eb5
--- /dev/null
+++ b/agent/tests/test_tap_forward.py
@@ -0,0 +1,246 @@
+"""Direct unit tests for ``src.trading.tap_forward``.
+
+The connector tests (test_alpaca_tap_routing.py) mock ``tap_forward.forward``
+wholesale, so this file exercises the module itself with ``urllib`` mocked:
+the fail-closed error paths, the 202 β†’ poll β†’ decision loop, and the
+poll-URL exfiltration guard (the agent key must never be sent to a URL taken
+from a response body unless it is a relative path re-rooted on the configured
+base). No network, no TAP instance needed.
+"""
+
+from __future__ import annotations
+
+import json
+import urllib.error
+import urllib.request
+
+import pytest
+
+from src.trading import tap_forward as tf
+
+pytestmark = pytest.mark.unit
+
+_BASE = "https://tap.test.local"
+_CRED = {"APCA-API-KEY-ID": "<CREDENTIAL:alpaca.key_id>"}
+
+
+class _FakeResponse:
+ def __init__(self, status: int, body: str):
+ self.status = status
+ self._body = body
+
+ def read(self) -> bytes:
+ return self._body.encode("utf-8")
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+
+def tap_env(monkeypatch):
+ """Configure TAP purely via the environment (no .env scanning)."""
+ monkeypatch.setenv("TAP_PROXY_URL", _BASE)
+ monkeypatch.setenv("TAP_AGENT_KEY", "tap-agent-key-under-test")
+ monkeypatch.setattr(tf.time, "sleep", lambda s: None) # poll loop: no real waiting
+
+
+def _install_urlopen(monkeypatch, handler):
+ """Route ``urllib.request.urlopen`` to ``handler(req)`` and record calls.
+
+ Returns the call log: a list of ``(method, url, header_names)`` tuples.
+ ``header_names`` uses the original casing so the exfil tests can assert on
+ whether X-TAP-Key was attached to a given URL.
+ """
+ calls: list[tuple[str, str, list[str]]] = []
+
+ def fake_urlopen(req, timeout=None):
+ assert isinstance(req, urllib.request.Request)
+ calls.append((req.get_method(), req.full_url, list(req.headers)))
+ return handler(req)
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+ return calls
+
+
+# --------------------------------------------------------------------------- #
+# Fail-closed basics
+# --------------------------------------------------------------------------- #
+
+
+def test_connection_error_fails_closed(tap_env, monkeypatch) -> None:
+ def handler(req):
+ raise urllib.error.URLError("connection refused")
+
+ _install_urlopen(monkeypatch, handler)
+ result = tf.forward(f"{_BASE}/v2/orders", "POST", "{}", _CRED)
+
+ assert result["ok"] is False
+ assert "connection failed" in (result["error"] or "")
+
+
+def test_unconfigured_tap_fails_closed(monkeypatch) -> None:
+ monkeypatch.delenv("TAP_PROXY_URL", raising=False)
+ monkeypatch.delenv("TAP_AGENT_KEY", raising=False)
+ monkeypatch.setattr(tf, "_load_env_into_environ", lambda: None) # skip .env scan
+
+ def handler(req): # pragma: no cover - must never be reached
+ raise AssertionError("no HTTP call may happen without TAP config")
+
+ _install_urlopen(monkeypatch, handler)
+ result = tf.forward("https://api.example/v2/orders", "POST", "{}", _CRED)
+
+ assert result["ok"] is False
+ assert result["error"] == "TAP not configured"
+
+
+def test_immediate_read_success(tap_env, monkeypatch) -> None:
+ _install_urlopen(
+ monkeypatch, lambda req: _FakeResponse(200, json.dumps({"cash": "1000"}))
+ )
+ result = tf.forward("https://api.example/v2/account", "GET", None, _CRED)
+
+ assert result["ok"] is True
+ assert result["decision"] == "immediate"
+ assert result["status"] == 200
+ assert result["body"] == {"cash": "1000"}
+
+
+# --------------------------------------------------------------------------- #
+# 202 β†’ poll β†’ terminal decision
+# --------------------------------------------------------------------------- #
+
+
+def _write_then_poll(monkeypatch, poll_bodies: list[str]):
+ """First call: 202 with a txn_id. Subsequent calls: pop from poll_bodies."""
+ state = {"first": True}
+
+ def handler(req):
+ if state["first"]:
+ state["first"] = False
+ return _FakeResponse(202, json.dumps({"txn_id": "txn-1"}))
+ return _FakeResponse(200, poll_bodies.pop(0))
+
+ return _install_urlopen(monkeypatch, handler)
+
+
+def test_approved_write_polls_until_forwarded(tap_env, monkeypatch) -> None:
+ calls = _write_then_poll(monkeypatch, [
+ json.dumps({"status": "pending"}),
+ json.dumps({"status": "forwarded",
+ "response": {"status": 200, "body": '{"id": "ord-1"}'}}),
+ ])
+ result = tf.forward(f"https://api.example/v2/orders", "POST", "{}", _CRED, timeout=30)
+
+ assert result["ok"] is True
+ assert result["decision"] == "forwarded"
+ assert result["status"] == 200
+ assert result["body"] == '{"id": "ord-1"}'
+ # The poll went to the CONFIGURED base, derived from the txn_id.
+ poll_calls = [c for c in calls if c[0] == "GET"]
+ assert all(url == f"{_BASE}/agent/approvals/txn-1" for _, url, _ in poll_calls)
+
+
+def test_forwarded_with_upstream_error_is_not_ok(tap_env, monkeypatch) -> None:
+ _write_then_poll(monkeypatch, [
+ json.dumps({"status": "forwarded",
+ "response": {"status": 422, "body": '{"message": "rejected"}'}}),
+ ])
+ result = tf.forward("https://api.example/v2/orders", "POST", "{}", _CRED, timeout=30)
+
+ assert result["ok"] is False # forwarded but upstream refused β†’ still fail-closed
+ assert result["decision"] == "forwarded"
+ assert result["status"] == 422
+
+
[email protected]("decision", ["denied", "timed_out", "error"])
+def test_terminal_refusals_fail_closed(tap_env, monkeypatch, decision) -> None:
+ _write_then_poll(monkeypatch, [json.dumps({"status": decision})])
+ result = tf.forward("https://api.example/v2/orders", "POST", "{}", _CRED, timeout=30)
+
+ assert result["ok"] is False
+ assert result["decision"] == decision
+
+
+def test_no_decision_within_timeout_fails_closed(tap_env, monkeypatch) -> None:
+ # timeout=0 β†’ the poll loop never runs; the deadline path must fail closed.
+ _install_urlopen(
+ monkeypatch, lambda req: _FakeResponse(202, json.dumps({"txn_id": "txn-1"}))
+ )
+ result = tf.forward("https://api.example/v2/orders", "POST", "{}", _CRED, timeout=0)
+
+ assert result["ok"] is False
+ assert result["decision"] == "timeout"
+
+
+# --------------------------------------------------------------------------- #
+# Poll-URL exfiltration guard: X-TAP-Key must never travel to a URL taken from
+# a response body β€” only a relative path re-rooted on the configured base.
+# --------------------------------------------------------------------------- #
+
+
+def _respond_202(monkeypatch, payload: dict):
+ """202 with an attacker-controlled body; any later GET returns 'forwarded'."""
+ state = {"first": True}
+
+ def handler(req):
+ if state["first"]:
+ state["first"] = False
+ return _FakeResponse(202, json.dumps(payload))
+ return _FakeResponse(200, json.dumps(
+ {"status": "forwarded", "response": {"status": 200, "body": "{}"}}))
+
+ return _install_urlopen(monkeypatch, handler)
+
+
[email protected]("poll_url", [
+ "https://evil.example/steal", # absolute URL β†’ refused
+ "//evil.example/steal", # protocol-relative β†’ refused (no leading single "/")
+ "agent/approvals/txn-1", # not "/"-prefixed β†’ refused
+])
+def test_tampered_poll_url_is_rejected_and_never_contacted(tap_env, monkeypatch, poll_url) -> None:
+ calls = _respond_202(monkeypatch, {"poll_url": poll_url})
+ result = tf.forward("https://api.example/v2/orders", "POST", "{}", _CRED, timeout=30)
+
+ assert result["ok"] is False
+ assert "txn_id" in (result["error"] or "")
+ # Only the initial POST happened β€” the key was never sent anywhere else.
+ assert len(calls) == 1
+ assert calls[0][0] == "POST" and calls[0][1] == f"{_BASE}/forward"
+
+
+def test_protocol_relative_poll_url_is_refused_specifically(tap_env, monkeypatch) -> None:
+ # "//evil.example/x" starts with "/" per a naive check; base + "//host/x"
+ # would resolve to the attacker's host. It must not be polled.
+ calls = _respond_202(monkeypatch, {"poll_url": "//evil.example/x"})
+ tf.forward("https://api.example/v2/orders", "POST", "{}", _CRED, timeout=30)
+
+ assert all("evil.example" not in url for _, url, _ in calls)
+
+
+def test_relative_poll_url_is_rerooted_on_configured_base(tap_env, monkeypatch) -> None:
+ calls = _respond_202(monkeypatch, {"poll_url": "/agent/approvals/txn-9"})
+ result = tf.forward("https://api.example/v2/orders", "POST", "{}", _CRED, timeout=30)
+
+ assert result["ok"] is True
+ get_calls = [c for c in calls if c[0] == "GET"]
+ assert get_calls and all(url == f"{_BASE}/agent/approvals/txn-9" for _, url, _ in get_calls)
+
+
+# --------------------------------------------------------------------------- #
+# .env loader robustness (review item: a non-UTF-8 .env must not break calls)
+# --------------------------------------------------------------------------- #
+
+
+def test_non_utf8_env_file_is_skipped(tmp_path, monkeypatch) -> None:
+ bad = tmp_path / ".env"
+ bad.write_bytes(b"TAP_PROXY_URL=\xff\xfe broken \x80\n")
+ monkeypatch.setattr(tf, "_ENV_CANDIDATES", (bad,))
+ monkeypatch.delenv("TAP_PROXY_URL", raising=False)
+ monkeypatch.delenv("TAP_AGENT_KEY", raising=False)
+
+ tf._load_env_into_environ() # must not raise UnicodeDecodeError
+
+ assert tf.tap_enabled() is False # unreadable file ≑ missing file