Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ QML_FILES := ui/Service.qml ui/BarWidget.qml ui/App.qml ui/compose/RecoveryContr
ui/components/LabelPicker.qml \
ui/components/UndoSendToast.qml \
ui/components/DraftSavedToast.qml \
ui/components/EmlSavedToast.qml \
ui/components/SearchBar.qml \
ui/components/AppMenu.qml \
ui/components/AccountSwitcher.qml \
Expand Down
16 changes: 15 additions & 1 deletion backend-api.json
Original file line number Diff line number Diff line change
Expand Up @@ -1361,6 +1361,19 @@
"equals": {
"message": "mail_account_unknown"
}
},
{
"name": "mail.exportEml refuses a folder that is not an absolute plain path",
"method": "mail.exportEml",
"params": {
"account": "imap:sender@example.org",
"id": "1:INBOX",
"directory": "../Downloads"
},
"errorCode": -32602,
"equals": {
"message": "Invalid params"
}
}
],
"unreleased": {
Expand All @@ -1375,7 +1388,8 @@
"mail.exportEml rejects unknown fields",
"mail.exportEml rejects a malformed UID before provider work",
"mail.exportEml rejects controlled filename hints",
"mail.exportEml rejects account controls before normalization"
"mail.exportEml rejects account controls before normalization",
"mail.exportEml refuses a folder that is not an absolute plain path"
]
}
}
26 changes: 25 additions & 1 deletion scripts/attachment.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# attachment.sh read <path>
# attachment.sh clipboard <dir>
# attachment.sh pick
# attachment.sh folder
# attachment.sh forget <dir> <path>
#
# One JSON object on stdout. Quickshell's Process.write() never closes stdin,
Expand Down Expand Up @@ -279,6 +280,26 @@ pick_files() {
emit_paths "$list"
}

