ibkr-agent-gateway 0.5.2

Unofficial local-first CLI and MCP gateway for Interactive Brokers workflows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Fake backend fixture loading support.

use super::r#trait::{BackendResult, IbkrBackend};
use crate::internal::domain::{
    AccountCapabilityProfile, AccountId, BrokerAccount, BrokerSessionStatus, ContractCandidate,
    ContractId, HistoricalBar, HistoricalBarsRequest, MarketSnapshot, OrdersHistory,
    OrdersHistoryRequest, PnlRealtime, PnlSnapshot, ReadOnlyOrderRecord,
};
use crate::internal::domain::{
    CurrencyRate, ErrorCode, FundamentalsReport, GatewayError, MarketDepth, MarketHolidays,
    MarketSession, NewsArticle, NewsList, OptionChain, OptionGreeks, ScannerRun, TransferHistory,
};
use async_trait::async_trait;
use serde::de::DeserializeOwned;
use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, RwLock};

/// Filesystem-backed fake broker fixtures.
#[derive(Clone, Debug)]
pub struct FakeFixtureStore {
    root: PathBuf,
    cache: Arc<RwLock<BTreeMap<String, Arc<serde_json::Value>>>>,
}

impl FakeFixtureStore {
    /// Creates a fixture store rooted at `root`.
    #[must_use]
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            cache: Arc::new(RwLock::new(BTreeMap::new())),
        }
    }

    /// Returns the fixture root.
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Loads and deserializes one JSON fixture.
    pub async fn load_json<T: DeserializeOwned>(
        &self,
        relative_path: &str,
    ) -> Result<T, GatewayError> {
        let value = self.load_value(relative_path).await?;
        serde_json::from_value((*value).clone()).map_err(|_| {
            GatewayError::new(
                ErrorCode::BrokerResponseInvalid,
                format!("Invalid fake backend fixture JSON shape: {relative_path}"),
                true,
                Some("Fix the fake backend fixture JSON".to_string()),
            )
        })
    }

    async fn load_value(
        &self,
        relative_path: &str,
    ) -> Result<Arc<serde_json::Value>, GatewayError> {
        if let Some(value) = self.cached(relative_path) {
            return Ok(value);
        }

        let path = safe_join(&self.root, relative_path)?;
        let raw = tokio::fs::read_to_string(&path).await.map_err(|err| {
            tracing::error!(
                target: "backend.fake",
                path = %path.display(),
                error = %err,
                error_kind = ?err.kind(),
                "fake backend fixture is missing or unreadable"
            );
            GatewayError::new(
                ErrorCode::BrokerBackendUnavailable,
                format!("Missing fake backend fixture: {}", path.display()),
                true,
                Some("Create the requested fake backend fixture".to_string()),
            )
        })?;

        let value = serde_json::from_str::<serde_json::Value>(&raw).map_err(|err| {
            tracing::error!(
                target: "backend.fake",
                path = %path.display(),
                error = %err,
                line = err.line(),
                column = err.column(),
                "fake backend fixture JSON is invalid"
            );
            GatewayError::new(
                ErrorCode::BrokerResponseInvalid,
                format!("Invalid fake backend fixture JSON: {}", path.display()),
                true,
                Some("Fix the fake backend fixture JSON".to_string()),
            )
        })?;
        let value = Arc::new(value);
        self.cache_value(relative_path, value.clone());
        Ok(value)
    }

    fn cached(&self, relative_path: &str) -> Option<Arc<serde_json::Value>> {
        let cache = self
            .cache
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        cache.get(relative_path).cloned()
    }

    fn cache_value(&self, relative_path: &str, value: Arc<serde_json::Value>) {
        let mut cache = self
            .cache
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        cache.insert(relative_path.to_string(), value);
    }
}

impl PartialEq for FakeFixtureStore {
    fn eq(&self, other: &Self) -> bool {
        self.root == other.root
    }
}

impl Eq for FakeFixtureStore {}

/// Fake backend for offline validation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FakeBackend {
    fixtures: FakeFixtureStore,
}

impl FakeBackend {
    /// Creates a fake backend rooted at `fixtures`.
    #[must_use]
    pub const fn new(fixtures: FakeFixtureStore) -> Self {
        Self { fixtures }
    }
}

#[async_trait]
impl IbkrBackend for FakeBackend {
    async fn session_status(&self) -> BackendResult<BrokerSessionStatus> {
        self.fixtures.load_json("session_status_usable.json").await
    }

    async fn keepalive(&self) -> BackendResult<BrokerSessionStatus> {
        self.fixtures.load_json("tickle_success.json").await
    }

    async fn list_accounts(&self) -> BackendResult<Vec<BrokerAccount>> {
        self.fixtures.load_json("accounts_success.json").await
    }

