ecr-store 0.2.2

Mail storage for ecr: notmuch queries, MIME parsing and sanitization, sync and send
Documentation
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
use crate::error::{Error, Result};
use crate::parse::{MbsyncConfig, MsmtpConfig, NotmuchConfig};
use crate::settings::ServerSettings;
use ecr_core::doctor::{ConfigKind, ConfigSource, ResolvedConfig};
use std::path::{Component, Path, PathBuf};

#[derive(Debug, Clone)]
pub struct Candidate {
    pub path: PathBuf,
    pub source: ConfigSource,
}

#[derive(Debug, Clone)]
pub struct Env {
    pub home: PathBuf,
    pub config_dir: PathBuf,
    pub state_dir: PathBuf,
    pub notmuch_config: Option<PathBuf>,
    pub notmuch_profile: Option<String>,
    pub mbsyncrc: Option<PathBuf>,
}

impl Env {
    pub fn from_process() -> Self {
        let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/"));
        Self {
            config_dir: dirs::config_dir().unwrap_or_else(|| home.join(".config")),
            state_dir: dirs::state_dir().unwrap_or_else(|| home.join(".local").join("state")),
            home,
            notmuch_config: std::env::var_os("NOTMUCH_CONFIG").map(PathBuf::from),
            notmuch_profile: std::env::var("NOTMUCH_PROFILE").ok(),
            mbsyncrc: std::env::var_os("MBSYNCRC").map(PathBuf::from),
        }
    }

    pub fn rooted_at(home: &Path) -> Self {
        Self {
            home: home.to_path_buf(),
            config_dir: home.join(".config"),
            state_dir: home.join(".local").join("state"),
            notmuch_config: None,
            notmuch_profile: None,
            mbsyncrc: None,
        }
    }

    fn candidates(&self, kind: ConfigKind, settings: &ServerSettings) -> Vec<Candidate> {
        let mut out = Vec::new();

        let explicit = match kind {
            ConfigKind::Notmuch => settings.notmuch_config.as_ref(),
            ConfigKind::Mbsync => settings.mbsync_config.as_ref(),
            ConfigKind::Msmtp => settings.msmtp_config.as_ref(),
        };
        if let Some(path) = explicit {
            out.push(Candidate {
                path: path.clone(),
                source: ConfigSource::ServerToml,
            });
        }

        match kind {
            ConfigKind::Notmuch => {
                if let Some(path) = &self.notmuch_config {
                    out.push(Candidate {
                        path: path.clone(),
                        source: ConfigSource::EnvVar("NOTMUCH_CONFIG".into()),
                    });
                }
                let profile = self.notmuch_profile.as_deref().unwrap_or("default");
                out.push(Candidate {
                    path: self.config_dir.join("notmuch").join(profile).join("config"),
                    source: ConfigSource::Xdg,
                });
                out.push(Candidate {
                    path: self.home.join(".notmuch-config"),
                    source: ConfigSource::LegacyDotfile,
                });
            }
            ConfigKind::Mbsync => {
                if let Some(path) = &self.mbsyncrc {
                    out.push(Candidate {
                        path: path.clone(),
                        source: ConfigSource::EnvVar("MBSYNCRC".into()),
                    });
                }
                out.push(Candidate {
                    path: self.config_dir.join("isyncrc"),
                    source: ConfigSource::Xdg,
                });
                out.push(Candidate {
                    path: self.config_dir.join("mbsync").join("mbsyncrc"),
                    source: ConfigSource::Xdg,
                });
                out.push(Candidate {
                    path: self.home.join(".mbsyncrc"),
                    source: ConfigSource::LegacyDotfile,
                });
            }
            ConfigKind::Msmtp => {
                out.push(Candidate {
                    path: self.config_dir.join("msmtp").join("config"),
                    source: ConfigSource::Xdg,
                });
                out.push(Candidate {
                    path: self.home.join(".msmtprc"),
                    source: ConfigSource::LegacyDotfile,
                });
            }
        }
        out
    }

