1use std::collections::{BTreeMap, BTreeSet};
21
22use alien_error::AlienError;
23use serde_json::json;
24
25use crate::error::{ErrorData, Result};
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct BindingContext {
30 pub platform: String,
32 pub prefix: String,
34 pub account: String,
36 pub region: Option<String>,
38}
39
40pub fn binding_env_name(id: &str) -> String {
42 format!("ALIEN_{}_BINDING", id.replace('-', "_").to_uppercase())
43}
44
45pub const DEPLOYER_SECRETS_VAULT: &str = "deployer-secrets";
47
48#[derive(Debug, Clone, Default, PartialEq, Eq)]
52pub struct OwnBindingFacts {
53 pub context: Option<BindingContext>,
55 pub resource_name: String,
57 pub resource_group: Option<String>,
59 pub location: Option<String>,
61 pub urls: Vec<String>,
65}
66
67pub 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 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 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 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
247pub struct Bindings {
248 pub values: BTreeMap<String, String>,
250 pub unresolved: BTreeMap<String, String>,
253}
254
255pub fn binding_env(
261 bindings: &BTreeMap<String, String>,
262 context: &BindingContext,
263) -> Result<Bindings> {
264 binding_env_with(bindings, &BTreeSet::new(), context)
265}
266
267pub 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 ("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", "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
334pub 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
362fn 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}