Skip to main content

alien_core/
sandbox_setup_inputs.rs

1//! The facts an AWS sandbox's setup renders its scaffolding from. Setup applies them and the
2//! runtime never re-reads them, so a change to any of them needs setup to run again.
3
4use alien_error::AlienError;
5use serde_json::Value;
6
7use crate::remote_bindings::{
8    remote_binding_for_entry, remote_binding_is_deliverable, RemoteBindingDefinition,
9};
10use crate::sandbox_build_role::SandboxBuildRole;
11use crate::sandbox_egress::{sandbox_egress_network, sandbox_needs_connector};
12use crate::{
13    parse_ecr_image_repository, ErrorData, ResourceLifecycle, Result, Sandbox, SandboxCode, Stack,
14    BUNDLE_REGION_TOKEN,
15};
16
17/// The account a sandbox's scaffolding is rendered into.
18#[derive(Debug, Clone, Copy)]
19pub struct SetupAccount<'a> {
20    pub partition: &'a str,
21    pub account_id: &'a str,
22    pub region: &'a str,
23}
24
25/// For comparing two stacks without an account. The region stays the token so a `{region}` host
26/// and a literal region never render the same ARN.
27pub const SETUP_INPUTS_COMPARISON_ACCOUNT: SetupAccount<'static> = SetupAccount {
28    partition: "aws",
29    account_id: "000000000000",
30    region: BUNDLE_REGION_TOKEN,
31};
32
33/// The id of the setup-owned network every AWS sandbox connector attaches to.
34/// The error is the refusal message, for the caller to wrap in its own error.
35pub fn aws_sandbox_egress_network_id<'a>(
36    stack: &'a Stack,
37    sandbox: &Sandbox,
38) -> std::result::Result<Option<&'a str>, String> {
39    if !sandbox_needs_connector(stack, sandbox) {
40        return Ok(None);
41    }
42    let network = match sandbox_egress_network(stack) {
43        Ok(network) => network,
44        Err(refusal) => return Err(refusal.to_string()),
45    };
46    if network.entry.lifecycle != ResourceLifecycle::Frozen {
47        return Err(
48            "an AWS sandbox routes session traffic through a VPC egress connector; its network \
49             must be created by setup, and this one is created at runtime"
50                .to_string(),
51        );
52    }
53    Ok(Some(network.id))
54}
55
56/// The build role setup renders for this sandbox from its bundle.
57pub fn aws_sandbox_build_role<'a>(
58    sandbox: &'a Sandbox,
59    bundle_uri: &'a str,
60    lifecycle: ResourceLifecycle,
61    account: SetupAccount<'a>,
62) -> SandboxBuildRole<'a> {
63    SandboxBuildRole::builder()
64        .sandbox_id(&sandbox.id)
65        .partition(account.partition)
66        .account_id(account.account_id)
67        .region(account.region)
68        .bundle_uri(bundle_uri)
69        .runtime_built(lifecycle == ResourceLifecycle::Live)
70        .maybe_private_base_image(sandbox.private_base_image.as_deref())
71        .build()
72}
73
74/// The Remote Bindings grant setup renders for this sandbox, `None` when it publishes none.
75pub fn aws_sandbox_remote_grant(
76    stack: &Stack,
77    sandbox: &Sandbox,
78) -> Option<&'static RemoteBindingDefinition> {
79    stack
80        .resources
81        .get(&sandbox.id)
82        .filter(|entry| remote_binding_is_deliverable(entry))
83        .and_then(remote_binding_for_entry)
84}
85
86/// Stands in for a Live sandbox's bundle store in its setup inputs; see [`aws_sandbox_setup_inputs`].
87const SETUP_GRANTED_STORE: &str = "setup-granted-store";
88/// Stands in for a Live sandbox's private base image repository in its setup inputs.
89const SETUP_GRANTED_BASE_IMAGE: &str =
90    "000000000000.dkr.ecr.us-east-1.amazonaws.com/setup-granted-repository:base";
91
92/// `image` as [`SETUP_GRANTED_BASE_IMAGE`], keeping its repository's namespace (the path before
93/// the last `/`). A publisher keeps installed setups building by writing their bundles `FROM` a
94/// repository they granted, which covers a renamed repository in the same namespace. A move to
95/// another namespace is not covered, so the namespace stays a setup input.
96fn setup_granted_base_image(image: &str) -> std::result::Result<String, String> {
97    let repository = parse_ecr_image_repository(image)?;
98    Ok(match repository.repository.rsplit_once('/') {
99        Some((namespace, _)) => SETUP_GRANTED_BASE_IMAGE.replacen(
100            "/setup-granted-repository",
101            &format!("/{namespace}/setup-granted-repository"),
102            1,
103        ),
104        None => SETUP_GRANTED_BASE_IMAGE.to_string(),
105    })
106}
107
108/// `image` with its bucket replaced by [`SETUP_GRANTED_STORE`], keeping the key.
109fn setup_granted_bundle(image: &str) -> std::result::Result<String, String> {
110    image
111        .strip_prefix("s3://")
112        .and_then(|path| path.split_once('/'))
113        .map(|(_, key)| format!("s3://{SETUP_GRANTED_STORE}/{key}"))
114        .ok_or_else(|| format!("bundle '{image}' is not an s3://bucket/key URI"))
115}
116
117/// Each setup input with the name a refused update reports it by. A new bundle under the same
118/// stable prefix, or a new tag in the same private repository, leaves them unchanged. For a Live
119/// sandbox the bundle's store and the base image's repository name are not inputs at all: they
120/// are fixed by the setup that granted them. The repository's namespace is.
121pub fn aws_sandbox_setup_inputs(
122    stack: &Stack,
123    sandbox: &Sandbox,
124    lifecycle: ResourceLifecycle,
125    account: SetupAccount<'_>,
126) -> Result<Vec<(&'static str, Value)>> {
127    let refuse = |reason: String| {
128        AlienError::new(ErrorData::OperationNotSupported {
129            operation: format!("setup inputs for sandbox '{}'", sandbox.id),
130            reason,
131        })
132    };
133    let SandboxCode::Image { image } = &sandbox.code else {
134        return Err(refuse(
135            "an AWS sandbox is built from a prebuilt s3:// bundle, not from source".to_string(),
136        ));
137    };
138    let policy = if lifecycle == ResourceLifecycle::Live {
139        // A Live sandbox's store and base image repository are fixed by its setup: the runtime
140        // reads each release's bundle key from the store this setup granted, and the publisher
141        // puts a bundle there whose base image this role can pull. Only the shape of the grant
142        // (stable prefix, whether a private base exists, its repository namespace) is a setup
143        // input.
144        let mut granted = sandbox.clone();
145        granted.private_base_image = sandbox
146            .private_base_image
147            .as_deref()
148            .map(setup_granted_base_image)
149            .transpose()
150            .map_err(refuse)?;
151        let bundle = setup_granted_bundle(image).map_err(refuse)?;
152        aws_sandbox_build_role(&granted, &bundle, lifecycle, account).policy()?
153    } else {
154        aws_sandbox_build_role(sandbox, image, lifecycle, account).policy()?
155    };
156    let network = aws_sandbox_egress_network_id(stack, sandbox).map_err(refuse)?;
157    // An update that stops publishing keeps the setup-owned Remote Bindings role, so without
158    // this the grant would outlive the declaration.
159    let grant =
160        aws_sandbox_remote_grant(stack, sandbox).map(|definition| definition.permission_set);
161    Ok(vec![
162        ("egress", sandbox.setup_digest_value()),
163        ("egress network", serde_json::json!(network)),
164        (
165            "build role policy",
166            serde_json::to_value(policy).expect("a build role policy serializes to JSON"),
167        ),
168        ("remote grant", serde_json::json!(grant)),
169    ])
170}
171
172/// [`aws_sandbox_setup_inputs`] for comparing stacks, which cannot fail: a sandbox whose inputs do
173/// not resolve counts as its whole configuration, so any change to it needs setup.
174pub fn comparable_aws_sandbox_setup_inputs(
175    stack: &Stack,
176    sandbox: &Sandbox,
177    lifecycle: ResourceLifecycle,
178) -> Vec<(&'static str, Value)> {
179    aws_sandbox_setup_inputs(stack, sandbox, lifecycle, SETUP_INPUTS_COMPARISON_ACCOUNT)
180        .unwrap_or_else(|_| {
181            vec![("configuration", {
182                let mut value =
183                    serde_json::to_value(sandbox).expect("a sandbox serializes to JSON");
184                value["egress"] = sandbox.setup_digest_value();
185                value
186                    .as_object_mut()
187                    .expect("sandbox config is an object")
188                    .remove("defaultPolicy");
189                value
190            })]
191        })
192}