    pub fn resolve(&self, kind: ConfigKind, settings: &ServerSettings) -> ResolvedConfig {
        let candidates = self.candidates(kind, settings);
        let mut chosen: Option<Candidate> = None;
        let mut shadowed = Vec::new();

        for candidate in candidates {
            if !candidate.path.is_file() {
                continue;
            }
            match chosen {
                None => chosen = Some(candidate),
                Some(_) => shadowed.push(candidate.path),
            }
        }

        match chosen {
            Some(c) => ResolvedConfig {
                kind,
                path: Some(c.path),
                source: c.source,
                shadowed,
            },
            None => ResolvedConfig::missing(kind),
        }
    }
}

#[derive(Debug, Clone)]
pub struct MailPaths {
    pub notmuch: ResolvedConfig,
    pub mbsync: ResolvedConfig,
    pub msmtp: ResolvedConfig,
    pub notmuch_config: NotmuchConfig,
    pub mbsync_config: MbsyncConfig,
    pub msmtp_config: MsmtpConfig,
    pub maildir_root: PathBuf,
    pub database_path: PathBuf,
    pub binaries: crate::settings::Binaries,
    /// Where ecr keeps its own files, as opposed to the mail tools' files.
    pub ecr_config_dir: PathBuf,
    /// The same split XDG draws: state is what ecr rewrites as it runs — the
    /// OAuth tokens and the mail index — as opposed to what the user edits.
    pub ecr_state_dir: PathBuf,
    /// Whether reads may be answered from the mail index. It is a cache of what
    /// notmuch holds, so turning it off costs speed and nothing else; the
    /// switch exists so a suspected disagreement can be settled without
    /// rebuilding or reinstalling anything.
    pub use_index: bool,
}

impl MailPaths {
    pub fn discover() -> Result<Self> {
        Self::with(&Env::from_process(), &ServerSettings::load())
    }

    pub fn with(env: &Env, settings: &ServerSettings) -> Result<Self> {
        let notmuch = env.resolve(ConfigKind::Notmuch, settings);
        let mbsync = env.resolve(ConfigKind::Mbsync, settings);
        let msmtp = env.resolve(ConfigKind::Msmtp, settings);

        let notmuch_path = notmuch.path.clone().ok_or_else(|| Error::ConfigNotFound {
            kind: "notmuch",
            searched: env
                .candidates(ConfigKind::Notmuch, settings)
                .into_iter()
                .map(|c| c.path)
                .collect(),
        })?;

        let notmuch_config = NotmuchConfig::parse(&std::fs::read_to_string(&notmuch_path)?);
        let mbsync_config = read_optional(&mbsync)
            .map(|t| MbsyncConfig::parse(&t))
            .unwrap_or_default();
        let msmtp_config = read_optional(&msmtp)
            .map(|t| MsmtpConfig::parse(&t))
            .unwrap_or_default();

        let database_path =
            notmuch_config
                .database_path
                .clone()
                .ok_or_else(|| Error::NoDatabasePath {
                    path: notmuch_path.clone(),
                })?;

        let maildir_root = settings
            .maildir_root
            .clone()
            .or_else(|| notmuch_config.effective_mail_root().cloned())
            .unwrap_or_else(|| database_path.clone());

        Ok(Self {
            notmuch,
            mbsync,
            msmtp,
            notmuch_config,
            mbsync_config,
            msmtp_config,
            maildir_root,
            database_path,
            binaries: crate::settings::Binaries::from_settings(settings),
            ecr_config_dir: env.config_dir.join("ecr"),
            ecr_state_dir: env.state_dir.join("ecr"),
            use_index: settings.index.unwrap_or(true),
        })
    }

    /// The user-facing settings file, shared by every client.
    pub fn settings_file(&self) -> PathBuf {
        self.ecr_config_dir.join("settings.toml")
    }

