summaryrefslogtreecommitdiffstats
path: root/browser/app/nmhproxy/src/commands.rs
blob: b26180e8f86b71caff010fbb2e1f2c1a86e44080 (plain)
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use serde::{Deserialize, Serialize};
use std::io::{self, Read, Write};
use std::path::PathBuf;
use std::process::Command;
use url::Url;

#[cfg(target_os = "windows")]
const OS_NAME: &str = "windows";

#[cfg(target_os = "macos")]
const OS_NAME: &str = "macos";

#[derive(Serialize, Deserialize)]
#[serde(tag = "command", content = "data")]
// {
//     "command": "LaunchFirefox",
//     "data": {"url": "https://example.com"},
// }
pub enum FirefoxCommand {
    LaunchFirefox { url: String },
    LaunchFirefoxPrivate { url: String },
    GetVersion {},
    GetInstallId {},
}
#[derive(Serialize, Deserialize)]
// {
//     "message": "Successful launch",
//     "result_code": 1,
// }
pub struct Response {
    pub message: String,
    pub result_code: u32,
}

#[derive(Serialize, Deserialize)]
// {
//     "installation_id": "123ABC456",
// }
pub struct InstallationId {
    pub installation_id: String,
}

#[repr(u32)]
pub enum ResultCode {
    Success = 0,
    Error = 1,
}
impl From<ResultCode> for u32 {
    fn from(m: ResultCode) -> u32 {
        m as u32
    }
}

trait CommandRunner {
    fn new() -> Self
    where
        Self: Sized;
    fn arg(&mut self, arg: &str) -> &mut Self;
    fn args(&mut self, args: &[&str]) -> &mut Self;
    fn spawn(&mut self) -> std::io::Result<()>;
    fn to_string(&mut self) -> std::io::Result<String>;
}

impl CommandRunner for Command {
    fn new() -> Self {
        #[cfg(target_os = "macos")]
        {
            Command::new("open")
        }
        #[cfg(target_os = "windows")]
        {
            use mozbuild::config::MOZ_APP_NAME;
            use std::env;
            use std::path::Path;
            // Get the current executable's path, we know Firefox is in the
            // same folder is nmhproxy.exe so we can use that.
            let nmh_exe_path = env::current_exe().unwrap();
            let nmh_exe_folder = nmh_exe_path.parent().unwrap_or_else(|| Path::new(""));
            let moz_exe_path = nmh_exe_folder.join(format!("{}.exe", MOZ_APP_NAME));
            Command::new(moz_exe_path)
        }
    }
    fn arg(&mut self, arg: &str) -> &mut Self {
        self.arg(arg)
    }
    fn args(&mut self, args: &[&str]) -> &mut Self {
        self.args(args)
    }
    fn spawn(&mut self) -> std::io::Result<()> {
        self.spawn().map(|_| ())
    }
    fn to_string(&mut self) -> std::io::Result<String> {
        Ok("".to_string())
    }
}

struct MockCommand {
    command_line: String,
}

impl CommandRunner for MockCommand {
    fn new() -> Self {
        MockCommand {
            command_line: String::new(),
        }
    }
    fn arg(&mut self, arg: &str) -> &mut Self {
        self.command_line.push_str(arg);
        self.command_line.push(' ');
        self
    }
    fn args(&mut self, args: &[&str]) -> &mut Self {
        for arg in args {
            self.command_line.push_str(arg);
            self.command_line.push(' ');
        }
        self
    }
    fn spawn(&mut self) -> std::io::Result<()> {
        Ok(())
    }
    fn to_string(&mut self) -> std::io::Result<String> {
        Ok(self.command_line.clone())
    }
}

// The message length is a 32-bit integer in native byte order
pub fn read_message_length<R: Read>(mut reader: R) -> std::io::Result<u32> {
    let mut buffer = [0u8; 4];
    reader.read_exact(&mut buffer)?;
    let length: u32 = u32::from_ne_bytes(buffer);
    if (length > 0) && (length < 100 * 1024) {
        Ok(length)
    } else {
        Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "Invalid message length",
        ))
    }
}

