agent-first-pay 0.7.0

A payment tool for AI agents — send and receive across five networks through one interface, with spending limits you control.
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
#![cfg(feature = "rest")]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use agent_first_pay::handler::{self, App};
use agent_first_pay::types::{Input, Output, RuntimeConfig};
use axum::body::Body;
use axum::extract::State;
use axum::http::{Request, StatusCode};
use axum::routing::post;
use std::net::SocketAddr;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use tokio::sync::mpsc;
use tower::ServiceExt as _;

// ═══════════════════════════════════════════
// Shared test server
// ═══════════════════════════════════════════

struct TestAppState {
    app: Arc<App>,
    api_key: String,
}

fn make_test_router(api_key: &str) -> (axum::Router, tempfile::TempDir) {
    let dir = tempfile::tempdir().unwrap();
    let config = RuntimeConfig {
        data_dir: dir.path().to_string_lossy().into_owned(),
        ..RuntimeConfig::default()
    };

    let (tx, _rx) = mpsc::channel::<Output>(4096);
    let store = agent_first_pay::store::create_storage_backend(&config);
    let app = Arc::new(App::new(config, tx, Some(true), store));

    let state = Arc::new(TestAppState {
        app,
        api_key: api_key.to_string(),
    });

    let router = axum::Router::new()
        .route("/v1/afpay", post(handle_call))
        .with_state(state);

    (router, dir)
}

async fn handle_call(
    State(state): State<Arc<TestAppState>>,
    headers: axum::http::HeaderMap,
    body: axum::body::Bytes,
) -> axum::response::Response {
    use axum::response::IntoResponse;

    // Auth check — Bearer or X-API-Key
    let authed = headers
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .map(|t| t == state.api_key)
        .unwrap_or(false)
        || headers
            .get("x-api-key")
            .and_then(|v| v.to_str().ok())
            .map(|v| v == state.api_key)
            .unwrap_or(false);

    if !authed {
        return (
            StatusCode::UNAUTHORIZED,
            axum::Json(serde_json::json!({"code":"error","error":"unauthorized"})),
        )
            .into_response();
    }

    let input: Input = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(e) => {
            return (
                StatusCode::BAD_REQUEST,
                axum::Json(
                    serde_json::json!({"code":"error","error":format!("invalid input: {e}")}),
                ),
            )
                .into_response();
        }
    };

    if input.is_local_only() {
        return (
            StatusCode::FORBIDDEN,
            axum::Json(
                serde_json::json!({"code":"error","error":"local-only operation not allowed over REST"}),
            ),
        )
            .into_response();
    }

    let (tx, mut rx) = mpsc::channel::<Output>(256);
    let config = state.app.config.read().await.clone();
    let store = agent_first_pay::store::create_storage_backend(&config);
    let app = Arc::new(App::new(config, tx, Some(true), store));
    app.requests_total.fetch_add(1, Ordering::Relaxed);

    handler::dispatch(&app, input).await;
    drop(app);

    let mut outputs = Vec::new();
    while let Some(out) = rx.recv().await {
        let v = serde_json::to_value(&out).unwrap_or(serde_json::Value::Null);
        outputs.push(v);
    }

    let has_error = outputs
        .iter()
        .any(|item| item.get("code").and_then(|v| v.as_str()) == Some("error"));
    let status = if has_error {
        StatusCode::UNPROCESSABLE_ENTITY
    } else {
        StatusCode::OK
    };

    (status, axum::Json(serde_json::Value::Array(outputs))).into_response()
}

/// Start a real TCP REST server. Returns (addr, api_key, tempdir).
async fn start_rest_server() -> (SocketAddr, String, tempfile::TempDir) {
    let api_key = "test-rest-api-key".to_string();
    let (router, dir) = make_test_router(&api_key);

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();

    tokio::spawn(async move {
        axum::serve(listener, router).await.unwrap();
    });

    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    (addr, api_key, dir)
}

// ═══════════════════════════════════════════
// Tests — in-process (tower::ServiceExt)
// ═══════════════════════════════════════════

#[tokio::test]
async fn rest_version_bearer_auth() {
    let (router, _dir) = make_test_router("my-key");

    let resp = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/afpay")
                .header("authorization", "Bearer my-key")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"code":"version"}"#))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status(), StatusCode::OK);

    let body = axum::body::to_bytes(resp.into_body(), 1 << 20)
        .await
        .unwrap();
    let outputs: Vec<serde_json::Value> = serde_json::from_slice(&body).unwrap();

    assert!(!outputs.is_empty());
    assert_eq!(
        outputs[0].get("code").and_then(|v| v.as_str()),
        Some("version")
    );
    assert!(outputs[0].get("version").and_then(|v| v.as_str()).is_some());
}

