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
/// Errors that can occur during module validation.
#[derive(Clone, Debug)]
pub enum ModuleValidationError {
    WebProxyMissingSyscalls { syscalls: Vec<String> },
    WcgiMissingSyscalls { syscalls: Vec<String> },
}

impl ModuleValidationError {
    pub fn explain(&self) -> String {
        match self {
            Self::WebProxyMissingSyscalls { syscalls } => {
                format!(
                    "web_proxy modules must read and write to sockets, \
                    but the module does not import the WASI functions required \
                    to do so. \\n
                    Missing functions: {}",
                    syscalls.join(", ")
                )
            }
            Self::WcgiMissingSyscalls { syscalls } => {
                format!(
                    "wcgi modules must read from stdin and write to stdout, \
                    but the module does not import the WASI functions required \
                    to do so. \n\
                    Missing functions: {}",
                    syscalls.join(", ")
                )
            }
        }
    }
}

impl std::fmt::Display for ModuleValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::WebProxyMissingSyscalls { syscalls } => {
                write!(
                    f,
                    "Module does not import required syscalls: {}",
                    syscalls.join(", ")
                )
            }
            Self::WcgiMissingSyscalls { syscalls } => {
                write!(
                    f,
                    "Module does not import required syscalls: {}",
                    syscalls.join(", ")
                )
            }
        }
    }
}

impl std::error::Error for ModuleValidationError {}

#[derive(Clone, Debug)]
pub enum CapabilityValidationError {
    NetworkCapabilityMissing,
}

impl CapabilityValidationError {
    pub fn explain(&self) -> String {
        match self {
            Self::NetworkCapabilityMissing => {
                "vpn_proxy requires that the deployment configuration has
                    a network capability."
                    .to_string()
            }
        }
    }
}

impl std::fmt::Display for CapabilityValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NetworkCapabilityMissing => {
                write!(f, "Configuration does not have a network capability",)
            }
        }
    }
}

impl std::error::Error for CapabilityValidationError {}

/// Validate a WASM module for usage as a webproxy.
///
/// This only checks for the presence of some mandatory syscalls.
#[allow(clippy::manual_flatten)]
pub fn validate_parse_module_webproxy(bytes: &[u8]) -> Result<(), ModuleValidationError> {
    let mut sock_listen = false;
    let mut sock_accept = false;
    let mut sock_recv = false;
    let mut sock_send = false;

    for payload in wasmparser::Parser::new(0).parse_all(bytes) {
        // NOTE: validation deliberately ignores parse errors to be more compatible.
        if let Ok(wasmparser::Payload::ImportSection(imports)) = payload {
            for import in imports {
                if let Ok(import) = import {
                    if !matches!(import.ty, wasmparser::TypeRef::Func(_)) {
                        continue;
                    }

                    // Checking is deliberately permissive, just check that the
                    // absolutely necessary syscalls are used.
                    if import.name.contains("sock_listen") {
                        sock_listen = true;
                    } else if import.name.contains("sock_accept") {
                        sock_accept = true;
                    } else if import.name.contains("sock_recv") {
                        sock_recv = true;
                    } else if import.name.contains("sock_send") {
                        sock_send = true;
                    }
                }
            }
        }
    }

    let mut missing = Vec::new();
    if !sock_listen {
        // NOTE: not checking this, because WASI (non-wasix) would also work
        // without listen, if there was a pre-defined socket.
        // missing.push("sock_listen".to_string());
    }
    if !sock_accept {
        missing.push("sock_accept".to_string());
    }
    if !sock_recv {
        missing.push("sock_recv".to_string());
    }
    if !sock_send {
        missing.push("sock_send".to_string());
    }

    if missing.is_empty() {
        Ok(())
    } else {
        Err(ModuleValidationError::WebProxyMissingSyscalls { syscalls: missing })
    }
}

/// Validate a WASM module for usage with wcgi .
///
/// This only checks for the presence of some mandatory syscalls.
#[allow(clippy::manual_flatten)]
pub fn validate_parse_module_wcgi(bytes: &[u8]) -> Result<(), ModuleValidationError> {
    let mut fd_read = false;
    let mut fd_write = false;
    let mut fd_pipe = false;

    for payload in wasmparser::Parser::new(0).parse_all(bytes) {
        // NOTE: validation deliberately ignores parse errors to be more compatible.
        if let Ok(wasmparser::Payload::ImportSection(imports)) = payload {
            for import in imports {
                if let Ok(import) = import {
                    if !matches!(import.ty, wasmparser::TypeRef::Func(_)) {
                        continue;
                    }

                    // Checking is deliberately permissive, just check that the
                    // absolutely necessary syscalls are used.
                    if import.name.contains("fd_read") {
                        fd_read = true;
                    } else if import.name.contains("fd_write") {
                        fd_write = true;
                    } else if import.name.contains("fd_pipe") {
                        fd_pipe = true;
                    }
                }
            }
        }
    }

    let mut missing = Vec::new();
    if !fd_read {
        missing.push("fd_read".to_string());
    }
    if !(fd_write || fd_pipe) {
        missing.push("fd_write|fd_pipe".to_string());
    }

    if missing.is_empty() {
        Ok(())
    } else {
        Err(ModuleValidationError::WcgiMissingSyscalls { syscalls: missing })
    }
}

#[derive(Clone, Debug)]
pub enum DeploymentValidationError {
    Module(ModuleValidationError),
    MissingCapability(CapabilityValidationError),
    UnsupportedRunner(String),
}

