spin_manifest/
compat.rs

1//! Compatibility for old manifest versions.
2
3mod allowed_http_hosts;
4
5use crate::{
6    error::Error,
7    schema::{v1, v2},
8};
9use allowed_http_hosts::{parse_allowed_http_hosts, AllowedHttpHosts};
10
11/// Converts a V1 app manifest to V2.
12pub fn v1_to_v2_app(manifest: v1::AppManifestV1) -> Result<v2::AppManifest, Error> {
13    let trigger_type = manifest.trigger.trigger_type.clone();
14    let trigger_global_configs = [(trigger_type.clone(), manifest.trigger.config)]
15        .into_iter()
16        .collect();
17
18    let application = v2::AppDetails {
19        name: manifest.name,
20        version: manifest.version,
21        description: manifest.description,
22        authors: manifest.authors,
23        targets: Default::default(),
24        trigger_global_configs,
25        tool: Default::default(),
26    };
27
28    let app_variables = manifest
29        .variables
30        .into_iter()
31        .map(|(key, var)| Ok((id_from_string(key)?, var)))
32        .collect::<Result<_, Error>>()?;
33
34    let mut triggers = v2::Map::<String, Vec<v2::Trigger>>::default();
35    let mut components = v2::Map::default();
36    for component in manifest.components {
37        let component_id = component_id_from_string(component.id)?;
38
39        let variables = component
40            .config
41            .into_iter()
42            .map(|(key, var)| Ok((id_from_string(key)?, var)))
43            .collect::<Result<_, Error>>()?;
44
45        let allowed_http = convert_allowed_http_to_allowed_hosts(
46            &component.allowed_http_hosts,
47            component.allowed_outbound_hosts.is_none(),
48        )
49        .map_err(Error::ValidationError)?;
50        let allowed_outbound_hosts = match component.allowed_outbound_hosts {
51            Some(mut hs) => {
52                hs.extend(allowed_http);
53                hs
54            }
55            None => allowed_http,
56        };
57        components.insert(
58            component_id.clone(),
59            #[allow(deprecated)]
60            v2::Component {
61                source: component.source,
62                description: component.description,
63                variables,
64                environment: component.environment,
65                files: component.files,
66                exclude_files: component.exclude_files,
67                key_value_stores: component.key_value_stores,
68                sqlite_databases: component.sqlite_databases,
69                ai_models: component.ai_models,
70                build: component.build,
71                tool: Default::default(),
72                allowed_outbound_hosts,
73                allowed_http_hosts: Vec::new(),
74                dependencies_inherit_configuration: false,
75                dependencies: Default::default(),
76            },
77        );
78        triggers
79            .entry(trigger_type.clone())
80            .or_default()
81            .push(v2::Trigger {
82                id: format!("trigger-{component_id}"),
83                component: Some(v2::ComponentSpec::Reference(component_id)),
84                components: Default::default(),
85                config: component.trigger,
86            });
87    }
88    Ok(v2::AppManifest {
89        spin_manifest_version: Default::default(),
90        application,
91        variables: app_variables,
92        triggers,
93        components,
94    })
95}
96
97/// Converts the old `allowed_http_hosts` field to the new `allowed_outbound_hosts` field.
98///
99/// If `allow_database_access` is `true`, the function will also allow access to all redis,
100/// mysql, and postgres databases as this was the default before `allowed_outbound_hosts` was introduced.
101pub fn convert_allowed_http_to_allowed_hosts(
102    allowed_http_hosts: &[impl AsRef<str>],
103    allow_database_access: bool,
104) -> anyhow::Result<Vec<String>> {
105    let http_hosts = parse_allowed_http_hosts(allowed_http_hosts)?;
106    let mut outbound_hosts = if allow_database_access {
107        vec![
108            "redis://*:*".into(),
109            "mysql://*:*".into(),
110            "postgres://*:*".into(),
111        ]
112    } else {
113        Vec::new()
114    };
115    match http_hosts {
116        AllowedHttpHosts::AllowAll => outbound_hosts.extend([
117            "http://*:*".into(),
118            "https://*:*".into(),
119            "http://self".into(),
120        ]),
121        AllowedHttpHosts::AllowSpecific(specific) => {
122            outbound_hosts.extend(specific.into_iter().flat_map(|s| {
123                if s.domain == "self" {
124                    vec!["http://self".into()]
125                } else {
126                    let port = s.port.map(|p| format!(":{p}")).unwrap_or_default();
127                    vec![
128                        format!("http://{}{}", s.domain, port),
129                        format!("https://{}{}", s.domain, port),
130                    ]
131                }
132            }))
133        }
134    };
135    Ok(outbound_hosts)
136}
137
138fn component_id_from_string(id: String) -> Result<v2::KebabId, Error> {
139    // If it's already valid, do nothing
140    if let Ok(id) = id.clone().try_into() {
141        return Ok(id);
142    }
143    // Fix two likely problems; under_scores and mixedCase
144    let id = id.replace('_', "-").to_lowercase();
145    id.clone()
146        .try_into()
147        .map_err(|err: String| Error::InvalidID { id, reason: err })
148}
149
150fn id_from_string<const DELIM: char, const LOWER: bool>(
151    id: String,
152) -> Result<spin_serde::id::Id<DELIM, LOWER>, Error> {
153    id.clone()
154        .try_into()
155        .map_err(|err: String| Error::InvalidID { id, reason: err })
156}