aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
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
//! Bounded `secret.use` calls over the daemon's attested consumer routes.

use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;

use serde_json::{json, Value};
use subc_client_rs::{
    CallError, CallOptions, CloseRouteOptions, ConsumerIdentity, ConsumerOptions, RouteHandle,
    SubcConsumer, SubscribeOptions, Subscription,
};
use subc_protocol::scope::{ScopeSelector, ScopeStamp};
use subc_protocol::{BindIdentity, RouteTarget};
use zeroize::Zeroizing;

use super::vault::SecretUseTransport;

#[path = "transport_diagnostics.rs"]
pub(super) mod diagnostics;
use diagnostics::{Failure, Stage};

const UNAVAILABLE: &str = "secret.use transport unavailable";
static CONNECTION_FILE: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);

pub fn install_connection_file(path: &std::path::Path) {
    *CONNECTION_FILE
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(path.to_owned());
}

pub fn for_current_command() -> Option<SubcSecretUseTransport> {
    let path = CONNECTION_FILE.read().ok()?.clone()?;
    if !path.is_file() {
        return None;
    }
    let (_, session) = crate::secret::call_context::current_secret_consent_context()?;
    SubcSecretUseTransport::new(
        path,
        BindIdentity::new("aft-secret-use", session),
        Duration::from_secs(15),
    )
}

/// A request-addressed vault transport. Construct it at call time: a standalone
/// process has no attested AFT module identity. Never open its vault route under
/// the daemon's unprivileged `direct` principal instead.
/// One command owns one consumer connection; failed connections are discarded so
/// a later request can reconnect after the daemon returns.
#[derive(Clone)]
pub struct SubcSecretUseTransport {
    connection_file: PathBuf,
    identity: BindIdentity,
    timeout: Duration,
    worker: Arc<OnceLock<tokio::sync::mpsc::UnboundedSender<Work>>>,
    #[cfg(any(test, feature = "test-support"))]
    test_principal: Option<ConsumerIdentity>,
}

struct Work {
    params: Value,
    test_principal: Option<ConsumerIdentity>,
    deadline: tokio::time::Instant,
    reply: std::sync::mpsc::Sender<Result<Zeroizing<Vec<u8>>, Failure>>,
    failure: Arc<Mutex<Option<Failure>>>,
}

struct ConnectionConfig {
    connection_file: PathBuf,
    identity: BindIdentity,
    timeout: Duration,
}

// Both scoped secret use and daemon-owned manifest delivery use the attested
// claustrum management surface. A manifest watch deliberately has no agent scope.
async fn open_vault_route(
    consumer: &SubcConsumer,
    identity: BindIdentity,
    test_principal: Option<ConsumerIdentity>,
    scope: Option<ScopeSelector>,
    timeout: Duration,
) -> Result<RouteHandle, CallError> {
    let target = RouteTarget::ManagementSurface {
        module_id: "claustrum".into(),
    };
    let options = CallOptions {
        timeout,
        route_retry_deadline: timeout,
        ..CallOptions::default()
    };
    #[cfg(any(test, feature = "test-support"))]
    let options = match test_principal {
        Some(principal) => with_test_vault_principal(options, principal),
        None => options,
    };
    #[cfg(not(any(test, feature = "test-support")))]
    let _ = test_principal;
    match scope {
        Some(scope) => {
            consumer
                .open_route_scoped(target, identity, scope, options)
                .await
        }
        None => consumer.open_route(target, identity, options).await,
    }
}

// In-process fakes supply independent principals without changing the SDK's
// process-wide launch-nonce cache. Production calls always use SDK identity.
#[cfg(any(test, feature = "test-support"))]
fn with_test_vault_principal(mut options: CallOptions, principal: ConsumerIdentity) -> CallOptions {
    options.consumer_identity = Some(principal);
    options
}

/// A held daemon-owned route on the existing vault transport. Closing it also
/// closes its consumer so reconnects never leave an old watch subscribed.
pub struct ManagementSession {
    consumer: SubcConsumer,
    route: RouteHandle,
}

impl ManagementSession {
    pub async fn connect(connection_file: &std::path::Path) -> Result<Self, ()> {
        aft_identity_available().then_some(()).ok_or(())?;
        Self::connect_as(connection_file, None).await
    }

    async fn connect_as(
        connection_file: &std::path::Path,
        test_principal: Option<ConsumerIdentity>,
    ) -> Result<Self, ()> {
        let consumer = crate::fleet_status::connect_subc_consumer(
            "secret_transport",
            connection_file,
            ConsumerOptions::default(),
        )
        .await
        .map_err(|_| ())?;
        let route = match open_vault_route(
            &consumer,
            BindIdentity::new("aft-manifest-sync", "daemon"),
            test_principal,
            None,
            Duration::from_secs(15),
        )
        .await
        {
            Ok(route) => route,
            Err(_) => {
                let _ = consumer.close().await;
                return Err(());
            }
        };
        Ok(Self { consumer, route })
    }