    /// The OAuth profiles, anchored to this `Env` rather than to the process.
    ///
    /// Doctor reports on tokens, and reading one adopts it from oauthman's
    /// directory — so resolving the store from `dirs::config_dir()` instead of
    /// from here made an integration test against a tempdir read, and write to,
    /// the developer's real `~/.config/ecr`. That is the same trap as
    /// `NOTMUCH_CONFIG` outranking a redirected `HOME`: isolation has to come
    /// from the one `Env` everything else already resolves through.
    pub fn oauth_profiles(&self) -> crate::oauth::Profiles {
        crate::oauth::Profiles::under(&self.ecr_config_dir, &self.ecr_state_dir)
    }

    /// Where the shipped presets are seeded and the user's own themes live.
    pub fn themes_dir(&self) -> PathBuf {
        self.ecr_config_dir.join("themes")
    }

    /// Resolves a path written in settings.toml against ecr's own directory.
    ///
    /// The link is user input that arrives over HTTP, so this is a boundary, not
    /// a convenience: anything that could climb out of `ecr_config_dir` or name a
    /// file ecr has no business reading is rejected rather than clamped. The
    /// check is lexical because the target need not exist yet — a theme can be
    /// pointed at before it is written.
    pub fn resolve_relative(&self, rel: &str) -> Result<PathBuf> {
        let unsafe_path = |reason| Error::UnsafePath {
            path: rel.to_string(),
            reason,
        };

        if rel.trim().is_empty() {
            return Err(unsafe_path("it is empty"));
        }

        let candidate = Path::new(rel);
        if candidate.is_absolute() {
            return Err(unsafe_path("it is absolute"));
        }

        for part in candidate.components() {
            match part {
                Component::Normal(_) => {}
                Component::CurDir => {}
                Component::ParentDir => return Err(unsafe_path("it climbs above the config dir")),
                Component::RootDir | Component::Prefix(_) => {
                    return Err(unsafe_path("it is absolute"));
                }
            }
        }

        if candidate.extension().and_then(|e| e.to_str()) != Some("toml") {
            return Err(unsafe_path("it is not a .toml file"));
        }

        Ok(self.ecr_config_dir.join(candidate))
    }

    pub fn xapian_dir(&self) -> PathBuf {
        self.database_path.join(".notmuch").join("xapian")
    }

    pub fn post_new_hook(&self) -> Option<PathBuf> {
        let hook = self
            .notmuch
            .path
            .as_ref()?
            .parent()?
            .join("hooks")
            .join("post-new");
        hook.is_file().then_some(hook)
    }
}

