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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// SPDX-License-Identifier: Apache-2.0

//! Configuration for a WASI application in an Enarx Keep
//!
#![doc = include_str!("../README.md")]
#![doc = include_str!("../Enarx_toml.md")]
#![deny(missing_docs)]
#![deny(clippy::all)]
#![warn(rust_2018_idioms)]

use std::{collections::HashMap, ops::Deref};

use serde::ser::SerializeStruct;
use serde::{de::Error as _, Deserialize, Deserializer, Serialize, Serializer};
use url::Url;

/// Configuration file template
pub const CONFIG_TEMPLATE: &str = r#"## Configuration for a WASI application in an Enarx Keep

## Arguments
# args = [
#      "--argument1",
#      "--argument2=foo"
# ]

## Steward
# steward = "https://steward.example.com"

## Environment variables
# [env]
# VAR1 = "var1"
# VAR2 = "var2"

## Pre-opened file descriptors
[[files]]
kind = "stdin"

[[files]]
kind = "stdout"

[[files]]
kind = "stderr"

## A listen socket
# [[files]]
# name = "LISTEN"
# kind = "listen"
# prot = "tls" # or prot = "tcp"
# port = 12345

## An outgoing connected socket
# [[files]]
# name = "CONNECT"
# kind = "connect"
# prot = "tls" # or prot = "tcp"
# host = "127.0.0.1"
# port = 23456
"#;

const fn default_port() -> u16 {
    443
}