    async fn account_summary(&self, account_id: &AccountId) -> BackendResult<serde_json::Value> {
        validate_account_id(account_id)?;
        self.fixtures.load_json("portfolio_snapshot.json").await
    }

    async fn portfolio_snapshot(&self, account_id: &AccountId) -> BackendResult<serde_json::Value> {
        validate_account_id(account_id)?;
        self.fixtures.load_json("portfolio_snapshot.json").await
    }

    async fn positions(&self, account_id: &AccountId) -> BackendResult<Vec<serde_json::Value>> {
        validate_account_id(account_id)?;
        self.fixtures.load_json("positions_list.json").await
    }

    async fn search_contracts(&self, query: &str) -> BackendResult<Vec<ContractCandidate>> {
        if query.eq_ignore_ascii_case("AMBIG") {
            return self.fixtures.load_json("contracts_ambiguous.json").await;
        }
        self.fixtures
            .load_json("contracts_search_stock_etf.json")
            .await
    }

    async fn resolve_contract(&self, query: &str) -> BackendResult<ContractCandidate> {
        let candidates = self.search_contracts(query).await?;
        super::resolve_unique_contract(candidates)
    }

    async fn market_snapshot(&self, _contract_id: &ContractId) -> BackendResult<MarketSnapshot> {
        self.fixtures.load_json("market_snapshot_live.json").await
    }

    async fn historical_bars(
        &self,
        _request: &HistoricalBarsRequest,
    ) -> BackendResult<Vec<HistoricalBar>> {
        self.fixtures.load_json("historical_bars.json").await
    }

    async fn orders(&self, account_id: &AccountId) -> BackendResult<Vec<ReadOnlyOrderRecord>> {
        validate_account_id(account_id)?;
        self.fixtures.load_json("orders_list.json").await
    }

    async fn order_status(
        &self,
        account_id: &AccountId,
        _order_lookup_id: &str,
    ) -> BackendResult<ReadOnlyOrderRecord> {
        validate_account_id(account_id)?;
        self.fixtures.load_json("order_status.json").await
    }

    async fn executions(&self, account_id: &AccountId) -> BackendResult<Vec<serde_json::Value>> {
        validate_account_id(account_id)?;
        self.fixtures.load_json("executions_list.json").await
    }

    async fn pnl_daily(&self, account_id: &AccountId) -> BackendResult<PnlSnapshot> {
        validate_account_id(account_id)?;
        self.fixtures.load_json("pnl_daily.json").await
    }

    async fn pnl_realtime(&self, account_id: &AccountId) -> BackendResult<PnlRealtime> {
        validate_account_id(account_id)?;
        self.fixtures.load_json("pnl_realtime.json").await
    }

    async fn orders_history(&self, request: &OrdersHistoryRequest) -> BackendResult<OrdersHistory> {
        validate_account_id(&request.account_id)?;
        self.fixtures.load_json("orders_history.json").await
    }

    async fn account_metadata(
        &self,
        account_id: &AccountId,
    ) -> BackendResult<AccountCapabilityProfile> {
        validate_account_id(account_id)?;
        self.fixtures.load_json("account_metadata.json").await
    }

    async fn options_chain(&self, symbol: &str) -> BackendResult<OptionChain> {
        validate_text("symbol", symbol)?;
        self.fixtures.load_json("options_chain.json").await
    }

    async fn option_greeks(&self, _contract_id: &ContractId) -> BackendResult<OptionGreeks> {
        self.fixtures.load_json("option_greeks.json").await
    }

    async fn market_depth(&self, _contract_id: &ContractId) -> BackendResult<MarketDepth> {
        self.fixtures.load_json("market_depth.json").await
    }

    async fn scanner_run(&self, scanner_code: &str) -> BackendResult<ScannerRun> {
        validate_text("scanner_code", scanner_code)?;
        self.fixtures.load_json("scanner_run.json").await
    }

    async fn news_list(&self, symbol: &str) -> BackendResult<NewsList> {
        validate_text("symbol", symbol)?;
        self.fixtures.load_json("news_list.json").await
    }

    async fn news_article(&self, article_id: &str) -> BackendResult<NewsArticle> {
        validate_text("article_id", article_id)?;
        self.fixtures.load_json("news_article.json").await
    }

    async fn fundamentals_get(&self, symbol: &str) -> BackendResult<FundamentalsReport> {
        validate_text("symbol", symbol)?;
        self.fixtures.load_json("fundamentals_get.json").await
    }

    async fn market_session(&self, exchange: &str) -> BackendResult<MarketSession> {
        validate_text("exchange", exchange)?;
        self.fixtures.load_json("market_session.json").await
    }

    async fn market_holidays(&self, exchange: &str) -> BackendResult<MarketHolidays> {
        validate_text("exchange", exchange)?;
        self.fixtures.load_json("market_holidays.json").await
    }

