Skip to main content

adk_website/deploy/
agency.rs

1//! Agency mode: one harness for many sites, each isolated (spec 3.5 §7.22, §7.17, A-I22).
2//!
3//! | Layer | Isolation |
4//! |---|---|
5//! | Kernel | Each site's two partitions carry the site as tenant and deny crossings; a request from one site's back office into another's — the coordinator's too — is denied and recorded as a crossing |
6//! | Edge | Each site has its own edge, capabilities and stores; [`AgencyRouter`] sends a request only to the edge of the site its host names, and refuses and records any other |
7
8use std::collections::BTreeMap;
9use std::sync::Arc;
10
11use adk_core::audit_log::{AuditActor, AuditTrail};
12use adk_core::{AdkError, Result};
13use adk_harness::website::{SitePartitions, SiteRef};
14use adk_kernel::{CrossingAccess, CrossingResource, CrossingRoute, PartitionPolicy, Partitions};
15use axum::body::Body;
16use axum::http::{Request, StatusCode, header};
17use axum::response::{IntoResponse, Response};
18use serde_json::json;
19use tower::ServiceExt;
20
21use crate::audit;
22
23/// The tool name under which a back-office agent's request reaches another site: any
24/// read of another site's memory, drivers or sessions (spec 3.5 A-I22).
25pub const CROSS_SITE_TOOL: &str = "cross_site_request";
26
27/// The record of a request an agency refused at the edge (spec 3.5 §9.3).
28pub const REQUEST_REFUSED: &str = "awp.request.refused";
29
30/// The sites one harness runs (spec 3.5 A-I22).
31///
32/// # Example
33///
34/// ```rust
35/// use adk_harness::website::SiteRef;
36/// use adk_kernel::Partitions;
37/// use adk_website::deploy::Agency;
38///
39/// # #[tokio::main(flavor = "current_thread")]
40/// # async fn main() {
41/// let mut agency = Agency::new(Partitions::in_memory());
42/// agency.add(SiteRef::new(uuid::Uuid::new_v4(), "bakery", "https://bakery.example")).await.unwrap();
43/// let again = agency.add(SiteRef::new(uuid::Uuid::new_v4(), "bakery", "https://other.example")).await;
44/// assert!(again.is_err(), "no two sites share a name");
45/// # }
46/// ```
47pub struct Agency {
48    table: Partitions,
49    sites: BTreeMap<String, (SiteRef, SitePartitions)>,
50}
51
52impl Agency {
53    /// An agency over the kernel's partition `table`.
54    pub fn new(table: Partitions) -> Self {
55        Self { table, sites: BTreeMap::new() }
56    }
57
58    /// Adds `site` and installs its partitions; refuses a name or an id another site has.
59    ///
60    /// # Errors
61    ///
62    /// A duplicate site, or the partition table's error.
63    pub async fn add(&mut self, site: SiteRef) -> Result<SitePartitions> {
64        if self.sites.contains_key(&site.name) || self.sites.values().any(|(s, _)| s.id == site.id)
65        {
66            return Err(AdkError::config(format!(
67                "the agency already runs a site named {} or with its id; every site needs its own (A-I22)",
68                site.name
69            )));
70        }
71        let partitions = SitePartitions::new(&site);
72        partitions
73            .install(&self.table, AuditActor::default())
74            .await
75            .map_err(|e| AdkError::config(e.to_string()))?;
76        self.sites.insert(site.name.clone(), (site, partitions.clone()));
77        Ok(partitions)
78    }
79
80    /// The sites, by name.
81    pub fn sites(&self) -> impl Iterator<Item = &SiteRef> {
82        self.sites.values().map(|(site, _)| site)
83    }
84
85    /// The partitions of site `name`.
86    pub fn partitions(&self, name: &str) -> Option<&SitePartitions> {
87        self.sites.get(name).map(|(_, partitions)| partitions)
88    }
89
90    /// The crossing policy of site `name`'s back office with `coordinator` as its
91    /// coordinator, deciding [`CROSS_SITE_TOOL`] as a crossing into the partition its
92    /// `partition` argument names (spec 3.5 A-I22): denied and recorded, since every site's
93    /// partitions deny crossings.
94    ///
95    /// # Errors
96    ///
97    /// An unknown site.
98    pub fn back_office_policy(&self, name: &str, coordinator: &str) -> Result<PartitionPolicy> {
99        let partitions = self
100            .partitions(name)
101            .ok_or_else(|| AdkError::config(format!("the agency runs no site named {name}")))?;
102        Ok(self
103            .table
104            .policy(partitions.back_office().id.clone())
105            .with_coordinator(coordinator)
106            .with_crossing_tool(
107                CROSS_SITE_TOOL,
108                CrossingRoute::argument(
109                    CrossingResource::Memory,
110                    CrossingAccess::Read,
111                    "another site's memory",
112                ),
113            ))
114    }
115
116    /// The partition table.
117    pub fn table(&self) -> &Partitions {
118        &self.table
119    }
120}
121
122/// Sends each request to the edge of the site its `Host` names; a request for any other host
123/// is refused with `404` and recorded (spec 3.5 A-I22).
124#[derive(Clone)]
125pub struct AgencyRouter {
126    edges: Arc<BTreeMap<String, axum::Router>>,
127    audit: Option<AuditTrail>,
128}
129
130impl AgencyRouter {
131    /// A router over each site's edge, by host.
132    pub fn new(edges: BTreeMap<String, axum::Router>) -> Self {
133        Self { edges: Arc::new(edges), audit: None }
134    }
135
136    /// Records refusals in `trail`.
137    #[must_use]
138    pub fn with_audit(mut self, trail: AuditTrail) -> Self {
139        self.audit = Some(trail);
140        self
141    }
142
143    /// The router to serve.
144    pub fn router(self) -> axum::Router {
145        axum::Router::new().fallback(move |request: Request<Body>| {
146            let agency = self.clone();
147            async move { agency.dispatch(request).await }
148        })
149    }
150
151    async fn dispatch(&self, request: Request<Body>) -> Response {
152        // HTTP/2 carries the host in the URI's authority, HTTP/1.1 in `Host`.
153        let host = request
154            .headers()
155            .get(header::HOST)
156            .and_then(|value| value.to_str().ok())
157            .or_else(|| request.uri().host())
158            .map(|host| host.split(':').next().unwrap_or(host).to_ascii_lowercase())
159            .unwrap_or_default();
160        if let Some(edge) = self.edges.get(&host) {
161            return match edge.clone().oneshot(request).await {
162                Ok(response) => response,
163                Err(never) => match never {},
164            };
165        }
166        audit::record(
167            self.audit.as_ref(),
168            REQUEST_REFUSED,
169            AuditActor::default(),
170            json!({ "host": host, "path": request.uri().path(), "reason": "not_a_site_of_this_agency" }),
171        )
172        .await;
173        tracing::info!(host, path = request.uri().path(), "awp.request.refused");
174        (StatusCode::NOT_FOUND, axum::Json(json!({ "awp": "2.0", "error": { "code": "resource_not_found", "message": "no site is served at this host", "retryable": false } })))
175            .into_response()
176    }
177}