fn read_optional(resolved: &ResolvedConfig) -> Option<String> {
    std::fs::read_to_string(resolved.path.as_ref()?).ok()
}

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

    fn write(path: &Path, contents: &str) {
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, contents).unwrap();
    }

    #[test]
    fn xdg_config_wins_over_the_legacy_dotfile() {
        let home = tempfile::tempdir().unwrap();
        let home = home.path();
        write(
            &home.join(".config/notmuch/default/config"),
            "[database]\npath=/srv/Mail\n",
        );
        write(
            &home.join(".notmuch-config"),
            "[database]\npath=/srv/stale-mail\n",
        );

        let paths = MailPaths::with(&Env::rooted_at(home), &ServerSettings::default()).unwrap();

        assert_eq!(paths.notmuch.source, ConfigSource::Xdg);
        assert_eq!(paths.maildir_root, PathBuf::from("/srv/Mail"));
    }

    #[test]
    fn the_stale_dotfile_is_reported_as_shadowed() {
        let home = tempfile::tempdir().unwrap();
        let home = home.path();
        write(
            &home.join(".config/notmuch/default/config"),
            "[database]\npath=/srv/Mail\n",
        );
        write(&home.join(".notmuch-config"), "[database]\npath=/srv/old\n");

        let paths = MailPaths::with(&Env::rooted_at(home), &ServerSettings::default()).unwrap();

        assert_eq!(paths.notmuch.shadowed, vec![home.join(".notmuch-config")]);
    }

    #[test]
    fn server_settings_override_everything() {
        let home = tempfile::tempdir().unwrap();
        let home = home.path();
        write(
            &home.join(".config/notmuch/default/config"),
            "[database]\npath=/srv/xdg\n",
        );
        let explicit = home.join("explicit-config");
        write(&explicit, "[database]\npath=/srv/explicit\n");

        let settings = ServerSettings {
            notmuch_config: Some(explicit.clone()),
            ..Default::default()
        };
        let paths = MailPaths::with(&Env::rooted_at(home), &settings).unwrap();

        assert_eq!(paths.notmuch.source, ConfigSource::ServerToml);
        assert_eq!(paths.maildir_root, PathBuf::from("/srv/explicit"));
    }

    #[test]
    fn falls_back_to_the_legacy_dotfile_when_xdg_is_absent() {
        let home = tempfile::tempdir().unwrap();
        let home = home.path();
        write(
            &home.join(".notmuch-config"),
            "[database]\npath=/srv/only\n",
        );

        let paths = MailPaths::with(&Env::rooted_at(home), &ServerSettings::default()).unwrap();

        assert_eq!(paths.notmuch.source, ConfigSource::LegacyDotfile);
        assert_eq!(paths.maildir_root, PathBuf::from("/srv/only"));
    }

    #[test]
    fn missing_notmuch_config_lists_every_location_searched() {
        let home = tempfile::tempdir().unwrap();
        let err =
            MailPaths::with(&Env::rooted_at(home.path()), &ServerSettings::default()).unwrap_err();

        let message = err.to_string();
        assert!(
            message.contains(".config/notmuch/default/config"),
            "{message}"
        );
        assert!(message.contains(".notmuch-config"), "{message}");
    }

    #[test]
    fn maildir_root_never_guesses_from_the_data_dir() {
        let home = tempfile::tempdir().unwrap();
        let home = home.path();
        write(
            &home.join(".config/notmuch/default/config"),
            "[database]\npath=/home/someone/.local/share/Mail\n",
        );

        let paths = MailPaths::with(&Env::rooted_at(home), &ServerSettings::default()).unwrap();

        assert_eq!(
            paths.maildir_root,
            PathBuf::from("/home/someone/.local/share/Mail")
        );
    }

    fn rooted_paths(home: &Path) -> MailPaths {
        write(
            &home.join(".config/notmuch/default/config"),
            "[database]\npath=/srv/Mail\n",
        );
        MailPaths::with(&Env::rooted_at(home), &ServerSettings::default()).unwrap()
    }

    #[test]
    fn a_relative_theme_resolves_inside_the_config_dir() {
        let home = tempfile::tempdir().unwrap();
        let paths = rooted_paths(home.path());

        assert_eq!(
            paths.resolve_relative("themes/nord.toml").unwrap(),
            home.path().join(".config/ecr/themes/nord.toml")
        );
    }

    #[test]
    fn a_relative_path_cannot_climb_out_of_the_config_dir() {
        let home = tempfile::tempdir().unwrap();
        let paths = rooted_paths(home.path());

        for attempt in [
            "../../../etc/passwd.toml",
            "themes/../../secrets.toml",
            "/etc/passwd.toml",
            "themes/../../../../../../etc/shadow.toml",
        ] {
            assert!(
                paths.resolve_relative(attempt).is_err(),
                "{attempt} was accepted"
            );
        }
    }

    #[test]
    fn only_toml_files_resolve() {
        let home = tempfile::tempdir().unwrap();
        let paths = rooted_paths(home.path());

        assert!(paths.resolve_relative("themes/nord.conf").is_err());
        assert!(paths.resolve_relative("../.ssh/id_rsa").is_err());
        assert!(paths.resolve_relative("").is_err());
        assert!(paths.resolve_relative("   ").is_err());
    }
}