pub fn read_message_string<R: Read>(mut reader: R, length: u32) -> io::Result<String> {
    let mut buffer = vec![0u8; length.try_into().unwrap()];
    reader.read_exact(&mut buffer)?;
    let message =
        String::from_utf8(buffer).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    Ok(message)
}

pub fn process_command(command: &FirefoxCommand) -> std::io::Result<bool> {
    match &command {
        FirefoxCommand::LaunchFirefox { url } => {
            launch_firefox::<Command>(url.to_owned(), false, OS_NAME)?;
            Ok(true)
        }
        FirefoxCommand::LaunchFirefoxPrivate { url } => {
            launch_firefox::<Command>(url.to_owned(), true, OS_NAME)?;
            Ok(true)
        }
        FirefoxCommand::GetVersion {} => generate_response("1", ResultCode::Success.into()),
        FirefoxCommand::GetInstallId {} => {
            // config_dir() evaluates to ~/Library/Application Support on macOS
            // and %RoamingAppData% on Windows.
            let mut json_path = match dirs::config_dir() {
                Some(path) => path,
                None => {
                    return generate_response(
                        "Config dir could not be found",
                        ResultCode::Error.into(),
                    )
                }
            };
            #[cfg(target_os = "windows")]
            json_path.push("Mozilla\\Firefox");
            #[cfg(target_os = "macos")]
            json_path.push("Firefox");

            json_path.push("install_id");
            json_path.set_extension("json");
            let mut install_id = String::new();
            get_install_id(&mut json_path, &mut install_id)
        }
    }
}

pub fn generate_response(message: &str, result_code: u32) -> std::io::Result<bool> {
    let response_struct = Response {
        message: message.to_string(),
        result_code,
    };
    let response_str = serde_json::to_string(&response_struct)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    let response_len_bytes: [u8; 4] = (response_str.len() as u32).to_ne_bytes();
    std::io::stdout().write_all(&response_len_bytes)?;
    std::io::stdout().write_all(response_str.as_bytes())?;
    std::io::stdout().flush()?;
    Ok(true)
}

fn validate_url(url: String) -> std::io::Result<String> {
    let parsed_url = Url::parse(url.as_str())
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    match parsed_url.scheme() {
        "http" | "https" | "file" => Ok(parsed_url.to_string()),
        _ => Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "Invalid URL scheme",
        )),
    }
}

fn launch_firefox<C: CommandRunner>(
    url: String,
    private: bool,
    os: &str,
) -> std::io::Result<String> {
    let validated_url: String = validate_url(url)?;
    let mut command = C::new();
    if os == "macos" {
        use mozbuild::config::MOZ_MACBUNDLE_ID;
        let mut args: [&str; 2] = ["--args", "-url"];
        if private {
            args[1] = "-private-window";
        }
        command
            .arg("-n")
            .arg("-b")
            .arg(MOZ_MACBUNDLE_ID)
            .args(&args)
            .arg(validated_url.as_str());
    } else if os == "windows" {
        let mut args: [&str; 2] = ["-osint", "-url"];
        if private {
            args[1] = "-private-window";
        }
        command.args(&args).arg(validated_url.as_str());
    }
    match command.spawn() {
        Ok(_) => generate_response(
            if private {
                "Successful private launch"
            } else {
                "Sucessful launch"
            },
            ResultCode::Success.into(),
        )?,
        Err(_) => generate_response(
            if private {
                "Failed private launch"
            } else {
                "Failed launch"
            },
            ResultCode::Error.into(),
        )?,
    };
    command.to_string()
}

