1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/*
 * Copyright 2020 Fluence Labs Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use marine_wasm_backend_traits::WasmBackend;
use marine_core::generic::HostImportDescriptor;

use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;

#[derive(Clone, Default, Debug)]
pub struct ConfigContext {
    pub base_path: Option<PathBuf>,
}

pub struct WithContext<'c, T> {
    pub context: &'c ConfigContext,
    pub data: T,
}

impl ConfigContext {
    pub fn wrapped<T>(&self, data: T) -> WithContext<'_, T> {
        WithContext {
            context: self,
            data,
        }
    }
}

/// Info to load a module from filesystem into runtime.
#[derive(Default)]
pub struct ModuleDescriptor<WB: WasmBackend> {
    pub load_from: Option<PathBuf>,
    pub file_name: String,
    pub import_name: String,
    pub config: MarineModuleConfig<WB>,
}

impl<WB: WasmBackend> ModuleDescriptor<WB> {
    pub fn get_path(&self, modules_dir: &Option<PathBuf>) -> Result<PathBuf, MarineError> {
        match &self.load_from {
            None => match modules_dir {
                Some(dir) => Ok(dir.join(Path::new(&self.file_name))),
                None => Err(MarineError::InvalidConfig(format!(
                    r#""modules_dir" field is not defined, but it is required to load module "{}""#,
                    self.import_name
                ))),
            },
            Some(path) => {
                if path.is_file() {
                    Ok(path.clone())
                } else {
                    Ok(path.join(Path::new(&self.file_name)))
                }
            }
        }
    }
}

/// Describes the behaviour of the Marine component.
#[derive(Default)]
pub struct MarineConfig<WB: WasmBackend> {
    /// Path to a dir where compiled Wasm modules are located.
    pub modules_dir: Option<PathBuf>,

    /// Settings for a module with particular name (not HashMap because the order is matter).
    pub modules_config: Vec<ModuleDescriptor<WB>>,

    /// Settings for a module that name's not been found in modules_config.
    pub default_modules_config: Option<MarineModuleConfig<WB>>,
}

/// Various settings that could be used to guide Marine how to load a module in a proper way.
#[derive(Default)]
pub struct MarineModuleConfig<WB: WasmBackend> {
    /// Maximum memory size accessible by a module in Wasm pages (64 Kb).
    pub mem_pages_count: Option<u32>,

    /// Maximum memory size for heap of Wasm module in bytes, if it set, mem_pages_count ignored.
    pub max_heap_size: Option<u64>,

    /// Defines whether Marine should provide a special host log_utf8_string function for this module.
    pub logger_enabled: bool,

    /// Export from host functions that will be accessible on the Wasm side by provided name.
    pub host_imports: HashMap<String, HostImportDescriptor<WB>>,

    /// A WASI config.
    pub wasi: Option<MarineWASIConfig>,

    /// Mask used to filter logs, for details see `log_utf8_string`
    pub logging_mask: i32,
}

impl<WB: WasmBackend> MarineModuleConfig<WB> {
    pub fn extend_wasi_envs(&mut self, new_envs: HashMap<String, String>) {
        match &mut self.wasi {
            Some(MarineWASIConfig { envs, .. }) => envs.extend(new_envs),
            w @ None => {
                *w = Some(MarineWASIConfig {
                    envs: new_envs,
                    preopened_files: HashSet::new(),
                    mapped_dirs: HashMap::new(),
                })
            }
        };
    }

    pub fn extend_wasi_files(
        &mut self,
        new_preopened_files: HashSet<PathBuf>,
        new_mapped_dirs: HashMap<String, PathBuf>,
    ) {
        match &mut self.wasi {
            Some(MarineWASIConfig {
                preopened_files,
                mapped_dirs,
                ..
            }) => {
                preopened_files.extend(new_preopened_files);
                mapped_dirs.extend(new_mapped_dirs);
            }
            w @ None => {
                *w = Some(MarineWASIConfig {
                    envs: HashMap::new(),
                    preopened_files: new_preopened_files,
                    mapped_dirs: new_mapped_dirs,
                })
            }
        };
    }

    pub fn root_wasi_files_at(&mut self, root: &Path) {
        // TODO: make all the security rules for paths configurable from outside
        match &mut self.wasi {
            Some(MarineWASIConfig {
                preopened_files,
                mapped_dirs,
                ..
            }) => {
                mapped_dirs.values_mut().for_each(|path| {
                    *path = root.join(&path);
                });

                let mapped_preopens = preopened_files.iter().map(|path| {
                    let new_path = root.join(path);
                    (path.to_string_lossy().into(), new_path)
                });

                mapped_dirs.extend(mapped_preopens);

                preopened_files.clear();
            }
            None => {}
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct MarineWASIConfig {
    /// A list of environment variables available for this module.
    pub envs: HashMap<String, String>,

    /// A list of files available for this module.
    /// A loaded module could have access only to files from this list.
    pub preopened_files: HashSet<PathBuf>,

    /// Mapping from a usually short to full file name.
    pub mapped_dirs: HashMap<String, PathBuf>,
}

use super::TomlMarineConfig;
use super::TomlMarineModuleConfig;
use super::TomlWASIConfig;
use super::TomlMarineNamedModuleConfig;
use crate::MarineError;
use crate::MarineResult;
use crate::config::as_relative_to_base;

use itertools::Itertools;

use std::convert::TryFrom;
use std::convert::TryInto;

impl<WB: WasmBackend> TryFrom<TomlMarineConfig> for MarineConfig<WB> {
    type Error = MarineError;

    fn try_from(toml_config: TomlMarineConfig) -> Result<Self, Self::Error> {
        let base_path = toml_config.base_path;
        let context = ConfigContext {
            base_path: Some(base_path),
        };

        let modules_dir = toml_config
            .modules_dir
            .map(|dir| as_relative_to_base(context.base_path.as_deref(), &dir))
            .transpose()?;

        let default_modules_config = toml_config
            .default
            .map(|m| context.wrapped(m).try_into())
            .transpose()?;

        let modules_config = toml_config
            .module
            .into_iter()
            .map(|toml_module| ModuleDescriptor::try_from(context.wrapped(toml_module)))
            .collect::<MarineResult<Vec<_>>>()?;

        Ok(MarineConfig {
            modules_dir,
            modules_config,
            default_modules_config,
        })
    }
}

impl<'c, WB: WasmBackend> TryFrom<WithContext<'c, TomlMarineNamedModuleConfig>>
    for ModuleDescriptor<WB>
{
    type Error = MarineError;

    fn try_from(config: WithContext<'c, TomlMarineNamedModuleConfig>) -> Result<Self, Self::Error> {
        let WithContext {
            context,
            data: config,
        } = config;

        let file_name = config.file_name.unwrap_or(format!("{}.wasm", config.name));
        let load_from = config
            .load_from
            .map(|path| as_relative_to_base(context.base_path.as_deref(), &path))
            .transpose()?;

        Ok(ModuleDescriptor {
            load_from,
            file_name,
            import_name: config.name,
            config: context.wrapped(config.config).try_into()?,
        })
    }
}

impl<'c, WB: WasmBackend> TryFrom<WithContext<'c, TomlMarineModuleConfig>>
    for MarineModuleConfig<WB>
{
    type Error = MarineError;

    fn try_from(toml_config: WithContext<'c, TomlMarineModuleConfig>) -> Result<Self, Self::Error> {
        let WithContext {
            context,
            data: toml_config,
        } = toml_config;

        let mounted_binaries = toml_config.mounted_binaries.unwrap_or_default();
        let mounted_binaries = mounted_binaries
            .into_iter()
            .map(|(import_func_name, host_cmd)| {
                let host_cmd = host_cmd.try_into::<PathBuf>()?;
                Ok((import_func_name, host_cmd))
            })
            .collect::<Result<Vec<_>, Self::Error>>()?;

        let max_heap_size = toml_config.max_heap_size.map(|v| v.as_u64());
        let mut host_cli_imports = HashMap::new();
        for (import_name, host_cmd) in mounted_binaries {
            let host_cmd = as_relative_to_base(context.base_path.as_deref(), &host_cmd)?;
            host_cli_imports.insert(
                import_name,
                crate::host_imports::create_mounted_binary_import(host_cmd),
            );
        }

        let wasi = toml_config.wasi.map(|w| w.try_into()).transpose()?;

        Ok(MarineModuleConfig {
            mem_pages_count: toml_config.mem_pages_count,
            max_heap_size,
            logger_enabled: toml_config.logger_enabled.unwrap_or(true),
            host_imports: host_cli_imports,
            wasi,
            logging_mask: toml_config.logging_mask.unwrap_or(i32::max_value()),
        })
    }
}

impl TryFrom<TomlWASIConfig> for MarineWASIConfig {
    type Error = MarineError;

    fn try_from(toml_config: TomlWASIConfig) -> Result<Self, Self::Error> {
        let to_string = |elem: (String, toml::Value)| -> Result<(String, String), Self::Error> {
            let to = elem
                .1
                .try_into::<String>()
                .map_err(MarineError::ParseConfigError)?;
            Ok((elem.0, to))
        };

        // Makes sure that no user-defined paths can be safely placed in an isolated directory
        // TODO: make all the security rules for paths configurable from outside
        let check_path = |path: PathBuf| -> Result<PathBuf, Self::Error> {
            if path.is_absolute() {
                return Err(MarineError::InvalidConfig(format!(
                    "Absolute paths are not supported in WASI section: {}",
                    path.display()
                )));
            }

            if path.components().contains(&Component::ParentDir) {
                return Err(MarineError::InvalidConfig(format!(
                    "Paths containing \"..\" are not supported in WASI section: {}",
                    path.display()
                )));
            }

            Ok(path)
        };

        let to_path = |elem: (String, toml::Value)| -> Result<(String, PathBuf), Self::Error> {
            let to = elem
                .1
                .try_into::<PathBuf>()
                .map_err(MarineError::ParseConfigError)?;

            let to = check_path(to)?;
            Ok((elem.0, to))
        };

        let envs = toml_config.envs.unwrap_or_default();
        let envs = envs
            .into_iter()
            .map(to_string)
            .collect::<Result<HashMap<_, _>, _>>()?;

        let preopened_files = toml_config.preopened_files.unwrap_or_default();
        let preopened_files = preopened_files
            .into_iter()
            .map(check_path)
            .collect::<Result<HashSet<_>, _>>()?;

        let mapped_dirs = toml_config.mapped_dirs.unwrap_or_default();
        let mapped_dirs = mapped_dirs
            .into_iter()
            .map(to_path)
            .collect::<Result<HashMap<_, _>, _>>()?;

        Ok(MarineWASIConfig {
            envs,
            preopened_files,
            mapped_dirs,
        })
    }
}