Skip to main content

nibkeep_node/library/
secret_files.rs

1//! Secret files: content that only the replicas holding the secrets read, such as the scan
2//! of a passport, sealed in the store, with no record of where it was found or of its plain
3//! copies ([technical design: secret files]).
4//!
5//! [technical design: secret files]: ../../../../docs/Technical-design.md#95-secret-files
6
7use std::fs::{File, OpenOptions};
8use std::io::{self, Read};
9use std::path::{Path, PathBuf};
10
11use nibkeep_base::{EntityId, Hash, SpaceId};
12use nibkeep_crypto::Zeroizing;
13use nibkeep_crypto::rand_core::CryptoRng;
14use nibkeep_model::{Name, Value, fields};
15use nibkeep_std::{ATTACHED_TO, CONTENT, MEDIA_TYPE, SECRET_CONTENT, SECRET_FILE, SIZE};
16
17use super::Library;
18use super::checkouts::{copy_checked, place_for, put_in_place, remove_leftover, temporary_for};
19use super::entities::NewValue;
20use super::files::HEAD;
21use crate::NodeError;
22
23/// What adding a secret file did.
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct AddedSecretFile {
26	/// The secret file.
27	pub file: EntityId,
28	/// The hash of its content.
29	pub content: Hash,
30	/// Its media type, as its first bytes tell it, if they do.
31	pub media_type: Option<String>,
32	/// Its size in bytes.
33	pub size: u64,
34	/// Whether the space holds the same content where the secrets do not protect it, as an
35	/// ordinary file's, which every replica can read.
36	pub unprotected_copy: bool,
37}
38
39impl Library {
40	/// Adds a secret file to a space, with its secrets unlocked: seals `content` for the
41	/// secrets, so that only the replicas that hold them read it, and records it as a secret
42	/// file named `name`, with its media type as its first bytes tell it and its size,
43	/// attached to the entities `attached_to`. Nothing records where it was found: the person
44	/// decides what becomes of the original. The type of secret files is added to the space
45	/// if it lacks it.
46	///
47	/// # Errors
48	///
49	/// Returns [`NodeError::SecretsLocked`] if the space's secrets are locked or were never
50	/// set up, [`NodeError::NoEntity`] if an entity to attach it to is not in the space,
51	/// [`NodeError::Unreadable`], naming the file by `name`, if reading `content` fails, and
52	/// another error if the library has no such space, or the content or the change cannot
53	/// be saved.
54	pub fn add_secret_file(
55		&mut self,
56		space: SpaceId,
57		name: &str,
58		content: impl Read,
59		attached_to: &[EntityId],
60		wall_millis: u64,
61		rng: &mut impl CryptoRng,
62	) -> Result<AddedSecretFile, NodeError> {
63		if !self.secrets_unlocked(space) {
64			return Err(NodeError::SecretsLocked);
65		}
66		// What would be refused is refused before anything is sealed.
67		self.check_not_revoked(space)?;
68		let mut records = Vec::with_capacity(attached_to.len());
69		{
70			let state = self.space(space)?.stored.log().state();
71			for &record in attached_to {
72				let canonical = state.canonical(record)?;
73				if state.is_deleted(canonical)? || state.types(canonical)?.is_empty() {
74					return Err(NodeError::NoEntity(record.to_string()));
75				}
76				records.push(canonical);
77			}
78		}
79		self.install_standard(space, &[SECRET_FILE], wall_millis, rng)?;
80		let mut reading = Sniffed {
81			inner: content,
82			head: Zeroizing::new(Vec::with_capacity(HEAD)),
83			size: 0,
84			failed: None,
85		};
86		let imported = self.seal_blob(space, (&mut reading, true), wall_millis, rng);
87		// An error of reading the file is the file's; any other is the library's.
88		let content = match (imported, reading.failed.take()) {
89			(Ok(content), _) => content,
90			(Err(_), Some(reason)) => {
91				return Err(NodeError::Unreadable {
92					path: name.to_owned(),
93					reason,
94				});
95			}
96			(Err(error), None) => return Err(error),
97		};
98		// An ordinary copy here, or a file anywhere that holds the content, as the space says.
99		let open = self.space(space)?;
100		let unprotected_copy = open.stored.holds_ordinary_blob(&content)
101			|| !open
102				.stored
103				.find(&CONTENT, &Value::Blob(content))?
104				.is_empty();
105		let media_type = infer::get(&reading.head).map(|kind| kind.mime_type().to_owned());
106		let size = reading.size;
107		drop(reading);
108
109		let mut values = Vec::new();
110		if !name.trim().is_empty() {
111			values.push(NewValue::new(fields::NAME, Value::Name(Name::new(name))));
112		}
113		values.push(NewValue::new(SECRET_CONTENT, Value::Blob(content)));
114		if let Some(media_type) = &media_type {
115			values.push(NewValue::new(MEDIA_TYPE, Value::Text(media_type.clone())));
116		}
117		values.push(NewValue::new(
118			SIZE,
119			Value::Integer(i64::try_from(size).unwrap_or(i64::MAX)),
120		));
121		values.extend(
122			records
123				.into_iter()
124				.map(|record| NewValue::new(ATTACHED_TO, Value::Reference(record))),
125		);
126		let (file, operations) = self.new_entity(space, &[SECRET_FILE], values, rng)?;
127		self.commit(space, operations, wall_millis, rng)?;
128		Ok(AddedSecretFile {
129			file,
130			content,
131			media_type,
132			size,
133			unprotected_copy,
134		})
135	}
136
137	/// Opens the content of a secret file of a space for reading, with the secrets unlocked.
138	/// The reader checks the content's hash when it reads all of it in order.
139	///
140	/// # Errors
141	///
142	/// Returns [`NodeError::SecretsLocked`] if the space's secrets are locked,
143	/// [`NodeError::NotSecretFile`] if the entity is no secret file, [`NodeError::Deleted`] if
144	/// it is deleted, [`NodeError::NoCopyHere`] if this device holds no copy of its content
145	/// yet, and another error if the library has no such space, or the content cannot be read.
146	pub fn open_secret_file(
147		&self,
148		space: SpaceId,
149		file: EntityId,
150	) -> Result<impl Read + use<>, NodeError> {
151		let (file, name, content) = self.secret_content(space, file)?;
152		self.open_content(space, (file, name.as_deref()), &content)
153	}
154
155	/// Opens content that this device holds a copy of, for reading.
156	fn open_content(
157		&self,
158		space: SpaceId,
159		(file, name): (EntityId, Option<&str>),
160		content: &Hash,
161	) -> Result<impl Read + use<>, NodeError> {
162		let stored = &self.space(space)?.stored;
163		if !stored.holds_blob(content) {
164			let name = name.map_or_else(|| file.to_string(), str::to_owned);
165			return Err(NodeError::NoCopyHere(name));
166		}
167		Ok(stored.open_blob(content)?)
168	}
169
170	/// Saves a plain copy of a secret file of a space, with the secrets unlocked, at
171	/// `place`: into a folder, under the file's name, or as a new file. Nothing records it:
172	/// NibKeep neither protects the copy, nor knows of it, nor deletes it when the file is
173	/// purged. It replaces nothing. The copy is written beside its place first, checked
174	/// against the content's hash and synced; on Unix, only its owner may read it. Returns
175	/// where the copy is.
176	///
177	/// # Errors
178	///
179	/// Returns the errors of [`Library::open_secret_file`], [`NodeError::PlaceTaken`] if
180	/// something is where the copy would go, [`NodeError::NotAFileName`] if a copy into a
181	/// folder would have no name, and [`NodeError::File`] if writing fails.
182	pub fn save_secret_file(
183		&self,
184		space: SpaceId,
185		file: EntityId,
186		place: &Path,
187	) -> Result<PathBuf, NodeError> {
188		let (file, name, content) = self.secret_content(space, file)?;
189		let path = place_for(place, name.as_deref())?;
190		if path.symlink_metadata().is_ok() {
191			return Err(NodeError::PlaceTaken(path));
192		}
193		let mut reader = self.open_content(space, (file, name.as_deref()), &content)?;
194		let temporary = temporary_for(&path, "copy");
195		remove_leftover(&temporary);
196		let written = write_private(&temporary, &mut reader, &content);
197		match written {
198			Ok(true) => {}
199			Ok(false) => {
200				remove_leftover(&temporary);
201				return Err(NodeError::Store(nibkeep_store::StoreError::DamagedBlob));
202			}
203			Err(error) => {
204				remove_leftover(&temporary);
205				return Err(NodeError::file(&temporary)(error));
206			}
207		}
208		if let Err(error) = put_in_place(&temporary, &path) {
209			remove_leftover(&temporary);
210			if error.kind() == io::ErrorKind::AlreadyExists {
211				return Err(NodeError::PlaceTaken(path));
212			}
213			return Err(NodeError::file(&path)(error));
214		}
215		Ok(path)
216	}
217
218	/// A secret file of a space, as the entity it is now, its name, and its current content:
219	/// of competing values, the one in the statement with the smallest ID.
220	fn secret_content(
221		&self,
222		space: SpaceId,
223		file: EntityId,
224	) -> Result<(EntityId, Option<String>, Hash), NodeError> {
225		if !self.secrets_unlocked(space) {
226			return Err(NodeError::SecretsLocked);
227		}
228		let state = self.space(space)?.stored.log().state();
229		let file = state.canonical(file)?;
230		let name = state
231			.current(file, &fields::NAME)?
232			.iter()
233			.min_by_key(|statement| statement.id)
234			.and_then(|statement| statement.value.as_name_text().map(str::to_owned));
235		let described = || name.clone().unwrap_or_else(|| file.to_string());
236		if !state.types(file)?.contains(&SECRET_FILE) {
237			return Err(NodeError::NotSecretFile(described()));
238		}
239		if state.is_deleted(file)? {
240			return Err(NodeError::Deleted(described()));
241		}
242		let content = state
243			.current(file, &SECRET_CONTENT)?
244			.iter()
245			.filter(|statement| matches!(statement.value, Value::Blob(_)))
246			.min_by_key(|statement| statement.id)
247			.and_then(|statement| match statement.value {
248				Value::Blob(content) => Some(content),
249				_ => None,
250			})
251			.ok_or_else(|| NodeError::NoContent(described()))?;
252		Ok((file, name, content))
253	}
254}
255
256/// A reader that keeps the first bytes it reads, which tell the media type, counts them all,
257/// and remembers why reading failed. What it keeps is wiped when it goes.
258struct Sniffed<R> {
259	inner: R,
260	head: Zeroizing<Vec<u8>>,
261	size: u64,
262	failed: Option<String>,
263}
264
265impl<R: Read> Read for Sniffed<R> {
266	fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
267		let read = self.inner.read(buffer).inspect_err(|error| {
268			self.failed = Some(error.to_string());
269		})?;
270		let room = HEAD.saturating_sub(self.head.len());
271		self.head.extend_from_slice(&buffer[..read.min(room)]);
272		self.size += read as u64;
273		Ok(read)
274	}
275}
276
277/// Writes what `reader` reads to `temporary`, a new file that on Unix only its owner may
278/// read, and syncs it: whether what was written has the hash `content`.
279fn write_private(temporary: &Path, reader: &mut impl Read, content: &Hash) -> io::Result<bool> {
280	let mut options = OpenOptions::new();
281	options.write(true).create_new(true);
282	#[cfg(unix)]
283	std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
284	let mut copy: File = options.open(temporary)?;
285	if !copy_checked(reader, &mut copy, content)? {
286		return Ok(false);
287	}
288	copy.sync_all()?;
289	Ok(true)
290}