    async fn currency_rate(&self, base: &str, quote: &str) -> BackendResult<CurrencyRate> {
        validate_text("base", base)?;
        validate_text("quote", quote)?;
        self.fixtures.load_json("currency_rate.json").await
    }

    async fn transfer_history(&self, account_id: &AccountId) -> BackendResult<TransferHistory> {
        validate_account_id(account_id)?;
        self.fixtures.load_json("transfer_history.json").await
    }
}

fn validate_account_id(account_id: &AccountId) -> Result<(), GatewayError> {
    if account_id.as_str().is_empty() {
        Err(GatewayError::new(
            ErrorCode::InputMissingAccount,
            "Account id is required",
            false,
            Some("Select one account explicitly".to_string()),
        ))
    } else {
        Ok(())
    }
}

fn validate_text(label: &str, value: &str) -> Result<(), GatewayError> {
    if value.trim().is_empty() {
        Err(GatewayError::new(
            ErrorCode::ConfigInvalid,
            format!("{label} is required"),
            false,
            Some("Provide a non-empty MCP argument".to_string()),
        ))
    } else {
        Ok(())
    }
}

/// Joins a fixture-relative path onto `root`, refusing absolute paths,
/// drive-relative paths, and any path component that would escape the root.
///
/// Mitigates review finding H-2 (2026-05-17): the fixture root is supplied via
/// configuration and may contain attacker-controlled relative segments.
fn safe_join(root: &Path, relative_path: &str) -> Result<PathBuf, GatewayError> {
    let candidate = Path::new(relative_path);
    for component in candidate.components() {
        match component {
            Component::Normal(_) => {}
            Component::CurDir => {}
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                return Err(GatewayError::new(
                    ErrorCode::BrokerResponseInvalid,
                    "Fake backend fixture path must be relative and within the root",
                    false,
                    Some(
                        "Use a fixture name without absolute prefixes or parent segments"
                            .to_string(),
                    ),
                ));
            }
        }
    }
    Ok(root.join(candidate))
}

#[cfg(test)]
mod tests {
    use super::safe_join;
    use crate::internal::domain::ErrorCode;
    use std::path::Path;

    #[test]
    fn rejects_parent_dir_components() {
        let Err(error) = safe_join(Path::new("/srv/fixtures"), "../../etc/passwd") else {
            unreachable!("parent-dir traversal must be rejected");
        };
        assert_eq!(error.code, ErrorCode::BrokerResponseInvalid);
    }

    #[test]
    fn rejects_absolute_relative_path() {
        let Err(error) = safe_join(Path::new("/srv/fixtures"), "/etc/passwd") else {
            unreachable!("absolute relative path must be rejected");
        };
        assert_eq!(error.code, ErrorCode::BrokerResponseInvalid);
    }

    #[test]
    fn accepts_simple_filename() {
        let joined = safe_join(Path::new("/srv/fixtures"), "accounts_success.json");
        assert!(joined.is_ok());
    }

    #[test]
    fn accepts_nested_normal_components() {
        let joined = safe_join(Path::new("/srv/fixtures"), "v1/accounts.json");
        assert!(joined.is_ok());
    }

    #[test]
    fn rejects_embedded_parent_segment() {
        let Err(error) = safe_join(Path::new("/srv/fixtures"), "v1/../../../etc/passwd") else {
            unreachable!("embedded traversal must be rejected");
        };
        assert_eq!(error.code, ErrorCode::BrokerResponseInvalid);
    }

    #[test]
    #[allow(clippy::panic)] // Test deliberately poisons the lock via panic.
    fn fixture_cache_survives_lock_poisoning() {
        use super::FakeFixtureStore;
        use std::sync::Arc;
        use std::thread;

        let store = FakeFixtureStore::new("/tmp/ibkr-agent-gateway/fixtures");

        // Pre-populate the cache so we can observe survival across the poison.
        store.cache_value("pre-poison.json", Arc::new(serde_json::Value::Bool(true)));

        // Deliberately poison the RwLock by panicking while holding the
        // write guard from another thread. `JoinHandle::join` returns `Err`
        // when the thread panicked; we ignore that.
        let poisoner_store = store.clone();
        let _ = thread::spawn(move || {
            let _guard = poisoner_store
                .cache
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            panic!("intentional poison for test");
        })
        .join();

        // Both read and write paths must still work after poisoning.
        let cached = store.cached("pre-poison.json");
        assert!(cached.is_some(), "cached entry must survive poison");

        store.cache_value("post-poison.json", Arc::new(serde_json::Value::Bool(false)));
        let cached_after = store.cached("post-poison.json");
        assert!(cached_after.is_some(), "writes must succeed after poison");
    }
}