summaryrefslogtreecommitdiffhomepage
path: root/mullvad-daemon/src/migrations/v11.rs
blob: 905361bad600d73c61b39e5623ef908a9939e234 (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
use super::{Error, Result};
use mullvad_types::settings::SettingsVersion;

/// The migration handles:
/// - Renaming of block_when_disconnected option to lockdown_mode.
/// - API access method names must now be unique and duplicates will be renamed.
pub fn migrate(settings: &mut serde_json::Value) -> Result<()> {
    if !(version(settings) == Some(SettingsVersion::V11)) {
        return Ok(());
    }

    log::info!("Migrating settings format to v12");

    migrate_block_when_disconnected(settings)?;
    migrate_duplicated_api_access_method_names(settings)?;

    settings["settings_version"] = serde_json::json!(SettingsVersion::V12);

    Ok(())
}

fn version(settings: &serde_json::Value) -> Option<SettingsVersion> {
    settings
        .get("settings_version")
        .and_then(|version| serde_json::from_value(version.clone()).ok())
}

fn migrate_block_when_disconnected(settings: &mut serde_json::Value) -> Result<()> {
    let key_name_before = "block_when_disconnected";
    let key_name_after = "lockdown_mode";

    let settings_map = settings
        .as_object_mut()
        .ok_or(Error::InvalidSettingsContent)?;

    // Get the old key's value and insert the new key with that value
    let value = settings_map
        .get(key_name_before)
        .ok_or(Error::InvalidSettingsContent)?;
    settings_map.insert(key_name_after.to_string(), value.clone());

    // Remove the old key
    settings_map.remove(key_name_before);

    Ok(())
}

fn generate_access_method_name_initial_suffix(
    access_method_names: &[impl AsRef<str>],
    access_method_name: &String,
) -> usize {
    let access_method_name_count = access_method_names
        .iter()
        .filter(|name| name.as_ref() == access_method_name)
        .count();

    let mut suffix = 1;
    if access_method_name_count > 1 {
        suffix = access_method_name_count - 1
    }

    suffix
}

/// Only consider renaming access methods with a duplicate name if it has a higher index
/// thab other access methods. This is to ensure that older entries' names are preserved,
/// in favor of renaming newer access methods.
fn get_should_rename_api_access_method(
    access_method_names: &[impl AsRef<str>],
    access_method_name: &String,
    access_method_name_index: usize,
) -> bool {
    access_method_names.iter().enumerate().any(|(index, name)| {
        access_method_name_index > index && name.as_ref() == *access_method_name
    })
}

fn generate_access_method_name(
    access_method_names: &[impl AsRef<str>],
    access_method_name: &String,
    access_method_name_index: usize,
    access_method_name_suffix: usize,
) -> String {
    // Generate a new name for the access method
    let generated_access_method_name = format!("{access_method_name}_{access_method_name_suffix}");

    // Verify if the generated name is unique or if a new name should be generated
    let should_rename_api_access_method = get_should_rename_api_access_method(
        access_method_names,
        &generated_access_method_name,
        access_method_name_index,
    );
    if should_rename_api_access_method {
        // Increment the suffix for the next attempt to generate a new access method name
        generate_access_method_name(
            access_method_names,
            access_method_name,
            access_method_name_index,
            access_method_name_suffix + 1,
        )
    } else {
        generated_access_method_name
    }
}

fn migrate_duplicated_api_access_method_names(settings: &mut serde_json::Value) -> Result<()> {
    let settings_map = settings
        .as_object_mut()
        .ok_or(Error::InvalidSettingsContent)?;

    let mut custom_api_access_methods: Vec<&mut String> = settings_map
        .get_mut("api_access_methods")
        .and_then(serde_json::Value::as_object_mut)
        .and_then(|api_access_method| api_access_method.get_mut("custom")?.as_array_mut())
        .into_iter()
        .flat_map(|array| array.iter_mut())
        // Take a &mut to each custom api access method name as a String
        .filter_map(|custom_api_access_method| custom_api_access_method.as_object_mut()?.get_mut("name"))
        .filter_map(|custom_api_access_method| match custom_api_access_method {
            serde_json::Value::String(custom_api_access_method_name) => {
                Some(custom_api_access_method_name)
            }
            _ => None,
        })
        .collect();

    for index in 0..custom_api_access_methods.len() {
        let access_method_name = &*custom_api_access_methods[index];

        let should_rename_api_access_method = get_should_rename_api_access_method(
            &custom_api_access_methods,
            access_method_name,
            index,
        );
        if should_rename_api_access_method {
            let access_method_name_suffix = generate_access_method_name_initial_suffix(
                &custom_api_access_methods,
                access_method_name,
            );

            let generated_access_method_name = generate_access_method_name(
                &custom_api_access_methods,
                access_method_name,
                index,
                access_method_name_suffix,
            );

            // Update the access method's name to the new unique name that was generated
            *custom_api_access_methods[index] = generated_access_method_name;
        }
    }

    Ok(())
}

#[cfg(test)]
mod test {
    use serde_json::json;

    use crate::migrations::v11::migrate_block_when_disconnected;
    use crate::migrations::v11::migrate_duplicated_api_access_method_names;

    /// "block_when_disconnected" is renamed to "lockdown_mode"
    #[test]
    fn test_v11_to_v12_migration_block_when_disconnected_disabled() {
        let mut old_settings = json!({
            "block_when_disconnected": false,
        });
        migrate_block_when_disconnected(&mut old_settings).unwrap();
        let new_settings: serde_json::Value = json!({
            "lockdown_mode": false,
        });
        assert_eq!(&old_settings, &new_settings);
    }

    #[test]
    fn test_v11_to_v12_migration_block_when_disconnected_enabled() {
        let mut old_settings = json!({
            "block_when_disconnected": true,
        });
        migrate_block_when_disconnected(&mut old_settings).unwrap();
        let new_settings: serde_json::Value = json!({
            "lockdown_mode": true,
        });
        assert_eq!(&old_settings, &new_settings);
    }

    // custom access method's names are renamed if they are not unique
    #[test]
    fn test_v11_to_v12_migration_access_method_name_duplicates() {
        let mut old_settings = json!({
            "api_access_methods": {
              "custom": [
                  {
                  "id": "90d35296-3823-4805-8926-720fff53c752",
                  "name": "test_3",
                  "enabled": true,
                  "access_method": {
                    "custom": {
                      "shadowsocks": {
                        "endpoint": "127.0.0.1:80",
                        "password": "",
                        "cipher": "aes-128-cfb"
                      }
                    }
                  }
                },
                {
                  "id": "d879f6e9-c052-4452-8e53-088183d01c0a",
                  "name": "test_2",
                  "enabled": true,
                  "access_method": {
                    "custom": {
                      "shadowsocks": {
                        "endpoint": "127.0.0.1:443",
                        "password": "secret",
                        "cipher": "aes-256-cfb"
                      }
                    }
                  }
                },
                {
                  "id": "7b49cef8-5a9f-4bbc-9bee-00841edc98e9",
                  "name": "test",
                  "enabled": true,
                  "access_method": {
                    "custom": {
                      "shadowsocks": {
                        "endpoint": "127.0.0.1:443",
                        "password": "",
                        "cipher": "aes-256-gcm"
                      }
                    }
                  }
                },
                 {
                  "id": "0bafc4ed-cd4f-4368-b067-74527f42451b",
                  "name": "test_1",
                  "enabled": true,
                  "access_method": {
                    "custom": {
                      "shadowsocks": {
                        "endpoint": "127.0.0.1:80",
                        "password": "",
                        "cipher": "aes-128-gcm"
                      }
                    }
                  }
                },
                {
                  "id": "09d032bc-7e3a-4d85-a63f-528b6c4b890e",
                  "name": "test_2",
                  "enabled": false,
                  "access_method": {
                    "custom": {
                      "shadowsocks": {
                        "endpoint": "127.0.0.1:443",
                        "password": "",
                        "cipher": "aes-128-cfb"
                      }
                    }
                  }
                },
                {
                  "id": "4471b3f5-a87e-4355-aea8-72c4c4936479",
                  "name": "test_1",
                  "enabled": false,
                  "access_method": {
                    "custom": {
                      "shadowsocks": {
                        "endpoint": "127.0.0.1:80",
                        "password": "secret",
                        "cipher": "aes-256-gcm"
                      }
                    }
                  }
                },
                {
                  "id": "d284a9d5-307b-4959-94a6-89fef8187807",
                  "name": "test",
                  "enabled": false,
                  "access_method": {
                    "custom": {
                      "shadowsocks": {
                        "endpoint": "127.0.0.1:443",
                        "password": "",
                        "cipher": "aes-128-cfb"
                      }
                    }
                  }
                },
                                {
                  "id": "6f8db7c3-2258-46c0-8b7d-2016dd9e5739",
                  "name": "other_name",
                  "enabled": false,
                  "access_method": {
                    "custom": {
                      "shadowsocks": {
                        "endpoint": "127.0.0.1:9090",
                        "password": "",
                        "cipher": "aes-256-cfb"
                      }
                    }
                  }
                },
                {
                  "id": "ffdf9900-e843-4298-9478-a9dfbaa63b17",
                  "name": "test",
                  "enabled": true,
                  "access_method": {
                    "custom": {
                      "shadowsocks": {
                        "endpoint": "127.0.0.1:8080",
                        "password": "",
                        "cipher": "aes-128-gcm"
                      }
                    }
                  }
                }
              ]
            }
        });
        migrate_duplicated_api_access_method_names(&mut old_settings).unwrap();
        insta::assert_snapshot!(serde_json::to_string_pretty(&old_settings).unwrap());
    }
}