# One folder, through the same out-of-process chooser, for Save as .eml.
pick_folder() {
list=
if command -v omarchy-file-select >/dev/null 2>&1; then
list=$(omarchy-file-select --title 'Save .eml to' --directory 2>/dev/null || true)
elif command -v zenity >/dev/null 2>&1; then
list=$(zenity --file-selection --directory --title='Save .eml to' 2>/dev/null || true)
else
fail_json "No folder picker is available"
fi
list=$(printf '%s\n' "$list" | sed -n '1p')
# The backend takes a folder only in its plain form, so no trailing slash.
while [ "${#list}" -gt 1 ] && [ "${list%/}" != "$list" ]; do list=${list%/}; done
case "$list" in
/*) ;;
*) fail_json "cancelled" ;;
esac
emit_paths "$list"
}

command=${1:-}
case "$command" in
read)
Expand All @@ -292,12 +313,15 @@ case "$command" in
pick)
pick_files
;;
folder)
pick_folder
;;
forget)
[ -n "${2:-}" ] && [ -n "${3:-}" ] || fail_json "That file is not a draft attachment"
forget_file "$2" "$3"
;;
*)
printf '%s\n' 'usage: attachment.sh read <path> | clipboard <dir> | pick | forget <dir> <path>' >&2
printf '%s\n' 'usage: attachment.sh read <path> | clipboard <dir> | pick | folder | forget <dir> <path>' >&2
exit 2
;;
esac
5 changes: 4 additions & 1 deletion src/backend/mail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,10 @@ impl Session {
"mail.exportEml" => {
let request = ExportRequest::try_from(params)?;
let refusals = crate::account::refusals_readonly(&request.account.id)?;
let downloads = crate::platform::dirs::AppDirs::discover()?.downloads;
let downloads = match &request.directory {
Some(chosen) => chosen.clone(),
None => crate::platform::dirs::AppDirs::discover()?.downloads,
};
let control = crate::mail::export::ExportControl::new();
crate::mail::export::export_with(
request,
Expand Down
115 changes: 113 additions & 2 deletions src/mail/export.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! Save one message's original bytes as `.eml` in the user's Downloads folder.
//! Save one message's original bytes as `.eml` in the user's Downloads folder,
//! or in a folder the user picked.
//!
//! The bytes come from the provider's raw-message operation (`imap.rawMessage`)
//! and are written unchanged. The `mail.exportEml` RPC contract is fixed; this
Expand Down Expand Up @@ -323,14 +324,18 @@ async fn run_export(
let downloads = downloads.to_path_buf();
let deadline_std = deadline.into_std();
let cancel = control.cancel.clone();
// Downloads is created on first use. A folder the user picked must already
// exist and pass the same ownership checks: a picker answer is never a
// reason to create directories.
let create = request.directory.is_none();
// Storage is synchronous create/write/fsync, so it runs on a blocking
// worker rather than a Tokio worker. The destination directory is anchored
// to a descriptor before the deadline is observed, so a path swap after the
// check cannot redirect the write. The exclusive create is the commit
// point: a cancellation or an expired deadline observed before it leaves no
// file; after it the write completes and success is returned.
let path = tokio::task::spawn_blocking(move || {
let dir = crate::platform::private_fs::directories(&downloads, &[], true)
let dir = crate::platform::private_fs::directories(&downloads, &[], create)
.map_err(|_| "mail_export_write_failed")?
.ok_or("mail_export_write_failed")?;
write_unique_in(&downloads, &dir, &filename, &bytes, deadline_std, &cancel)
Expand Down Expand Up @@ -532,6 +537,52 @@ mod tests {
dir
}

#[cfg(unix)]
#[test]
fn a_chosen_folder_must_be_an_absolute_plain_path() {
if crate::mail::tests::isolated() {
return;
}
let fixture = crate::mail::tests::account_fixture(json!({
"version": 1,
"activeId": "imap:owner@example.org",
"accounts": [{"provider": "imap", "email": "owner@example.org",
"imap": {"username": "owner@example.org"}}]
}));
let before = crate::mail::tests::fixture_tree(&fixture.root);
let parse = |directory: Value| {
ExportRequest::try_from(&json!({
"account": "imap:owner@example.org", "id": "1:INBOX", "directory": directory
}))
.map(|request| request.directory)
};
assert_eq!(
parse(json!("/home/owner/Mail")),
Ok(Some(PathBuf::from("/home/owner/Mail")))
);
for refused in [
json!(""),
json!("Mail"),
json!("./Mail"),
json!("/home/owner/../other"),
json!("/home/owner/./Mail"),
json!("/home/owner//Mail"),
json!("/home/owner/Mail/"),
json!("/home/owner/Mail\n"),
json!("/home/owner/\u{0}Mail"),
json!(null),
json!(7),
] {
assert_eq!(parse(refused.clone()), Err("invalid_params"), "{refused}");
}
let request = ExportRequest::try_from(&json!({
"account": "imap:owner@example.org", "id": "1:INBOX"
}))
.unwrap();
assert_eq!(request.directory, None, "no folder means Downloads");
assert_eq!(crate::mail::tests::fixture_tree(&fixture.root), before);
}

#[test]
fn export_requires_an_explicit_account_without_creating_state() {
if crate::mail::tests::isolated() {
Expand Down Expand Up @@ -771,6 +822,7 @@ mod tests {
},
id: "42:INBOX".into(),
suggested_name: "Project update".into(),
directory: None,
}
}

Expand Down Expand Up @@ -1113,6 +1165,65 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}

// A picked folder receives the file, and one that is missing is refused
// rather than created: only Downloads is made on first use.
#[tokio::test]
async fn a_chosen_folder_is_written_to_but_never_created() {
let dir = scratch("chosen");
let limits = ExportLimits::new();
let adapter = Fake {
payload: json!({"bytes": 4, "data": STANDARD.encode(b"body")}),
};
let mut chosen = request();
chosen.directory = Some(dir.clone());
let saved = export_with(
chosen,
&adapter,
&dir,
&Value::Null,
&limits,
&ExportControl::new(),
)
.await
.unwrap();
assert_eq!(
Path::new(saved["path"].as_str().unwrap()),
dir.join("Project update.eml")
);
assert_eq!(fs::read(dir.join("Project update.eml")).unwrap(), b"body");

let missing = dir.join("not-there");
let mut chosen = request();
chosen.directory = Some(missing.clone());
assert_eq!(
export_with(
chosen,
&adapter,
&missing,
&Value::Null,
&limits,
&ExportControl::new()
)
.await,
Err("mail_export_write_failed")
);
assert!(!missing.exists(), "a picked folder is never created");

let downloads = dir.join("Downloads");
let made = export_with(
request(),
&adapter,
&downloads,
&Value::Null,
&limits,
&ExportControl::new(),
)
.await;
assert!(made.is_ok(), "{made:?}");
assert!(downloads.join("Project update.eml").is_file());
fs::remove_dir_all(dir).unwrap();
}

// A swap of the destination directory after it is anchored must not
// redirect the file: the handle still names the original directory.
#[cfg(unix)]
Expand Down
32 changes: 31 additions & 1 deletion src/mail/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -381,13 +381,15 @@ pub struct ExportRequest {
pub account: Account,
pub id: String,
pub suggested_name: String,
/// A folder the user picked. `None` saves to Downloads.
pub directory: Option<PathBuf>,
}

impl TryFrom<&Value> for ExportRequest {
type Error = &'static str;

fn try_from(value: &Value) -> Result<Self, Self::Error> {
let object = params_object(value, &["account", "id", "suggestedName"])?;
let object = params_object(value, &["account", "id", "suggestedName", "directory"])?;
let wanted = object
.get("account")
.and_then(Value::as_str)
Expand All @@ -404,14 +406,42 @@ impl TryFrom<&Value> for ExportRequest {
if suggested_name.chars().any(char::is_control) {
return Err("invalid_params");
}
let directory = export_directory(object.get("directory"))?;
Ok(Self {
account,
id,
suggested_name,
directory,
})
}
}

/// A chosen destination is an absolute, already normalized folder path. The
/// writer still anchors it by descriptor and refuses a missing or unsafe one;
/// this only rejects what can never name a folder before any work starts.
fn export_directory(value: Option<&Value>) -> Result<Option<PathBuf>, &'static str> {
let Some(value) = value else {
return Ok(None);
};
let text = value.as_str().ok_or("invalid_params")?;
let path = std::path::Path::new(text);
// `components()` quietly drops an inner `.`, a doubled or trailing
// separator, so the path must also be exactly its own normal form.
let normal: PathBuf = path.components().collect();
if text.is_empty()
|| text.len() > 4096
|| text.chars().any(char::is_control)
|| !path.is_absolute()
|| normal.as_os_str() != path.as_os_str()
|| path
.components()
.any(|part| matches!(part, std::path::Component::ParentDir))
{
return Err("invalid_params");
}
Ok(Some(path.to_path_buf()))
}

/// Export needs an explicit account. An empty or unknown id is refused and
/// never falls back to the registry's active account, unlike `resolve_account`.
fn resolve_export_account(wanted: &str) -> Result<Account, &'static str> {
Expand Down
34 changes: 34 additions & 0 deletions tests/test_attachment.sh
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,40 @@ answer=$(sh "$script" pick)
check "a cancelled picker is cancelled, not an error" "$(json_field error "$answer")" "cancelled"
unset OMAMAIL_PICK_OUT OMAMAIL_PICK_EXIT

# A folder for Save as .eml: the chooser is asked for a directory, and only
# its first absolute answer is returned.
cat > "$work/bin/omarchy-file-select" <<'STUB'
#!/bin/sh
printf '%s\n' "$*" > "$OMAMAIL_PICK_ARGS"
printf '%s\n' "$OMAMAIL_PICK_OUT"
exit "${OMAMAIL_PICK_EXIT:-0}"
STUB
chmod +x "$work/bin/omarchy-file-select"
OMAMAIL_PICK_ARGS=$work/pick-args
OMAMAIL_PICK_OUT=$(printf '%s\n' "/home/ada/Mail archive" /home/ada/other)
export OMAMAIL_PICK_ARGS OMAMAIL_PICK_OUT
answer=$(sh "$script" folder)
check "folder says ok" "$(json_field ok "$answer")" "True"
picked=$(printf '%s' "$answer" | python3 -c 'import json,sys; print("\n".join(json.load(sys.stdin)["paths"]))')
check "folder returns only the first folder" "$picked" "/home/ada/Mail archive"
case "$(cat "$OMAMAIL_PICK_ARGS")" in
*--directory*) ok "folder asks the chooser for a directory" ;;
*) bad "folder asks the chooser for a directory" ;;
esac
OMAMAIL_PICK_OUT=/home/ada/Mail/
answer=$(sh "$script" folder)
picked=$(printf '%s' "$answer" | python3 -c 'import json,sys; print(json.load(sys.stdin)["paths"][0])')
check "a trailing slash is dropped" "$picked" "/home/ada/Mail"
OMAMAIL_PICK_OUT=relative/folder
answer=$(sh "$script" folder)
check "a relative folder is refused as cancelled" "$(json_field error "$answer")" "cancelled"
OMAMAIL_PICK_EXIT=1
OMAMAIL_PICK_OUT=
export OMAMAIL_PICK_EXIT OMAMAIL_PICK_OUT
answer=$(sh "$script" folder)
check "a cancelled folder chooser is cancelled" "$(json_field error "$answer")" "cancelled"
unset OMAMAIL_PICK_OUT OMAMAIL_PICK_EXIT OMAMAIL_PICK_ARGS

# forget only deletes files this script wrote into the compose dir.
printf 'keep\n' > "$work/outside.txt"
sh "$script" forget "$work/compose" "$work/outside.txt" >/dev/null 2>&1 || true
Expand Down
2 changes: 2 additions & 0 deletions ui/App.qml
Original file line number Diff line number Diff line change
Expand Up @@ -2429,6 +2429,8 @@ Item {
panelFontFamily: root.fontFamily
}

EmlSavedToast { app: root }

// --------------------------------------------------------- status bar

Item {
Expand Down
Loading
Loading