impl std::fmt::Display for DeploymentValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Module(e) => e.fmt(f),
            Self::MissingCapability(e) => e.fmt(f),
            Self::UnsupportedRunner(e) => write!(f, "Unsupported runner: {}", e),
        }
    }
}

// /// Validate a module against the given deployment config.
// ///
// /// Will check that the module is compatible with the runner.
// pub fn validate_deployment_module(
//     depl: &DeploymentV1,
//     module_wasm: &[u8],
// ) -> Result<(), DeploymentValidationError> {
//     match &depl.workload.runner {
//         WorkloadRunnerV1::Wasm(_) => Err(DeploymentValidationError::UnsupportedRunner(
//             "wasm".to_string(),
//         )),
//         WorkloadRunnerV1::WebcCommand(_) => Err(DeploymentValidationError::UnsupportedRunner(
//             "webc_command".to_string(),
//         )),
//         WorkloadRunnerV1::TcpProxy(_) => Err(DeploymentValidationError::UnsupportedRunner(
//             "tcp_proxy".to_string(),
//         )),
//         WorkloadRunnerV1::WCgi(_) => {
//             validate_parse_module_wcgi(module_wasm).map_err(DeploymentValidationError::Module)
//         }
//         WorkloadRunnerV1::WebProxy(_) => {
//             validate_parse_module_webproxy(module_wasm).map_err(DeploymentValidationError::Module)
//         }
//     }
// }

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    // use wasmer_deploy_schema::schema::{
    //     RunnerWCgiV1, WorkloadRunnerWasmSourceLocalPathV1, WorkloadRunnerWasmSourceV1,
    // };

    use super::*;

    fn root_path() -> PathBuf {
        std::env::var("CARGO_MANIFEST_DIR")
            .map(PathBuf::from)
            .unwrap()
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .to_owned()
    }

    fn tests_path() -> PathBuf {
        root_path().join("wasm-tests").join("compiled")
    }

    #[test]
    fn test_validate_wcgi_valid() {
        let path = tests_path().join("local").join("wcgi-hello.wasm");
        let contents = std::fs::read(path).unwrap();
        validate_parse_module_wcgi(&contents).unwrap();
    }

    #[test]
    fn test_validate_wcgi_invalid() {
        let path = tests_path().join("vendor").join("empty.wasm");
        let contents = std::fs::read(path).unwrap();

        let res = validate_parse_module_wcgi(&contents);
        assert!(matches!(
            res,
            Err(ModuleValidationError::WcgiMissingSyscalls { .. })
        ));
    }

    #[test]
    fn test_validate_webproxy_valid() {
        let path = tests_path().join("vendor").join("static-web-server.wasm");
        let contents = std::fs::read(path).unwrap();

        validate_parse_module_webproxy(&contents).unwrap();
    }

    #[test]
    fn test_validate_webproxy_invalid() {
        let path = tests_path().join("local").join("wcgi-hello.wasm");
        let contents = std::fs::read(path).unwrap();

        let res = validate_parse_module_webproxy(&contents);
        assert!(matches!(
            res,
            Err(ModuleValidationError::WebProxyMissingSyscalls { .. })
        ));
    }

    // #[test]
    // fn test_validate_deployment_wcgi() {
    //     // Valid

    //     let path = tests_path().join("local").join("wcgi-hello.wasm");
    //     let contents = std::fs::read(path).unwrap();

    //     let depl = DeploymentV1 {
    //         name: "name".to_string(),
    //         workload: wasmer_deploy_schema::schema::WorkloadV1 {
    //             name: None,
    //             capabilities: Default::default(),
    //             runner: WorkloadRunnerV1::WCgi(RunnerWCgiV1 {
    //                 source: WorkloadRunnerWasmSourceV1::LocalPath(
    //                     WorkloadRunnerWasmSourceLocalPathV1 {
    //                         path: ".".to_string(),
    //                     },
    //                 ),
    //                 dialect: None,
    //             }),
    //         },
    //     };

    //     validate_deployment_module(&depl, &contents).unwrap();

    //     // Invalid.

    //     let path = tests_path().join("vendor").join("empty.wasm");
    //     let contents = std::fs::read(path).unwrap();

    //     assert!(matches!(
    //         validate_deployment_module(&depl, &contents),
    //         Err(DeploymentValidationError::Module(
    //             ModuleValidationError::WcgiMissingSyscalls { .. }
    //         ))
    //     ));
    // }

    // #[test]
    // fn test_validate_deployment_web_proxy() {
    //     // Valid

    //     let path = tests_path().join("vendor").join("static-web-server.wasm");
    //     let contents = std::fs::read(path).unwrap();

    //     let depl = DeploymentV1 {
    //         name: "name".to_string(),
    //         workload: wasmer_deploy_schema::schema::WorkloadV1 {
    //             name: None,
    //             capabilities: Default::default(),
    //             runner: WorkloadRunnerV1::WebProxy(
    //                 wasmer_deploy_schema::schema::RunnerWebProxyV1 {
    //                     source: WorkloadRunnerWasmSourceV1::LocalPath(
    //                         WorkloadRunnerWasmSourceLocalPathV1 {
    //                             path: ".".to_string(),
    //                         },
    //                     ),
    //                 },
    //             ),
    //         },
    //     };

    //     validate_deployment_module(&depl, &contents).unwrap();

    //     // Invalid.

    //     let path = tests_path().join("local").join("wcgi-hello.wasm");
    //     let contents = std::fs::read(path).unwrap();

    //     assert!(matches!(
    //         validate_deployment_module(&depl, &contents),
    //         Err(DeploymentValidationError::Module(
    //             ModuleValidationError::WebProxyMissingSyscalls { .. }
    //         ))
    //     ));
    // }
}