    #[cfg(all(any(test, feature = "test-support"), unix))]
    pub async fn for_test(connection_file: &std::path::Path) -> Result<Self, ()> {
        Self::connect_as(
            connection_file,
            Some(ConsumerIdentity {
                module_id: "aft".into(),
                launch_nonce: "manifest-sync-test-nonce".into(),
            }),
        )
        .await
    }

    pub async fn request(&self, body: Vec<u8>) -> Result<Vec<u8>, CallError> {
        self.consumer
            .request(
                &self.route,
                body,
                CallOptions {
                    timeout: Duration::from_secs(15),
                    ..CallOptions::default()
                },
            )
            .await
    }

    pub async fn watch(&self, body: Vec<u8>) -> Result<Subscription, CallError> {
        self.consumer
            .subscribe_route(&self.route, body, SubscribeOptions::default())
            .await
    }

    pub async fn close(self) {
        let _ = self
            .consumer
            .close_handle(&self.route, CloseRouteOptions::default())
            .await;
        let _ = self.consumer.close().await;
    }
}

/// Exercise the manifest synchronizer's production transport in a supervised
/// real-daemon fixture, without starting its long-lived watch worker.
#[cfg(feature = "test-hooks")]
pub async fn manifest_latest_for_test(
    connection_file: &std::path::Path,
) -> Result<Vec<u8>, String> {
    let session = ManagementSession::connect(connection_file)
        .await
        .map_err(|()| "manifest transport unavailable".to_string())?;
    let result = session
        .request(br#"{"method":"manifest.latest","params":{}}"#.to_vec())
        .await
        .map_err(|error| error.to_string());
    session.close().await;
    result
}

impl SubcSecretUseTransport {
    /// Use AFT's daemon identity, never an agent-supplied principal.
    /// The deadline includes connection, scoped open, request, and cleanup.
    pub fn new(
        connection_file: PathBuf,
        identity: BindIdentity,
        timeout: Duration,
    ) -> Option<Self> {
        aft_identity_available().then_some(())?;
        Some(Self {
            connection_file,
            identity,
            timeout,
            worker: Arc::default(),
            #[cfg(any(test, feature = "test-support"))]
            test_principal: None,
        })
    }

    #[cfg(all(any(test, feature = "test-support"), unix))]
    pub fn for_test(
        connection_file: PathBuf,
        identity: BindIdentity,
        timeout: Duration,
        principal: ConsumerIdentity,
    ) -> Self {
        Self {
            connection_file,
            identity,
            timeout,
            worker: Arc::default(),
            test_principal: Some(principal),
        }
    }

    async fn send(
        config: &ConnectionConfig,
        consumer: &subc_client_rs::SubcConsumer,
        params: Value,
        test_principal: Option<ConsumerIdentity>,
    ) -> Result<Zeroizing<Vec<u8>>, Failure> {
        let target = &params["target"];
        if target["scheme"] != "https"
            || target
                .get("port")
                .is_some_and(|port| port.as_u64() != Some(443))
        {
            return Err(Failure::local(Stage::TargetRefused));
        }
        let stamp: ScopeStamp =
            serde_json::from_value(params.get("stamp").cloned().unwrap_or_default())
                .map_err(|_| Failure::local(Stage::StampDecode))?;
        let kind = stamp.kind;
        let scope = ScopeSelector::new(stamp.owner, stamp.scope_ref, Some(stamp.scope_epoch));
        let body = serde_json::to_vec(&json!({"method": "secret.use", "params": params}))
            .map_err(|_| Failure::local(Stage::Encode))?;
        let route = open_vault_route(
            consumer,
            config.identity.clone(),
            test_principal,
            Some(scope.clone()),
            config.timeout,
        )
        .await
        .map_err(|error| Failure::call(Stage::RouteOpen, &error).under_scope(kind, &scope))?;
        let reply = consumer
            .request(
                &route,
                body,
                CallOptions {
                    timeout: config.timeout,
                    ..CallOptions::default()
                },
            )
            .await;
        match reply {
            Ok(bytes) => {
                let bytes = Zeroizing::new(bytes);
                Ok(bytes)
            }
            // Preserve the distinction between a module Error frame and a
            // result refusal. Only allowlisted codes enter diagnostics: SDK
            // messages, detail and reply bytes could carry released material.
            Err(error @ CallError::Module(_)) => {
                let failure = Failure::call(Stage::ModuleError, &error);
                let CallError::Module(error) = error else {
                    unreachable!();
                };
                let code = Zeroizing::new(error.code);
                let _message = Zeroizing::new(error.message);
                // Retain only the classified sender error. Peer detail may
                // contain a credential and must never enter a second buffer.
                if code.as_str() == "invalid_params" {
                    Ok(Zeroizing::new(
                        br#"{"code":"invalid_params","message":""}"#.to_vec(),
                    ))
                } else {
                    Err(failure)
                }
            }
            Err(error) => Err(Failure::call(Stage::Request, &error)),
        }
    }

    #[cfg(any(test, feature = "test-support"))]
    fn dispatch(
        &self,
        params: Value,
        principal: ConsumerIdentity,
    ) -> Result<Zeroizing<Vec<u8>>, String> {
        self.dispatch_work(params, Some(principal))
            .map_err(Failure::unavailable)
    }

    fn dispatch_work(
        &self,
        params: Value,
        test_principal: Option<ConsumerIdentity>,
    ) -> Result<Zeroizing<Vec<u8>>, Failure> {
        let sender = self.worker.get_or_init(|| {
            let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
            let config = ConnectionConfig {
                connection_file: self.connection_file.clone(),
                identity: self.identity.clone(),
                timeout: self.timeout,
            };
            std::thread::spawn(move || {
                if let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                {
                    runtime.block_on(Self::serve(config, receiver));
                }
            });
            sender
        });
        let (reply, answer) = std::sync::mpsc::channel();
        let failure = Arc::new(Mutex::new(None));
        sender
            .send(Work {
                params,
                test_principal,
                deadline: tokio::time::Instant::now() + self.timeout,
                reply,
                failure: Arc::clone(&failure),
            })
            .map_err(|_| Failure::local(Stage::Worker))?;
        answer.recv_timeout(self.timeout).unwrap_or_else(|error| {
            // The worker can be closing a failed connection when the caller's
            // deadline expires. Preserve that failure and log only at the caller,
            // so cleanup and deadline races never emit two warnings for one call.
            Err(failure
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .clone()
                .unwrap_or_else(|| {
                    Failure::local(match error {
                        std::sync::mpsc::RecvTimeoutError::Timeout => Stage::Deadline,
                        std::sync::mpsc::RecvTimeoutError::Disconnected => Stage::Worker,
                    })
                }))
        })
    }

    async fn serve(
        config: ConnectionConfig,
        mut receiver: tokio::sync::mpsc::UnboundedReceiver<Work>,
    ) {
        let mut consumer = None;
        while let Some(work) = receiver.recv().await {
            let result = tokio::time::timeout_at(work.deadline, async {
                if consumer.is_none() {
                    consumer = Some(
                        crate::fleet_status::connect_subc_consumer(
                            "secret_use",
                            &config.connection_file,
                            ConsumerOptions::default(),
                        )
                        .await
                        .map_err(|error| Failure::connect(&error))?,
                    );
                }
                Self::send(
                    &config,
                    consumer.as_ref().expect("connected consumer"),
                    work.params,
                    work.test_principal,
                )
                .await
            })
            .await
            .unwrap_or_else(|_| Err(Failure::local(Stage::Deadline)));
            if let Err(error) = &result {
                *work
                    .failure
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(error.clone());
                if let Some(failed) = consumer.take() {
                    let _ = tokio::time::timeout(Duration::from_secs(1), failed.close()).await;
                }
            }
            let _ = work.reply.send(result);
        }
        if let Some(consumer) = consumer {
            let _ = tokio::time::timeout(Duration::from_secs(1), consumer.close()).await;
        }
    }
}

fn aft_identity_available() -> bool {
    use crate::registration;
    registration::module_consumer_allowed() && registration::module_id().as_deref() == Some("aft")
}

impl SecretUseTransport for SubcSecretUseTransport {
    fn secret_use(&self, params: Value) -> Result<Zeroizing<Vec<u8>>, String> {
        #[cfg(any(test, feature = "test-support"))]
        if let Some(principal) = &self.test_principal {
            return self.dispatch(params, principal.clone());
        }
        if !aft_identity_available() {
            return Err(Failure::local(Stage::IdentityMissing).unavailable());
        }
        self.dispatch_work(params, None)
            .map_err(Failure::unavailable)
    }
}

#[cfg(any(test, feature = "test-support"))]
#[path = "transport_tests.rs"]
#[cfg_attr(not(test), allow(dead_code, unused_imports))]
pub mod tests;

#[cfg(any(test, feature = "test-support"))]
#[path = "transport_fake.rs"]
pub mod fake;