#[tokio::test]
async fn rest_version_x_api_key_auth() {
    let (router, _dir) = make_test_router("my-key");

    let resp = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/afpay")
                .header("x-api-key", "my-key")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"code":"version"}"#))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status(), StatusCode::OK);
}

#[tokio::test]
async fn rest_unauthorized_no_header() {
    let (router, _dir) = make_test_router("my-key");

    let resp = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/afpay")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"code":"version"}"#))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn rest_unauthorized_wrong_key() {
    let (router, _dir) = make_test_router("my-key");

    let resp = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/afpay")
                .header("authorization", "Bearer wrong-key")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"code":"version"}"#))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn rest_bad_json() {
    let (router, _dir) = make_test_router("my-key");

    let resp = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/afpay")
                .header("authorization", "Bearer my-key")
                .header("content-type", "application/json")
                .body(Body::from(r#"{invalid json"#))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn rest_local_only_rejected() {
    let (router, _dir) = make_test_router("my-key");

    // limit_set is a local-only operation
    let resp = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/afpay")
                .header("authorization", "Bearer my-key")
                .header("content-type", "application/json")
                .body(Body::from(
                    r#"{"code":"limit_set","id":"test_1","limits":[]}"#,
                ))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status(), StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn rest_wallet_list_empty() {
    let (router, _dir) = make_test_router("my-key");

    let resp = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/afpay")
                .header("authorization", "Bearer my-key")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"code":"wallet_list","id":"test_list"}"#))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status(), StatusCode::OK);

    let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20)
        .await
        .unwrap();
    let outputs: Vec<serde_json::Value> = serde_json::from_slice(&bytes).unwrap();

    assert!(!outputs.is_empty());
    assert_eq!(
        outputs[0].get("code").and_then(|v| v.as_str()),
        Some("wallet_list")
    );
    let wallets = outputs[0].get("wallets").and_then(|v| v.as_array());
    assert!(wallets.is_some());
    assert!(wallets.unwrap().is_empty());
}

#[tokio::test]
async fn rest_limit_list_allowed() {
    let (router, _dir) = make_test_router("my-key");

    // limit_list is read-only — should be allowed over REST
    let resp = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/afpay")
                .header("authorization", "Bearer my-key")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"code":"limit_list","id":"test_limit"}"#))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status(), StatusCode::OK);

    let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20)
        .await
        .unwrap();
    let outputs: Vec<serde_json::Value> = serde_json::from_slice(&bytes).unwrap();

    assert!(!outputs.is_empty());
    assert_eq!(
        outputs[0].get("code").and_then(|v| v.as_str()),
        Some("limit_status")
    );
}

// ═══════════════════════════════════════════
// Tests — real TCP (reqwest)
// ═══════════════════════════════════════════

#[tokio::test]
async fn rest_tcp_version() {
    let (addr, api_key, _dir) = start_rest_server().await;
    let url = format!("http://{}/v1/afpay", addr);

    let client = reqwest::Client::new();
    let resp = client
        .post(&url)
        .header("Authorization", format!("Bearer {api_key}"))
        .json(&serde_json::json!({"code":"version"}))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);

    let outputs: Vec<serde_json::Value> = resp.json().await.unwrap();
    assert!(!outputs.is_empty());
    assert_eq!(outputs[0]["code"], "version");
    assert!(outputs[0]["version"].as_str().is_some());
}

#[tokio::test]
async fn rest_tcp_unauthorized() {
    let (addr, _api_key, _dir) = start_rest_server().await;
    let url = format!("http://{}/v1/afpay", addr);

    let client = reqwest::Client::new();
    let resp = client
        .post(&url)
        .header("Authorization", "Bearer wrong")
        .json(&serde_json::json!({"code":"version"}))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 401);
}

#[tokio::test]
async fn rest_tcp_wallet_list_and_balance() {
    let (addr, api_key, _dir) = start_rest_server().await;
    let url = format!("http://{}/v1/afpay", addr);
    let client = reqwest::Client::new();

    // Wallet list
    let resp = client
        .post(&url)
        .header("Authorization", format!("Bearer {api_key}"))
        .json(&serde_json::json!({"code":"wallet_list","id":"tcp_1"}))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let outputs: Vec<serde_json::Value> = resp.json().await.unwrap();
    assert_eq!(outputs[0]["code"], "wallet_list");

    // Balance (all wallets — empty)
    let resp = client
        .post(&url)
        .header("Authorization", format!("Bearer {api_key}"))
        .json(&serde_json::json!({"code":"balance","id":"tcp_2"}))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let outputs: Vec<serde_json::Value> = resp.json().await.unwrap();
    assert_eq!(outputs[0]["code"], "wallet_balances");
}