fn get_install_id(json_path: &mut PathBuf, install_id: &mut String) -> std::io::Result<bool> {
    if !json_path.exists() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "Install ID file does not exist",
        ));
    }
    let json_size = std::fs::metadata(&json_path)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e))?
        .len();
    // Set a 1 KB limit for the file size.
    if json_size <= 0 || json_size > 1024 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "Install ID file has invalid size",
        ));
    }
    let mut file =
        std::fs::File::open(json_path).or_else(|_| -> std::io::Result<std::fs::File> {
            return Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "Failed to open file",
            ));
        })?;
    let mut contents = String::new();
    match file.read_to_string(&mut contents) {
        Ok(_) => match serde_json::from_str::<InstallationId>(&contents) {
            Ok(id) => {
                *install_id = id.installation_id.clone();
                generate_response(&id.installation_id, ResultCode::Success.into())
            }
            Err(_) => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "Failed to read installation ID",
                ))
            }
        },
        Err(_) => generate_response("Failed to read file", ResultCode::Error.into()),
    }?;
    Ok(true)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;
    use tempfile::NamedTempFile;
    #[test]
    fn test_validate_url() {
        let valid_test_cases = vec![
            "https://example.com/".to_string(),
            "http://example.com/".to_string(),
            "file:///path/to/file".to_string(),
            "https://test.example.com/".to_string(),
        ];

        for input in valid_test_cases {
            let result = validate_url(input.clone());
            assert!(result.is_ok(), "Expected Ok, got Err");
            // Safe to unwrap because we know the result is Ok
            let ok_value = result.unwrap();
            assert_eq!(ok_value, input);
        }

        assert!(matches!(
            validate_url("fakeprotocol://test.example.com/".to_string()).map_err(|e| e.kind()),
            Err(std::io::ErrorKind::InvalidInput)
        ));

        assert!(matches!(
            validate_url("invalidURL".to_string()).map_err(|e| e.kind()),
            Err(std::io::ErrorKind::InvalidData)
        ));
    }

    #[test]
    fn test_read_message_length_valid() {
        let input: [u8; 4] = 256u32.to_ne_bytes();
        let mut cursor = Cursor::new(input);
        let length = read_message_length(&mut cursor);
        assert!(length.is_ok(), "Expected Ok, got Err");
        assert_eq!(length.unwrap(), 256);
    }

    #[test]
    fn test_read_message_length_invalid_too_large() {
        let input: [u8; 4] = 1_000_000u32.to_ne_bytes();
        let mut cursor = Cursor::new(input);
        let result = read_message_length(&mut cursor);
        assert!(result.is_err());
        let error = result.err().unwrap();
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_read_message_length_invalid_zero() {
        let input: [u8; 4] = 0u32.to_ne_bytes();
        let mut cursor = Cursor::new(input);
        let result = read_message_length(&mut cursor);
        assert!(result.is_err());
        let error = result.err().unwrap();
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_read_message_string_valid() {
        let input_data = b"Valid UTF8 string!";
        let input_length = input_data.len() as u32;
        let message = read_message_string(&input_data[..], input_length);
        assert!(message.is_ok(), "Expected Ok, got Err");
        assert_eq!(message.unwrap(), "Valid UTF8 string!");
    }

    #[test]
    fn test_read_message_string_invalid() {
        let input_data: [u8; 3] = [0xff, 0xfe, 0xfd];
        let input_length = input_data.len() as u32;
        let result = read_message_string(&input_data[..], input_length);
        assert!(result.is_err());
        let error = result.err().unwrap();
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_launch_regular_command_macos() {
        let url = "https://example.com";
        let result = launch_firefox::<MockCommand>(url.to_string(), false, "macos");
        assert!(result.is_ok());
        let command_line = result.unwrap();
        let correct_url_format = format!("-url {}", url);
        assert!(command_line.contains(correct_url_format.as_str()));
    }

    #[test]
    fn test_launch_regular_command_windows() {
        let url = "https://example.com";
        let result = launch_firefox::<MockCommand>(url.to_string(), false, "windows");
        assert!(result.is_ok());
        let command_line = result.unwrap();
        let correct_url_format = format!("-osint -url {}", url);
        assert!(command_line.contains(correct_url_format.as_str()));
    }

    #[test]
    fn test_launch_private_command_macos() {
        let url = "https://example.com";
        let result = launch_firefox::<MockCommand>(url.to_string(), true, "macos");
        assert!(result.is_ok());
        let command_line = result.unwrap();
        let correct_url_format = format!("-private-window {}", url);
        assert!(command_line.contains(correct_url_format.as_str()));
    }

    #[test]
    fn test_launch_private_command_windows() {
        let url = "https://example.com";
        let result = launch_firefox::<MockCommand>(url.to_string(), true, "windows");
        assert!(result.is_ok());
        let command_line = result.unwrap();
        let correct_url_format = format!("-osint -private-window {}", url);
        assert!(command_line.contains(correct_url_format.as_str()));
    }

    #[test]
    fn test_get_install_id_valid() -> std::io::Result<()> {
        let mut tempfile = NamedTempFile::new().unwrap();
        let installation_id = InstallationId {
            installation_id: "123ABC456".to_string(),
        };
        let json_string = serde_json::to_string(&installation_id);
        let _ = tempfile.write_all(json_string?.as_bytes());
        let mut install_id = String::new();
        let result = get_install_id(&mut tempfile.path().to_path_buf(), &mut install_id);
        assert!(result.is_ok());
        assert_eq!(install_id, "123ABC456");
        Ok(())
    }

    #[test]
    fn test_get_install_id_incorrect_var() -> std::io::Result<()> {
        #[derive(Serialize, Deserialize)]
        pub struct IncorrectJSON {
            pub incorrect_var: String,
        }
        let mut tempfile = NamedTempFile::new().unwrap();
        let incorrect_json = IncorrectJSON {
            incorrect_var: "incorrect_val".to_string(),
        };
        let json_string = serde_json::to_string(&incorrect_json);
        let _ = tempfile.write_all(json_string?.as_bytes());
        let mut install_id = String::new();
        let result = get_install_id(&mut tempfile.path().to_path_buf(), &mut install_id);
        assert!(result.is_err());
        let error = result.err().unwrap();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        Ok(())
    }

    #[test]
    fn test_get_install_id_partially_correct_vars() -> std::io::Result<()> {
        #[derive(Serialize, Deserialize)]
        pub struct IncorrectJSON {
            pub installation_id: String,
            pub incorrect_var: String,
        }
        let mut tempfile = NamedTempFile::new().unwrap();
        let incorrect_json = IncorrectJSON {
            installation_id: "123ABC456".to_string(),
            incorrect_var: "incorrect_val".to_string(),
        };
        let json_string = serde_json::to_string(&incorrect_json);
        let _ = tempfile.write_all(json_string?.as_bytes());
        let mut install_id = String::new();
        let result = get_install_id(&mut tempfile.path().to_path_buf(), &mut install_id);
        // This still succeeds as the installation_id field is present
        assert!(result.is_ok());
        Ok(())
    }

    #[test]
    fn test_get_install_id_file_does_not_exist() -> std::io::Result<()> {
        let tempfile = NamedTempFile::new().unwrap();
        let mut path = tempfile.path().to_path_buf();
        tempfile.close()?;
        let mut install_id = String::new();
        let result = get_install_id(&mut path, &mut install_id);
        assert!(result.is_err());
        let error = result.err().unwrap();
        assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
        Ok(())
    }

    #[test]
    fn test_get_install_id_file_too_large() -> std::io::Result<()> {
        let mut tempfile = NamedTempFile::new().unwrap();
        let installation_id = InstallationId {
            // Create a ~10 KB file
            installation_id: String::from_utf8(vec![b'X'; 10000]).unwrap(),
        };
        let json_string = serde_json::to_string(&installation_id);
        let _ = tempfile.write_all(json_string?.as_bytes());
        let mut install_id = String::new();
        let result = get_install_id(&mut tempfile.path().to_path_buf(), &mut install_id);
        assert!(result.is_err());
        let error = result.err().unwrap();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        Ok(())
    }
}