use crate::error::{Error, Result};
use crate::merge::{MergeReport, merge};
use crate::plugin::{Operation, Plugin, Report, Request, invoke};
use crate::vault::Vault;
use std::path::Path;
#[derive(Debug, Clone)]
pub struct PullReport {
pub transport: Report,
pub merged: MergeReport,
}
pub fn push(vault: &Vault, plugin: &Plugin, name: &str) -> Result<Report> {
invoke(
plugin,
&Request {
operation: Operation::Push,
file: vault.path(),
name,
},
)
}
pub fn pull(
vault: &mut Vault,
plugin: &Plugin,
name: &str,
remote_password: &[u8],
) -> Result<PullReport> {
let scratch = Scratch::new()?;
let transport = invoke(
plugin,
&Request {
operation: Operation::Pull,
file: scratch.path(),
name,
},
)?;
if !scratch.path().exists() {
return Err(Error::PluginFailed {
name: plugin.name().to_owned(),
reason: "it reported success but wrote no file".into(),
});
}
let remote = Vault::open(scratch.path(), remote_password)?;
let merged = merge(vault, &remote)?;
drop(remote);
Ok(PullReport { transport, merged })
}
pub fn sync(
vault: &mut Vault,
plugin: &Plugin,
name: &str,
remote_password: &[u8],
) -> Result<SyncReport> {
let pulled = pull(vault, plugin, name, remote_password)?;
let pushed = push(vault, plugin, name)?;
Ok(SyncReport { pulled, pushed })
}
#[derive(Debug, Clone)]
pub struct SyncReport {
pub pulled: PullReport,
pub pushed: Report,
}
struct Scratch {
_directory: tempfile::TempDir,
file: std::path::PathBuf,
}
impl Scratch {
fn new() -> Result<Self> {
let directory = tempfile::Builder::new()
.prefix(".sefy-")
.tempdir()
.map_err(|source| Error::io("cannot create a temporary directory", source))?;
let file = directory.path().join("blob");
Ok(Self {
_directory: directory,
file,
})
}
fn path(&self) -> &Path {
&self.file
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{NewItem, Payload};
use crate::plugin::discover_in;
use std::path::PathBuf;
const PASSWORD: &[u8] = b"master password";
fn file_transport(directory: &Path, remote: &Path, log: &Path) {
let manifest = r#"{"protocol_version":1,"name":"file","version":"0.1.0","operations":["push","pull"]}"#;
let remote = remote.display().to_string();
let log = log.display().to_string();
#[cfg(windows)]
{
let manifest_path = directory.join("manifest.json");
std::fs::write(&manifest_path, manifest).unwrap();
let script = directory.join("transport.ps1");
std::fs::write(
&script,
format!(
"$request = [Console]::In.ReadToEnd() | ConvertFrom-Json\r\n\
Set-Content -LiteralPath '{log}' -Value $request.file -NoNewline\r\n\
if ($request.operation -eq 'push') {{ Copy-Item -LiteralPath $request.file -Destination '{remote}' -Force }}\r\n\
else {{ Copy-Item -LiteralPath '{remote}' -Destination $request.file -Force }}\r\n"
),
)
.unwrap();
let path = directory.join("sefy-plugin-file.cmd");
std::fs::write(
&path,
format!(
"@echo off\r\n\
if \"%1\"==\"--manifest\" (type \"{manifest}\" & exit /b 0)\r\n\
powershell -NoProfile -ExecutionPolicy Bypass -File \"{script}\"\r\n",
manifest = manifest_path.display(),
script = script.display(),
),
)
.unwrap();
}
#[cfg(not(windows))]
{
use std::os::unix::fs::PermissionsExt;
let path = directory.join("sefy-plugin-file");
std::fs::write(
&path,
format!(
r#"#!/bin/sh
if [ "$1" = "--manifest" ]; then
printf '%s' '{manifest}'
exit 0
fi
REQUEST=$(cat)
FILE=$(printf '%s' "$REQUEST" | sed 's/.*"file":"//; s/".*//')
printf '%s' "$FILE" > '{log}'
case "$REQUEST" in
*'"operation":"push"'*) cp "$FILE" '{remote}' ;;
*) cp '{remote}' "$FILE" ;;
esac
"#
),
)
.unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
}
fn silent_transport(directory: &Path, operations: &str) {
let manifest = format!(
r#"{{"protocol_version":1,"name":"silent","version":"0.1.0","operations":{operations}}}"#
);
#[cfg(windows)]
{
let manifest_path = directory.join("silent.json");
std::fs::write(&manifest_path, &manifest).unwrap();
std::fs::write(
directory.join("sefy-plugin-silent.cmd"),
format!(
"@echo off\r\nif \"%1\"==\"--manifest\" (type \"{}\")\r\n",
manifest_path.display()
),
)
.unwrap();
}
#[cfg(not(windows))]
{
use std::os::unix::fs::PermissionsExt;
let path = directory.join("sefy-plugin-silent");
std::fs::write(
&path,
format!(
r#"#!/bin/sh
if [ "$1" = "--manifest" ]; then
printf '%s' '{manifest}'
fi
"#
),
)
.unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
}
fn installed(directory: &Path, name: &str) -> Plugin {
discover_in(&[directory.to_path_buf()])
.into_iter()
.find(|plugin| plugin.name() == name)
.unwrap_or_else(|| panic!("the {name} plugin must be discovered"))
}
fn note(vault: &mut Vault, title: &str, text: &str) {
vault
.add(NewItem::new(title, Payload::Note { text: text.into() }))
.unwrap();
vault.save().unwrap();
}
fn titles(vault: &Vault) -> Vec<String> {
let mut names: Vec<String> = vault
.list()
.unwrap()
.into_iter()
.map(|summary| summary.title)
.collect();
names.sort();
names
}
fn fetched_path(log: &Path) -> PathBuf {
let recorded = std::fs::read_to_string(log)
.expect("the transport must have been asked to move something");
PathBuf::from(recorded.trim())
}
fn remote_holding(directory: &Path, title: &str, password: &[u8]) -> PathBuf {
let elsewhere = directory.join("elsewhere.bak");
let mut theirs = Vault::create(&elsewhere, password).unwrap();
note(&mut theirs, title, "from over there");
let remote = directory.join("remote.bin");
std::fs::copy(&elsewhere, &remote).unwrap();
remote
}
#[test]
fn a_push_puts_the_sealed_file_at_the_remote_byte_for_byte() {
let directory = tempfile::tempdir().unwrap();
let local = directory.path().join("notes.bak");
let remote = directory.path().join("remote.bin");
let mut vault = Vault::create(&local, PASSWORD).unwrap();
note(&mut vault, "bank", "vault code 1234");
file_transport(directory.path(), &remote, &directory.path().join("log"));
let plugin = installed(directory.path(), "file");
push(&vault, &plugin, "vault").unwrap();
assert_eq!(
std::fs::read(&local).unwrap(),
std::fs::read(&remote).unwrap(),
"what travels is the sealed file, unchanged"
);
}
#[test]
fn what_the_transport_carries_is_never_readable_as_plaintext() {
let directory = tempfile::tempdir().unwrap();
let local = directory.path().join("notes.bak");
let remote = directory.path().join("remote.bin");
let mut vault = Vault::create(&local, PASSWORD).unwrap();
note(&mut vault, "bank", "SECRETVALUE");
file_transport(directory.path(), &remote, &directory.path().join("log"));
let plugin = installed(directory.path(), "file");
push(&vault, &plugin, "vault").unwrap();
let carried = std::fs::read(&remote).unwrap();
assert!(
!carried
.windows(b"SECRETVALUE".len())
.any(|window| window == b"SECRETVALUE"),
"the remote holds ciphertext, not the note"
);
}
#[test]
fn a_pull_folds_the_remote_copy_in_and_keeps_what_is_here() {
let directory = tempfile::tempdir().unwrap();
let remote = remote_holding(directory.path(), "their note", PASSWORD);
let local = directory.path().join("notes.bak");
let mut vault = Vault::create(&local, PASSWORD).unwrap();
note(&mut vault, "my note", "from here");
file_transport(directory.path(), &remote, &directory.path().join("log"));
let plugin = installed(directory.path(), "file");
let report = pull(&mut vault, &plugin, "vault", PASSWORD).unwrap();
assert_eq!(report.merged.added, 1);
assert_eq!(titles(&vault), vec!["my note", "their note"]);
let reopened = Vault::open(&local, PASSWORD).unwrap();
assert_eq!(titles(&reopened), vec!["my note", "their note"]);
}
#[test]
fn a_pull_leaves_no_copy_of_the_remote_vault_behind() {
let directory = tempfile::tempdir().unwrap();
let remote = remote_holding(directory.path(), "their note", PASSWORD);
let local = directory.path().join("notes.bak");
let mut vault = Vault::create(&local, PASSWORD).unwrap();
let log = directory.path().join("log");
file_transport(directory.path(), &remote, &log);
let plugin = installed(directory.path(), "file");
pull(&mut vault, &plugin, "vault", PASSWORD).unwrap();
let fetched = fetched_path(&log);
assert!(
!fetched.exists(),
"the fetched copy is still at {}",
fetched.display()
);
assert!(
!fetched.parent().unwrap().exists(),
"the scratch directory outlived the pull"
);
}
#[test]
fn a_pull_under_the_wrong_password_changes_nothing_here() {
let directory = tempfile::tempdir().unwrap();
let remote = remote_holding(directory.path(), "their note", b"another password");
let local = directory.path().join("notes.bak");
let mut vault = Vault::create(&local, PASSWORD).unwrap();
note(&mut vault, "my note", "from here");
let log = directory.path().join("log");
file_transport(directory.path(), &remote, &log);
let plugin = installed(directory.path(), "file");
let error = pull(&mut vault, &plugin, "vault", PASSWORD).unwrap_err();
assert!(matches!(error, Error::WrongPasswordOrNotAVault));
assert_eq!(titles(&vault), vec!["my note"]);
let fetched = fetched_path(&log);
assert!(
!fetched.exists(),
"a failed pull left the fetched copy at {}",
fetched.display()
);
}
#[test]
fn a_transport_reporting_success_without_a_file_says_so() {
let directory = tempfile::tempdir().unwrap();
let local = directory.path().join("notes.bak");
let mut vault = Vault::create(&local, PASSWORD).unwrap();
silent_transport(directory.path(), r#"["push","pull"]"#);
let plugin = installed(directory.path(), "silent");
let error = pull(&mut vault, &plugin, "vault", PASSWORD).unwrap_err();
let message = error.to_string();
assert!(message.contains("wrote no file"), "got: {message}");
}
#[test]
fn a_sync_takes_the_other_side_first_and_publishes_the_result() {
let directory = tempfile::tempdir().unwrap();
let remote = remote_holding(directory.path(), "their note", PASSWORD);
let local = directory.path().join("notes.bak");
let mut vault = Vault::create(&local, PASSWORD).unwrap();
note(&mut vault, "my note", "from here");
file_transport(directory.path(), &remote, &directory.path().join("log"));
let plugin = installed(directory.path(), "file");
let report = sync(&mut vault, &plugin, "vault", PASSWORD).unwrap();
assert_eq!(report.pulled.merged.added, 1);
let published = directory.path().join("published.bak");
std::fs::copy(&remote, &published).unwrap();
let published = Vault::open(&published, PASSWORD).unwrap();
assert_eq!(titles(&published), vec!["my note", "their note"]);
}
#[test]
fn a_transport_that_only_pushes_is_refused_a_pull_before_it_runs() {
let directory = tempfile::tempdir().unwrap();
let local = directory.path().join("notes.bak");
let mut vault = Vault::create(&local, PASSWORD).unwrap();
silent_transport(directory.path(), r#"["push"]"#);
let plugin = installed(directory.path(), "silent");
let error = pull(&mut vault, &plugin, "vault", PASSWORD).unwrap_err();
assert!(error.to_string().contains("pull"), "got: {error}");
}
}