fn default_addr() -> String {
    "::".into()
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
/// Name assigned to a file descriptor
///
/// This is used to export the `FD_NAMES` environment variable,
/// which is a concatenation of all file descriptors names seperated by `:`.
///
/// See the [crate] documentation for examples.
pub struct FileName(String);

impl From<String> for FileName {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for FileName {
    fn from(value: &str) -> Self {
        Self(value.into())
    }
}

impl Deref for FileName {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'de> Deserialize<'de> for FileName {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let name = String::deserialize(deserializer)?;

        if name.contains(':') {
            return Err(D::Error::custom("invalid value for `name` contains ':'"));
        }

        Ok(Self(name))
    }
}

/// The configuration for an Enarx WASI application
///
/// This struct can be used with any serde deserializer.
///
/// # Examples
///
/// ```
/// extern crate toml;
/// use enarx_config::Config;
/// const CONFIG: &str = r#"
/// [[files]]
/// name = "LISTEN"
/// kind = "listen"
/// prot = "tls"
/// port = 12345
/// "#;
///
/// let config: Config = toml::from_str(CONFIG).unwrap();
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
pub struct Config {
    /// The environment variables to provide to the application
    #[serde(default)]
    pub env: HashMap<String, String>,

    /// The arguments to provide to the application
    #[serde(default)]
    pub args: Vec<String>,

    /// The array of pre-opened file descriptors
    #[serde(default)]
    pub files: Vec<File>,

    /// An optional Steward URL
    #[serde(default)]
    pub steward: Option<Url>,
}

// TOML requires the `Vec`s to be serialized last, so manually implement `Serialize`
impl Serialize for Config {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut s = serializer.serialize_struct("Config", 4)?;
        if !self.args.is_empty() {
            s.serialize_field("args", &self.args).unwrap();
        }
        if self.steward.is_some() {
            s.serialize_field("steward", &self.steward).unwrap();
        }
        if !self.env.is_empty() {
            s.serialize_field("env", &self.env).unwrap();
        }
        if !self.files.is_empty() {
            s.serialize_field("files", &self.files).unwrap();
        }
        s.end()
    }
}

impl Default for Config {
    fn default() -> Self {
        let files = vec![
            File::Stdin { name: None },
            File::Stdout { name: None },
            File::Stderr { name: None },
        ];

        Self {
            env: HashMap::new(),
            args: vec![],
            files,
            steward: None, // TODO: Default to a deployed Steward instance
        }
    }
}

/// Parameters for a pre-opened file descriptor
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum File {
    /// File descriptor of `/dev/null`
    #[serde(rename = "null")]
    Null {
        /// Name assigned to the file descriptor
        name: Option<FileName>,
    },

    /// File descriptor of stdin
    #[serde(rename = "stdin")]
    Stdin {
        /// Name assigned to the file descriptor
        name: Option<FileName>,
    },

    /// File descriptor of stdout
    #[serde(rename = "stdout")]
    Stdout {
        /// Name assigned to the file descriptor
        name: Option<FileName>,
    },

    /// File descriptor of stderr
    #[serde(rename = "stderr")]
    Stderr {
        /// Name assigned to the file descriptor
        name: Option<FileName>,
    },

    /// File descriptor of a TCP listen socket
    #[serde(rename = "listen")]
    Listen {
        /// Name assigned to the file descriptor
        name: FileName,

        /// Address to listen on
        #[serde(default = "default_addr")]
        addr: String,

        /// Port to listen on
        #[serde(default = "default_port")]
        port: u16,

        /// Protocol to use
        #[serde(default)]
        prot: Protocol,
    },

    /// File descriptor of a TCP stream socket
    #[serde(rename = "connect")]
    Connect {
        /// Name assigned to the file descriptor
        name: Option<FileName>,

        /// Host address to connect to
        host: String,

        /// Port to connect to
        #[serde(default = "default_port")]
        port: u16,

        /// Protocol to use
        #[serde(default)]
        prot: Protocol,
    },
}

impl File {
    /// Get the name for a file descriptor
    pub fn name(&self) -> &str {
        match self {
            Self::Null { name } => name.as_deref().unwrap_or("null"),
            Self::Stdin { name } => name.as_deref().unwrap_or("stdin"),
            Self::Stdout { name } => name.as_deref().unwrap_or("stdout"),
            Self::Stderr { name } => name.as_deref().unwrap_or("stderr"),
            Self::Listen { name, .. } => name,
            Self::Connect { name, host, .. } => name.as_deref().unwrap_or(host),
        }
    }
}

/// Protocol to use for a connection
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Protocol {
    /// Transparently wrap the TCP connection with the TLS protocol
    #[serde(rename = "tls")]
    Tls,

    /// Normal TCP connection
    #[serde(rename = "tcp")]
    Tcp,
}

impl Default for Protocol {
    fn default() -> Self {
        Self::Tls
    }
}

#[cfg(test)]
mod test {
    use super::*;

    const CONFIG: &str = r#"
        [[files]]
        kind = "stdin"

        [[files]]
        name = "X"
        kind = "listen"
        prot = "tcp"
        port = 9000

        [[files]]
        kind = "stdout"

        [[files]]
        kind = "null"

        [[files]]
        kind = "stderr"

        [[files]]
        kind = "connect"
        host = "example.com"
    "#;

    #[test]
    fn values() {
        let cfg: Config = toml::from_str(CONFIG).unwrap();

        assert_eq!(
            cfg.files,
            vec![
                File::Stdin { name: None },
                File::Listen {
                    name: "X".into(),
                    port: 9000,
                    prot: Protocol::Tcp,
                    addr: default_addr()
                },
                File::Stdout { name: None },
                File::Null { name: None },
                File::Stderr { name: None },
                File::Connect {
                    name: None,
                    port: default_port(),
                    prot: Protocol::Tls,
                    host: "example.com".into(),
                },
            ]
        );

        let _cfg_str = toml::to_string(&cfg).unwrap();
    }

    #[test]
    fn names() {
        let cfg: Config = toml::from_str(CONFIG).unwrap();

        assert_eq!(
            vec!["stdin", "X", "stdout", "null", "stderr", "example.com"],
            cfg.files.iter().map(|f| f.name()).collect::<Vec<_>>()
        );
    }

    #[test]
    fn invalid_name() {
        const CONFIG: &str = r#"
        [[files]]
        name = "test:"
        kind = "null"
        "#;

        let err = toml::from_str::<Config>(CONFIG).unwrap_err();
        assert_eq!(err.line_col(), Some((1, 8)));
        assert_eq!(
            err.to_string(),
            "invalid value for `name` contains ':' for key `files` at line 2 column 9"
        );
    }

    #[test]
    fn check_template() {
        let cfg_str = CONFIG_TEMPLATE
            .lines()
            .map(|l| l.trim_start_matches("# "))
            .collect::<Vec<_>>()
            .join("\n");

        let cfg: Config = toml::from_str(&cfg_str).unwrap();
        let cfg_str = toml::to_string(&cfg).unwrap();
        let cfg2: Config = toml::from_str(&cfg_str).unwrap();
        assert_eq!(cfg, cfg2);
    }
}