Skip to main content

alien_signing/
binding.rs

1//! Binding values an enforcer computes from its own install.
2//!
3//! A binding tells a workload which resource to use, such as the bucket
4//! behind `ALIEN_UPLOADS_BINDING`. On a protected install the control plane
5//! must not choose it, or it could point the vendor's code at another
6//! customer's bucket. Each value comes from the first of:
7//!
8//! 1. [`binding_env`]: setup names each owned resource `<prefix>-<id>`, so for
9//!    most types the value follows from the install's prefix, account and
10//!    region. The engine and every enforcer use this one function, and a test
11//!    in the engine checks that its controllers produce the same values.
12//! 2. The enforcer's own cloud reads, for types whose value isn't a name
13//!    (a database endpoint, a service URL): it describes the resource it
14//!    finds by the derived name or setup's tag in its own install.
15//! 3. A signed `config/v1`, for resources outside the customer's cloud.
16//!
17//! [`resolve_bindings`] applies that order. The control plane supplies none of
18//! them.
19
20use std::collections::{BTreeMap, BTreeSet};
21
22use alien_error::AlienError;
23use serde_json::json;
24
25use crate::error::{ErrorData, Result};
26
27/// Where an enforcer runs, as it learned from its own identity.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct BindingContext {
30    /// `aws`, `gcp`, `azure`, `kubernetes` or `machines`.
31    pub platform: String,
32    /// The install's resource prefix.
33    pub prefix: String,
34    /// AWS account id or GCP project id.
35    pub account: String,
36    /// Region, where the platform has one.
37    pub region: Option<String>,
38}
39
40/// The environment variable that carries binding `id`.
41pub fn binding_env_name(id: &str) -> String {
42    format!("ALIEN_{}_BINDING", id.replace('-', "_").to_uppercase())
43}
44
45/// Id of the vault a deployer writes its own secrets into.
46pub const DEPLOYER_SECRETS_VAULT: &str = "deployer-secrets";
47
48/// What an enforcer knows about the resource a workload runs as, to check the workload's own
49/// binding against. The binding tells the workload's code where to reach itself, so every field
50/// that picks a destination has to come from the install, not from the control plane.
51#[derive(Debug, Clone, Default, PartialEq, Eq)]
52pub struct OwnBindingFacts {
53    /// Where the enforcer runs.
54    pub context: Option<BindingContext>,
55    /// The function, service, Container App or machine container the binding must name.
56    pub resource_name: String,
57    /// The Azure resource group of the install.
58    pub resource_group: Option<String>,
59    /// The Cloud Run location the service is in: the one the enforcer is configured with.
60    pub location: Option<String>,
61    /// The addresses the enforcer reads from the cloud for the resource: the only ones any URL
62    /// field (`privateUrl`, `publicUrl`, a Lambda function's `url`) may carry. A name the
63    /// control plane picked, such as a custom or generated domain, is in none of them.
64    pub urls: Vec<String>,
65}
66
67/// Check `value`, a workload's own binding, against `facts`: the binding of the platform the
68/// workload runs on, naming the workload's own resource and nothing else, with no field the
69/// install doesn't decide and every URL one of `facts.urls`.
70pub fn check_own_binding(value: &str, facts: &OwnBindingFacts) -> std::result::Result<(), String> {
71    let context = facts
72        .context
73        .as_ref()
74        .ok_or("the enforcer knows no install to check it against")?;
75    let binding: serde_json::Value = serde_json::from_str(value)
76        .map_err(|_| "the own binding isn't a JSON object".to_string())?;
77    let object = binding
78        .as_object()
79        .ok_or("the own binding isn't a JSON object")?;
80    let text = |key: &str| object.get(key).and_then(|value| value.as_str());
81    let expect = |key: &str, expected: &str| match text(key) {
82        Some(found) if found == expected => Ok(()),
83        _ => Err(format!(
84            "its {key} is {}, not {expected}",
85            object
86                .get(key)
87                .map_or("missing".to_string(), |v| v.to_string())
88        )),
89    };
90    let url = |key: &str, required: bool| match object.get(key) {
91        None if !required => Ok(()),
92        None => Err(format!("it has no {key}")),
93        Some(found) => {
94            let found = found
95                .as_str()
96                .ok_or_else(|| format!("its {key} isn't a URL"))?;
97            let same = |url: &String| url.trim_end_matches('/') == found.trim_end_matches('/');
98            if facts.urls.iter().any(same) {
99                Ok(())
100            } else {
101                Err(format!(
102                    "its {key} is {found}, which is no URL the cloud reports for {}",
103                    facts.resource_name
104                ))
105            }
106        }
107    };
108    let only = |keys: &[&str]| {
109        for key in object.keys() {
110            if !keys.contains(&key.as_str()) {
111                return Err(format!(
112                    "it has a field {key} the platform's binding doesn't"
113                ));
114            }
115        }
116        Ok(())
117    };
118    let name = facts.resource_name.as_str();
119    match context.platform.as_str() {
120        "aws" => {
121            only(&["service", "workerName", "region", "url"])?;
122            expect("service", "lambda")?;
123            expect("workerName", name)?;
124            expect(
125                "region",
126                context
127                    .region
128                    .as_deref()
129                    .ok_or("the enforcer knows no region")?,
130            )?;
131            // Lambda is invoked by name through the cloud API. The enforcer reads no address for
132            // it, so the binding carries none: an API Gateway address can't be told from one the
133            // control plane created.
134            url("url", false)?;
135        }
136        "gcp" => {
137            only(&[
138                "service",
139                "projectId",
140                "serviceName",
141                "location",
142                "privateUrl",
143                "publicUrl",
144            ])?;
145            expect("service", "cloudrun")?;
146            expect("projectId", &context.account)?;
147            expect("serviceName", name)?;
148            expect(
149                "location",
150                facts
151                    .location
152                    .as_deref()
153                    .ok_or("the enforcer found no such service to read its location from")?,
154            )?;
155            url("privateUrl", true)?;
156            url("publicUrl", false)?;
157        }
158        "azure" => {
159            only(&[
160                "service",
161                "subscriptionId",
162                "resourceGroupName",
163                "containerAppName",
164                "privateUrl",
165                "publicUrl",
166            ])?;
167            expect("service", "containerapp")?;
168            expect("subscriptionId", &context.account)?;
169            expect(
170                "resourceGroupName",
171                facts
172                    .resource_group
173                    .as_deref()
174                    .ok_or("the enforcer knows no resource group")?,
175            )?;
176            expect("containerAppName", name)?;
177            url("privateUrl", true)?;
178            url("publicUrl", false)?;
179        }
180        "machines" => {
181            only(&[
182                "service",
183                "containerName",
184                "internalUrl",
185                "internalUrls",
186                "publicUrl",
187            ])?;
188            // The backend's name, not an address: any plain identifier is fine.
189            if let Some(service) = object.get("service") {
190                let plain = service.as_str().is_some_and(|found| {
191                    !found.is_empty()
192                        && found.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
193                });
194                if !plain {
195                    return Err(format!("field service is {service}, not a plain name"));
196                }
197            }
198            expect("containerName", name)?;
199            // A machine container is reached at `<name>.svc` inside its cluster.
200            let internal = |found: &serde_json::Value, key: &str| {
201                let found = found.as_str().unwrap_or_default();
202                let parsed = url::Url::parse(found).ok().filter(|parsed| {
203                    parsed.scheme() == "http"
204                        && parsed.host_str() == Some(&format!("{name}.svc"))
205                        && parsed.port().is_some()
206                        && parsed.username().is_empty()
207                        && parsed.password().is_none()
208                        && matches!(parsed.path(), "" | "/")
209                        && parsed.query().is_none()
210                        && parsed.fragment().is_none()
211                });
212                if parsed.is_some() {
213                    Ok(())
214                } else {
215                    Err(format!(
216                        "its {key} is {found}, not an address of {name}.svc"
217                    ))
218                }
219            };
220            if let Some(found) = object.get("internalUrl") {
221                internal(found, "internalUrl")?;
222            }
223            for found in object
224                .get("internalUrls")
225                .and_then(|urls| urls.as_object())
226                .into_iter()
227                .flat_map(|urls| urls.values())
228            {
229                internal(found, "internalUrls")?;
230            }
231            if object
232                .get("internalUrls")
233                .is_some_and(|urls| !urls.is_object())
234            {
235                return Err("its internalUrls isn't a map".to_string());
236            }
237            url("publicUrl", false)?;
238        }
239        other => return Err(format!("{other} has no own binding the enforcer can check")),
240    }
241    Ok(())
242}
243
244/// Binding values derived from the install, and the bindings that need
245/// another source.
246#[derive(Debug, Clone, Default, PartialEq, Eq)]
247pub struct Bindings {
248    /// Values by environment name.
249    pub values: BTreeMap<String, String>,
250    /// Resource id to type, for bindings whose value doesn't follow from the
251    /// install's names.
252    pub unresolved: BTreeMap<String, String>,
253}
254
255/// The value of every binding in `bindings` (resource id to resource type)
256/// that follows from the install, by environment name.
257///
258/// Every resource is taken to be Frozen, which setup creates; see [`binding_env_with`] for a
259/// stack that also has Live resources.
260pub fn binding_env(
261    bindings: &BTreeMap<String, String>,
262    context: &BindingContext,
263) -> Result<Bindings> {
264    binding_env_with(bindings, &BTreeSet::new(), context)
265}
266
267/// [`binding_env`], where `live` holds the ids of the signed stack's Live resources. A Live
268/// resource is created by its controller, which names a GCP queue's subscription `<topic>-sub`
269/// and keeps a KV store in the `(default)` Firestore database, in the collection
270/// `kv-<prefix>-<id>`; a Frozen one is created by setup, which names them differently.
271pub fn binding_env_with(
272    bindings: &BTreeMap<String, String>,
273    live: &BTreeSet<String>,
274    context: &BindingContext,
275) -> Result<Bindings> {
276    let mut derived = Bindings::default();
277    for (id, resource_type) in bindings {
278        let name = format!("{}-{id}", context.prefix);
279        let region = || {
280            context
281                .region
282                .clone()
283                .ok_or_else(|| refused(id, resource_type, context, "the enforcer knows no region"))
284        };
285        let value = match (context.platform.as_str(), resource_type.as_str()) {
286            ("aws", "storage") => json!({ "service": "s3", "bucketName": name }),
287            ("aws", "kv") => {
288                json!({ "service": "dynamodb", "tableName": name, "region": region()? })
289            }
290            ("aws", "queue") => json!({
291                "service": "sqs",
292                "queueUrl": format!("https://sqs.{}.amazonaws.com/{}/{name}", region()?, context.account),
293            }),
294            ("aws", "vault") => json!({ "service": "parameter-store", "vaultPrefix": name }),
295            ("gcp", "storage") => json!({ "service": "gcs", "bucketName": name }),
296            ("gcp", "vault") => json!({ "service": "secret-manager", "vaultPrefix": name }),
297            // Setup creates the topic `<prefix>-<id>` with the pull subscription
298            // `<prefix>-<id>-default`, and a Firestore database `<prefix>-<id>` whose
299            // collection is the resource id.
300            ("gcp", "queue") => json!({
301                "service": "pubsub",
302                "topic": name,
303                "subscription": format!("{name}{}", if live.contains(id) { "-sub" } else { "-default" }),
304            }),
305            ("gcp", "kv") if live.contains(id) => json!({
306                "service": "firestore",
307                "projectId": context.account,
308                "databaseId": "(default)",
309                "collectionName": format!("kv-{name}").to_lowercase().replace('_', "-"),
310            }),
311            ("gcp", "kv") => json!({
312                "service": "firestore",
313                "projectId": context.account,
314                "databaseId": name,
315                "collectionName": id,
316            }),
317            // Azure names the deployer secrets vault with a random suffix, so the enforcer
318            // finds it in its own group instead of deriving it.
319            ("azure", "vault") if id != DEPLOYER_SECRETS_VAULT => {
320                json!({ "service": "key-vault", "vaultName": name })
321            }
322            _ => {
323                derived.unresolved.insert(id.clone(), resource_type.clone());
324                continue;
325            }
326        };
327        derived
328            .values
329            .insert(binding_env_name(id), canonical(&value));
330    }
331    Ok(derived)
332}
333
334/// Every binding's value, by environment name: derived values first, then
335/// what the enforcer read from its own cloud (by resource id), then values a
336/// verified `config/v1` carries (by resource id). A source never overrides an
337/// earlier one, and a binding none of them covers is refused by name.
338pub fn resolve_bindings(
339    derived: Bindings,
340    read: &BTreeMap<String, String>,
341    signed_config: &BTreeMap<String, serde_json::Value>,
342) -> Result<BTreeMap<String, String>> {
343    let mut values = derived.values;
344    for (id, resource_type) in &derived.unresolved {
345        let value = match (read.get(id), signed_config.get(id)) {
346            (Some(value), _) => value.clone(),
347            (None, Some(value)) => canonical(value),
348            (None, None) => {
349                return Err(AlienError::new(ErrorData::WorkloadRefused {
350                    workload: id.clone(),
351                    reason: format!(
352                        "binding '{id}' ({resource_type}) has no value: it doesn't follow from the install's names, the enforcer found no such resource in its install, and no signed config sets it"
353                    ),
354                }))
355            }
356        };
357        values.insert(binding_env_name(id), value);
358    }
359    Ok(values)
360}
361
362/// JSON with object keys sorted, so a binding's value is the same in every
363/// enforcer build, whichever `serde_json` features the build enables.
364fn canonical(value: &serde_json::Value) -> String {
365    fn sorted(value: &serde_json::Value) -> serde_json::Value {
366        match value {
367            serde_json::Value::Object(map) => {
368                let keys: BTreeMap<&String, &serde_json::Value> = map.iter().collect();
369                serde_json::Value::Object(
370                    keys.into_iter()
371                        .map(|(key, value)| (key.clone(), sorted(value)))
372                        .collect(),
373                )
374            }
375            serde_json::Value::Array(items) => {
376                serde_json::Value::Array(items.iter().map(sorted).collect())
377            }
378            other => other.clone(),
379        }
380    }
381    sorted(value).to_string()
382}
383
384fn refused(
385    id: &str,
386    resource_type: &str,
387    context: &BindingContext,
388    reason: &str,
389) -> AlienError<ErrorData> {
390    AlienError::new(ErrorData::WorkloadRefused {
391        workload: id.to_string(),
392        reason: format!(
393            "binding '{id}' ({resource_type} on {}): {reason}",
394            context.platform
395        ),
396    })
397}