bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Log output of an invocation. This test has its own binary: tracing caches whether
//! a log statement is enabled for the whole process, so a test on another thread
//! without a subscriber would disable the statements this test captures.

mod common;

use std::sync::{Arc, Mutex};

use bedrock_agentcore::{
    ErrorKind, RequestContext,
    runtime::{BedrockAgentCoreApp, PingStatus, Response},
};
use common::*;
use futures_util::stream;
use reqwest::StatusCode;
use serde_json::Value;

#[derive(Clone, Default)]
struct LogBuffer(Arc<Mutex<Vec<u8>>>);

impl std::io::Write for LogBuffer {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        self.0.lock().unwrap().extend_from_slice(bytes);
        Ok(bytes.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// A stream item that cannot be encoded when it is negative.
struct Item(i32);

impl serde::Serialize for Item {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        if self.0 < 0 {
            return Err(serde::ser::Error::custom("the item cannot be encoded"));
        }
        serializer.serialize_i32(self.0)
    }
}

/// An error whose text says less than its source, as the errors of the AWS SDK do.
#[derive(Debug)]
struct Unavailable(std::io::Error);

impl std::fmt::Display for Unavailable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("the model is unavailable")
    }
}

impl std::error::Error for Unavailable {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.0)
    }
}

/// The subscriber is the default of the thread of this test only. The server gives
/// it to its own thread, so the test sees the events of the server too.
#[tokio::test]
async fn logs_carry_ids_error_reasons_no_credentials_and_one_outcome_for_each_invocation() {
    let logs = LogBuffer::default();
    let buffer = logs.clone();
    let writer = logs.clone();
    let subscriber = tracing_subscriber::fmt().with_ansi(false).with_writer(move || writer.clone()).finish();
    let _default = tracing::subscriber::set_default(subscriber);

    let handler = |_payload: Value, ctx: RequestContext| async move {
        tracing::info!(?ctx, "handling");
        Ok::<_, BoxError>(format!("{ctx:?}"))
    };
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(handler)).await;
    let headers = [
        (SESSION, "session-123"),
        (REQUEST_ID, "request-456"),
        (WAT, "SECRET-TOKEN"),
        ("authorization", "Bearer SECRET-AUTH"),
        (CUSTOM, "SECRET-CUSTOM"),
        ("oauth2callbackurl", "https://secret.example/callback"),
    ];
    let (status, debug) = server.invoke(&headers, r#"{"prompt":"SECRET-PAYLOAD"}"#).await;
    assert_eq!(status, StatusCode::OK);
    server.stop().await;
    let taken = |logs: &LogBuffer| String::from_utf8(std::mem::take(&mut *logs.0.lock().unwrap())).unwrap();
    let first = taken(&logs);

    // A stream logs one outcome for its whole lifetime: when it ends, when it fails
    // and when the client leaves before its end.
    let (release, gate) = tokio::sync::watch::channel(false);
    let streaming = move |payload: Value| {
        let gate = gate.clone();
        let events = stream::unfold(0, move |n| {
            let (payload, mut gate) = (payload.clone(), gate.clone());
            async move {
                match (n, payload.as_str()) {
                    (0, _) => Some((Ok(Item(n)), n + 1)),
                    (_, Some("ends")) => None,
                    (_, Some("bad")) => Some((Ok(Item(-1)), n + 1)),
                    (_, Some("fails")) => Some((Err(BoxError::from("the model stopped")), n + 1)),
                    // Waits until the test has disconnected, then ends.
                    _ => gate.wait_for(|released| *released).await.ok().and(None),
                }
            }
        });
        std::future::ready(Ok::<_, BoxError>(Response::stream(events)))
    };
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(streaming)).await;
    let stream_headers = [(SESSION, "session-123"), ("accept", "text/event-stream")];
    // (payload, what the log must say once)
    let cases = [
        ("\"ends\"", "invocation completed"),
        // The status is 200 by then. The outcome line must still say that it failed.
        ("\"fails\"", "invocation failed: its stream ended with an error"),
        ("\"bad\"", "invocation failed: its stream ended with an error"),
        ("\"waits\"", "invocation response dropped before its end"),
    ];
    let mut stream_logs = Vec::new();
    for (payload, message) in cases {
        let mut events = SseReader::new(server.send("POST", "/invocations", &stream_headers, payload).await);
        assert_eq!(events.next().await.as_deref(), Some("data: 0"));
        if payload == "\"waits\"" {
            // The client leaves while the source waits.
            drop(events);
        } else {
            while events.next().await.is_some() {}
        }
        // The server logs the outcome after the client has seen the end of the body.
        let logged = async {
            while !String::from_utf8_lossy(&logs.0.lock().unwrap()).contains(message) {
                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
            }
        };
        tokio::time::timeout(DEADLINE, logged).await.unwrap_or_else(|_| panic!("{payload}: no log line: {message}"));
        stream_logs.push(taken(&logs));
    }
    release.send(true).unwrap();
    server.stop().await;
    for ((payload, message), log) in cases.iter().zip(&stream_logs) {
        assert_eq!(log.matches(message).count(), 1, "{payload}: {log}");
        let outcomes = ["invocation completed", "invocation failed", "dropped before its end", "body failed"];
        assert_eq!(outcomes.iter().map(|outcome| log.matches(outcome).count()).sum::<usize>(), 1, "{payload}: {log}");
        assert!(log.contains("session-123"), "{payload}: {log}");
        // The cause of a stream failure is on its outcome line, and one failure
        // writes one ERROR line.
        let cause = match *payload {
            "\"fails\"" => Some("the model stopped"),
            "\"bad\"" => Some("the item cannot be encoded"),
            _ => None,
        };
        for text in ["the model stopped", "the item cannot be encoded"] {
            assert_eq!(log.contains(text), cause == Some(text), "{payload}: {log}");
        }
        assert_eq!(log.matches("ERROR").count(), usize::from(cause.is_some()), "{payload}: {log}");
    }
    logs.0.lock().unwrap().extend_from_slice(first.as_bytes());

    let logs = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap();
    for text in [debug.as_str().unwrap(), logs.as_str()] {
        assert!(text.contains("session-123") && text.contains("request-456"), "{text}");
        assert!(!text.to_lowercase().contains("secret"), "{text}");
    }
    assert!(logs.contains("invocation completed"), "{logs}");
    // Both IDs are in quotes, so text that a caller puts in an ID stays inside its field.
    assert!(logs.contains(r#"invocation{request_id="request-456" session_id="session-123"}"#), "{logs}");

    // AgentCore Runtime does not relay a failed reply to its caller, who is sent to
    // the logs. The reason of a handler error must therefore be there, with the
    // sources of the error, and so must the text of a panic.
    let failing = |payload: Value| async move {
        if payload == "panic" {
            panic!("the handler lost its state");
        }
        Err::<Value, _>(Unavailable(std::io::Error::other("the key is denied")))
    };
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(failing)).await;
    let headers = [(SESSION, "session-123"), (REQUEST_ID, "request-789")];
    // The reply holds the text of the error only.
    let unavailable = serde_json::json!({ "error": "the model is unavailable" });
    assert_eq!(server.invoke(&headers, "{}").await, (StatusCode::INTERNAL_SERVER_ERROR, unavailable));
    let headers = [(SESSION, "session-123"), (REQUEST_ID, "request-panic")];
    assert_eq!(server.invoke(&headers, "\"panic\"").await.0, StatusCode::INTERNAL_SERVER_ERROR);
    server.stop().await;
    let logs = String::from_utf8(buffer.0.lock().unwrap().clone()).unwrap();
    for (text, cause, request_id) in [
        ("the model is unavailable", "the key is denied", "request-789"),
        ("the invocation handler panicked", "the handler lost its state", "request-panic"),
    ] {
        let reason = logs.lines().find(|line| line.contains(text)).expect(&logs);
        assert!(reason.contains("ERROR") && reason.contains(cause), "{reason}");
        assert!(reason.contains(request_id) && reason.contains("session-123"), "{reason}");
    }

    // A subscriber that keeps warnings and errors only still gets the IDs with them.
    {
        let quiet = LogBuffer::default();
        let writer = quiet.clone();
        let subscriber = tracing_subscriber::fmt()
            .with_ansi(false)
            .with_max_level(tracing::Level::WARN)
            .with_writer(move || writer.clone())
            .finish();
        let _quiet = tracing::subscriber::set_default(subscriber);
        let server = Server::start(BedrockAgentCoreApp::builder().invocation(failing)).await;
        let headers = [(SESSION, "session-123"), (REQUEST_ID, "request-quiet")];
        assert_eq!(server.invoke(&headers, "{}").await.0, StatusCode::INTERNAL_SERVER_ERROR);
        server.stop().await;
        let logs = String::from_utf8(quiet.0.lock().unwrap().clone()).unwrap();
        let reason = logs.lines().find(|line| line.contains("the model is unavailable")).expect(&logs);
        assert!(reason.contains("request-quiet") && reason.contains("session-123"), "{reason}");
        assert!(!logs.contains("INFO"), "{logs}");
    }

    // The same holds for a request that the server refuses. (body, what the log must
    // name, what it must not hold)
    #[derive(serde::Deserialize)]
    struct Typed {
        #[allow(dead_code, reason = "the test only decodes it")]
        count: u64,
    }
    let typed = |_request: Typed| async { Ok::<_, BoxError>("ok") };
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(typed).body_limit(64)).await;
    let large = format!(r#"{{"count":1,"pad":"{}"}}"#, "x".repeat(64));
    let (bad_request, too_large) = (StatusCode::BAD_REQUEST, StatusCode::PAYLOAD_TOO_LARGE);
    let cases = [
        // The session header is logged although the body cannot be parsed.
        (r#"{"count": "#, bad_request, "Invalid JSON", "EOF while parsing"),
        ("{}", bad_request, "Invalid request body format", "missing field `count`"),
        // Serde quotes the value that has the wrong type. It is payload.
        (
            r#"{"count":"SECRET-PAYLOAD"}"#,
            bad_request,
            "Invalid request body format",
            "does not fit the request type at line 1",
        ),
        // The line names the limit and the setting that changes it.
        (
            large.as_str(),
            too_large,
            "Request body is too large",
            "The limit is 64 bytes. Builder::body_limit changes it.",
        ),
    ];
    for (n, (body, status, error, details)) in cases.into_iter().enumerate() {
        let request_id = format!("request-refused-{n}");
        let headers = [(SESSION, "session-123"), (REQUEST_ID, request_id.as_str())];
        assert_eq!(server.invoke(&headers, body.to_owned()).await.0, status, "{body}");
        let logs = String::from_utf8(buffer.0.lock().unwrap().clone()).unwrap();
        let lines: Vec<&str> = logs.lines().filter(|line| line.contains(&request_id)).collect();
        let reason = lines.iter().find(|line| line.contains("invocation request refused")).expect(&logs);
        assert!(reason.contains("WARN") && reason.contains(error) && reason.contains(details), "{reason}");
        assert!(lines.iter().all(|line| line.contains("session-123") && !line.contains("SECRET")), "{lines:?}");
    }
    server.stop().await;

    // AgentCore Runtime can end the process before the grace period ends. The work
    // that a shutdown interrupts is therefore named at the signal: the invocation
    // with its IDs, and the tracked tasks. A handler that the deadline cancels is
    // logged with the IDs of its invocation too.
    let (entered_tx, mut entered) = tokio::sync::mpsc::unbounded_channel();
    let stuck = move |_payload: Value, ctx: RequestContext| {
        let entered = entered_tx.clone();
        async move {
            let _guard = ctx.tasks().track("report");
            let _ = entered.send(());
            std::future::pending::<Result<Value, BoxError>>().await
        }
    };
    let grace = std::time::Duration::from_millis(100);
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(stuck).shutdown_grace(grace)).await;
    let request = client().post(format!("{}/invocations", server.base)).body("{}");
    let reply = tokio::spawn(request.header(SESSION, "session-123").header(REQUEST_ID, "request-000").send());
    entered.recv().await.unwrap();
    assert_eq!(server.ping().await["status"], "HealthyBusy");
    assert_eq!(server.shut_down().await.0.unwrap_err().kind(), ErrorKind::ShutdownTimeout);
    assert_eq!(reply.await.unwrap().unwrap().status(), StatusCode::SERVICE_UNAVAILABLE);
    let logs = String::from_utf8(buffer.0.lock().unwrap().clone()).unwrap();
    for text in ["shutdown signal received while this invocation is in flight", "dropped before its handler returned"] {
        let line = logs.lines().find(|line| line.contains(text)).expect(&logs);
        assert!(line.contains("WARN") && line.contains("request-000") && line.contains("session-123"), "{line}");
    }
    // The servers of this test that were idle at their shutdown wrote the line too.
    let started = logs.lines().rfind(|line| line.contains("shutdown started")).expect(&logs);
    assert!(started.contains(r#"invocations=1 active_tasks=1 tasks=["report"]"#), "{started}");
    let busy = logs.lines().find(|line| line.contains("ping status changed")).expect(&logs);
    assert!(busy.contains("from=Healthy to=HealthyBusy active_tasks=1"), "{busy}");

    // AgentCore Runtime pings a session every two seconds. A ping handler that
    // panics is logged when it starts to panic, not for each ping.
    let panics = || -> PingStatus { panic!("the ping handler has no status") };
    let echo = |payload: Value| async { Ok::<_, BoxError>(payload) };
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(echo).ping(panics)).await;
    for _ in 0..3 {
        assert_eq!(server.ping().await["status"], "Healthy");
    }
    server.stop().await;
    let logs = String::from_utf8(buffer.0.lock().unwrap().clone()).unwrap();
    let warned: Vec<&str> = logs.lines().filter(|line| line.contains("the custom ping handler panicked")).collect();
    assert_eq!(warned.len(), 1, "{logs}");
    assert!(warned[0].contains("the ping handler has no status"), "{warned:?}");
    #[cfg(feature = "identity")]
    identity::logs_and_replies_hold_no_credential(&buffer).await;
}

/// Identity operations in a handler that logs everything it has at hand.
#[cfg(feature = "identity")]
mod identity {
    use aws_sdk_bedrockagentcore::{
        Client,
        config::http::HttpResponse,
        operation::{
            get_resource_api_key::GetResourceApiKeyOutput, get_resource_oauth2_token::GetResourceOauth2TokenOutput,
        },
        primitives::SdkBody,
    };
    use aws_smithy_mocks::{RuleMode, mock, mock_client};
    use bedrock_agentcore::identity::{AuthFlow, IdentityClient};

    use super::*;

    pub(super) async fn logs_and_replies_hold_no_credential(logs: &LogBuffer) {
        let key = mock!(Client::get_resource_api_key)
            .match_requests(|request| request.resource_credential_provider_name() == Some("orders"))
            .then_output(|| GetResourceApiKeyOutput::builder().api_key("SECRET-KEY").build().unwrap());
        // A reply that cannot be decoded. The SDK error keeps its body.
        let undecodable = mock!(Client::get_resource_api_key)
            .match_requests(|request| request.resource_credential_provider_name() == Some("broken"))
            .then_http_response(|| {
                HttpResponse::new(200u16.try_into().unwrap(), SdkBody::from(r#"{"apiKey":"SECRET-BODY""#))
            });
        let token = mock!(Client::get_resource_oauth2_token)
            .then_output(|| GetResourceOauth2TokenOutput::builder().access_token("SECRET-ACCESS").build());
        let identity = IdentityClient::from_client(mock_client!(
            aws_sdk_bedrockagentcore,
            RuleMode::MatchAny,
            [&key, &undecodable, &token]
        ));

        let handler = move |_payload: Value, ctx: RequestContext| {
            let identity = identity.clone();
            async move {
                let key_request = identity.api_key("orders");
                let token_request = identity
                    .oauth2_token("orders", AuthFlow::M2m)
                    .workload_access_token(ctx.workload_access_token().cloned().ok_or("no token")?)
                    .callback_url("https://secret.example/explicit")
                    .custom_state("SECRET-STATE")
                    .custom_parameters([("secret-name", "SECRET-VALUE")]);
                let requests = format!("{identity:?} {key_request:?} {token_request:?}");
                let key = key_request.send().await?;
                let token = token_request.send().await?;
                let error = identity.api_key("broken").send().await.unwrap_err();
                let seen = format!("{requests} {key:?} {token:?} {error:?} {error:#?} {error}");
                tracing::info!(?identity, ?key, ?token, ?error, %error, requests, "identity");
                if key.expose() != "SECRET-KEY" || token.expose() != "SECRET-ACCESS" {
                    return Err("the handler did not get the credentials".into());
                }
                Ok::<_, BoxError>(seen)
            }
        };
        let server = Server::start(BedrockAgentCoreApp::builder().invocation(handler)).await;
        let headers = [
            (SESSION, "session-123"),
            (REQUEST_ID, "request-identity"),
            (WAT, "SECRET-TOKEN"),
            ("oauth2callbackurl", "https://secret.example/callback"),
        ];
        let (status, seen) = server.invoke(&headers, "{}").await;
        assert_eq!(status, StatusCode::OK, "{seen}");

        // The runtime logs the error that a handler returns.
        let failing = |_payload: Value| async {
            let identity = IdentityClient::from_client(mock_client!(
                aws_sdk_bedrockagentcore,
                [&mock!(Client::get_resource_api_key).then_http_response(|| {
                    HttpResponse::new(200u16.try_into().unwrap(), SdkBody::from(r#"{"apiKey":"SECRET-BODY""#))
                })]
            ));
            Ok::<_, bedrock_agentcore::Error>(identity.api_key("broken").send().await?.expose().to_owned())
        };
        server.stop().await;
        let server = Server::start(BedrockAgentCoreApp::builder().invocation(failing)).await;
        let (status, reply) = server.invoke(&headers, "{}").await;
        assert_eq!(
            (status, &reply),
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                &serde_json::json!({ "error": "GetResourceApiKey for provider broken failed: service error (HTTP 200)" })
            )
        );
        server.stop().await;

        let logs = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap();
        let identity_logs: Vec<&str> = logs.lines().filter(|line| line.contains("request-identity")).collect();
        assert!(identity_logs.iter().any(|line| line.contains("Sensitive Data Redacted")), "{logs}");
        assert!(
            identity_logs
                .iter()
                .any(|line| line.contains("ERROR") && line.contains("GetResourceApiKey for provider broken failed")),
            "{logs}"
        );
        for text in [seen.as_str().unwrap(), &identity_logs.join("\n")] {
            assert!(
                text.contains("GetResourceApiKey for provider broken failed") && text.contains("ApiKeyBuilder"),
                "{text}"
            );
            assert!(!text.to_lowercase().contains("secret"), "a synthetic credential appeared in Identity output");
        }
        workload_identity_exchange_is_traced_without_its_body().await;
    }

    /// The AWS SDK prints the request that it sends at the TRACE level. The body of
    /// the exchange holds the context, and then the refresh token.
    async fn workload_identity_exchange_is_traced_without_its_body() {
        use aws_sdk_bedrockagentcore::config::{Credentials, ProvideCredentials, Region, SharedCredentialsProvider};
        use aws_smithy_http_client::test_util::infallible_client_fn;
        use bedrock_agentcore::identity::WorkloadIdentityCredentials;

        let logs = LogBuffer::default();
        let writer = logs.clone();
        let subscriber = tracing_subscriber::fmt()
            .with_ansi(false)
            .with_max_level(tracing::Level::TRACE)
            .with_writer(move || writer.clone())
            .finish();
        let _trace = tracing::subscriber::set_default(subscriber);

        // The credentials expire in one minute, so the second call renews them.
        let http_client = infallible_client_fn(|_request: http::Request<SdkBody>| {
            let expiration = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() + 60;
            let credentials = serde_json::json!({
                "accessKeyId": "KEY",
                "secretAccessKey": "SECRET-ACCESS-KEY",
                "sessionToken": "SECRET-SESSION-TOKEN",
                "expiration": expiration,
            });
            let body = serde_json::json!({ "credentials": credentials, "refreshToken": "SECRET-REFRESH" });
            http::Response::builder().status(200).body(body.to_string()).unwrap()
        });
        let config = aws_types::SdkConfig::builder()
            .region(Region::new("us-west-2"))
            .credentials_provider(SharedCredentialsProvider::new(Credentials::for_tests()))
            .http_client(http_client)
            .build();
        let provider = WorkloadIdentityCredentials::new(&config);
        let ctx = RequestContext::builder("session-trace").workload_identity_context("SECRET-CONTEXT").build();
        for _ in 0..2 {
            let credentials = bedrock_agentcore::context::scope(ctx.clone(), provider.provide_credentials()).await;
            assert_eq!(credentials.unwrap().access_key_id(), "KEY");
        }

        let logs = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap();
        let requests: Vec<&str> = logs.lines().filter(|line| line.contains("transmitting request")).collect();
        assert_eq!(requests.len(), 2, "{logs}");
        // The second request sends the refresh token. The reply of this test client is
        // in memory, unlike a reply from the network, so its trace line is not checked.
        assert!(requests.iter().all(|line| !line.contains("SECRET")), "{requests:?}");
        assert!(!logs.contains("SECRET-CONTEXT"), "{logs}");
    }
}