lib.rs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424
  1. pub use block_path::{BlockPath, BlockPathError};
  2. pub mod blocktree;
  3. /// Code which enables cryptographic operations.
  4. pub mod crypto;
  5. pub mod log;
  6. pub mod msg;
  7. mod block_path;
  8. mod sectored_buf;
  9. #[cfg(test)]
  10. mod test_helpers;
  11. mod trailered;
  12. #[macro_use]
  13. extern crate static_assertions;
  14. #[macro_use]
  15. #[cfg(test)]
  16. extern crate lazy_static;
  17. use btserde::{read_from, write_to};
  18. use crypto::{
  19. AsymKeyPub, Ciphertext, Creds, Decrypter, DecrypterExt, Encrypter, EncrypterExt, HashKind,
  20. MerkleStream, PublicCreds, SecretStream, Sign, Signature, Signer, SymKey, SymKeyKind, VarHash,
  21. };
  22. use trailered::Trailered;
  23. use ::log::error;
  24. use brotli::{CompressorWriter, Decompressor};
  25. use fuse_backend_rs::abi::fuse_abi::{stat64, Attr};
  26. use sectored_buf::SectoredBuf;
  27. use serde::{Deserialize, Serialize};
  28. use serde_big_array::BigArray;
  29. use std::{
  30. collections::{btree_map, hash_map::DefaultHasher, BTreeMap, HashMap},
  31. convert::{Infallible, TryFrom},
  32. fmt::{self, Display, Formatter},
  33. hash::{Hash as Hashable, Hasher},
  34. io::{self, Read, Seek, SeekFrom, Write},
  35. net::SocketAddr,
  36. ops::{Add, Sub},
  37. sync::PoisonError,
  38. time::{Duration, SystemTime},
  39. };
  40. use strum_macros::{Display, EnumDiscriminants, FromRepr};
  41. #[derive(Debug)]
  42. pub enum Error {
  43. MissingWritecap,
  44. Io(std::io::Error),
  45. Serde(btserde::Error),
  46. Crypto(crypto::Error),
  47. IncorrectSize { expected: usize, actual: usize },
  48. NoBlockKey,
  49. NotOpen(u64),
  50. InvalidHandle { handle: u64, inode: u64 },
  51. NoHandlesAvailable(u64),
  52. NoBlockPath,
  53. InodeNotFound(u64),
  54. Custom(Box<dyn std::fmt::Debug + Send + Sync>),
  55. }
  56. impl Error {
  57. fn custom<E: std::fmt::Debug + Send + Sync + 'static>(err: E) -> Error {
  58. Error::Custom(Box::new(err))
  59. }
  60. }
  61. impl Display for Error {
  62. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  63. match self {
  64. Error::MissingWritecap => write!(f, "missing writecap"),
  65. Error::Io(err) => err.fmt(f),
  66. Error::Serde(err) => err.fmt(f),
  67. Error::Crypto(err) => err.fmt(f),
  68. Error::IncorrectSize { expected, actual } => {
  69. write!(f, "incorrect size {actual}, expected {expected}")
  70. }
  71. Error::NoBlockKey => write!(f, "no block key is present"),
  72. Error::NotOpen(inode) => write!(f, "inode {inode} is not open"),
  73. Error::InvalidHandle { handle, inode } => {
  74. write!(f, "invalid handle {handle} for inode {inode}")
  75. }
  76. Error::NoHandlesAvailable(inode) => {
  77. write!(f, "no handles are available for inode {inode}")
  78. }
  79. Error::NoBlockPath => write!(f, "no block path was specified"),
  80. Error::InodeNotFound(inode) => write!(f, "inode {inode} could not be found"),
  81. Error::Custom(err) => err.fmt(f),
  82. }
  83. }
  84. }
  85. impl std::error::Error for Error {}
  86. impl From<std::io::Error> for Error {
  87. fn from(err: std::io::Error) -> Self {
  88. Error::Io(err)
  89. }
  90. }
  91. impl From<Error> for std::io::Error {
  92. fn from(err: Error) -> Self {
  93. io::Error::new(io::ErrorKind::Other, err)
  94. }
  95. }
  96. impl From<btserde::Error> for Error {
  97. fn from(err: btserde::Error) -> Self {
  98. Error::Serde(err)
  99. }
  100. }
  101. impl From<crypto::Error> for Error {
  102. fn from(err: crypto::Error) -> Self {
  103. Error::Crypto(err)
  104. }
  105. }
  106. impl From<std::num::TryFromIntError> for Error {
  107. fn from(err: std::num::TryFromIntError) -> Self {
  108. Error::custom(err)
  109. }
  110. }
  111. impl<T: std::fmt::Debug> From<PoisonError<T>> for Error {
  112. fn from(err: PoisonError<T>) -> Self {
  113. Error::custom(err.to_string())
  114. }
  115. }
  116. type Result<T> = std::result::Result<T, Error>;
  117. /// TODO: Remove this once the error_chain crate is integrated.
  118. trait BoxInIoErr<T> {
  119. fn box_err(self) -> std::result::Result<T, io::Error>;
  120. }
  121. impl<T, E: Into<Box<dyn Send + Sync + std::error::Error>>> BoxInIoErr<T>
  122. for std::result::Result<T, E>
  123. {
  124. fn box_err(self) -> std::result::Result<T, io::Error> {
  125. self.map_err(|err| io::Error::new(io::ErrorKind::Other, err))
  126. }
  127. }
  128. trait ToStringInIoErr<T> {
  129. fn err_to_string(self) -> std::result::Result<T, io::Error>;
  130. }
  131. impl<T, E: ToString> ToStringInIoErr<T> for std::result::Result<T, E> {
  132. fn err_to_string(self) -> std::result::Result<T, io::Error> {
  133. self.map_err(|err| io::Error::new(io::ErrorKind::Other, err.to_string()))
  134. }
  135. }
  136. /// TODO: Remove this once the error_chain crate is integrated.
  137. trait StrInIoErr<T> {
  138. fn str_err(self) -> std::result::Result<T, io::Error>;
  139. }
  140. impl<T, E: Display> StrInIoErr<T> for std::result::Result<T, E> {
  141. fn str_err(self) -> std::result::Result<T, io::Error> {
  142. self.map_err(|err| io::Error::new(io::ErrorKind::Other, err.to_string()))
  143. }
  144. }
  145. /// The default sector size to use for new blocks.
  146. const SECTOR_SZ_DEFAULT: usize = 4096;
  147. /// ### THE BLOCK TRAIT
  148. ///
  149. /// Trait for types which provide read and write access to blocks.
  150. pub trait Block: Read + Write + Seek + MetaAccess {
  151. /// Flushes metadata to persistent storage.
  152. fn flush_meta(&mut self) -> Result<()>;
  153. fn read_dir(&mut self) -> Result<Directory> {
  154. self.seek(SeekFrom::Start(0))?;
  155. // &mut &mut Self has to be passed because rustc complains that &mut Self is not sized,
  156. // for some reason (implicit dereference?). You can't pass in `&mut self` because `self`
  157. // is not declared as mutable. Hence this hack.
  158. let mut selfie = self;
  159. let dir: Directory = read_from(&mut selfie)?;
  160. Ok(dir)
  161. }
  162. fn write_dir(&mut self, dir: &Directory) -> Result<()> {
  163. self.seek(SeekFrom::Start(0))?;
  164. let mut selfie = self;
  165. write_to(dir, &mut selfie)?;
  166. selfie.flush()?;
  167. Ok(())
  168. }
  169. }
  170. impl<T: MetaAccess> MetaAccess for &mut T {}
  171. impl<T: Block> Block for &mut T {
  172. fn flush_meta(&mut self) -> Result<()> {
  173. (*self).flush_meta()
  174. }
  175. }
  176. // A trait for streams which only allow reads and writes in fixed sized units called sectors.
  177. pub trait Sectored {
  178. // Returns the size of the sector for this stream.
  179. fn sector_sz(&self) -> usize;
  180. fn assert_sector_sz(&self, actual: usize) -> Result<()> {
  181. let expected = self.sector_sz();
  182. if expected == actual {
  183. Ok(())
  184. } else {
  185. Err(Error::IncorrectSize { expected, actual })
  186. }
  187. }
  188. }
  189. /// A version of the `Write` trait, which allows integrity information to be supplied when flushing.
  190. pub trait WriteInteg: Write {
  191. fn flush_integ(&mut self, integrity: &[u8]) -> io::Result<()>;
  192. }
  193. trait Decompose<T> {
  194. fn into_inner(self) -> T;
  195. }
  196. trait TryCompose<T, U: Decompose<T>> {
  197. type Error;
  198. fn try_compose(self, inner: T) -> std::result::Result<U, Self::Error>;
  199. }
  200. trait Compose<T, U> {
  201. fn compose(self, inner: T) -> U;
  202. }
  203. impl<T, U: Decompose<T>, S: TryCompose<T, U, Error = Infallible>> Compose<T, U> for S {
  204. fn compose(self, inner: T) -> U {
  205. let result = self.try_compose(inner);
  206. // Safety: Infallible has no values, so `result` must be `Ok`.
  207. unsafe { result.unwrap_unchecked() }
  208. }
  209. }
  210. /// Trait for accessing the metadata associated with a block.
  211. pub trait MetaAccess: AsRef<BlockMeta> + AsMut<BlockMeta> {
  212. fn meta(&self) -> &BlockMeta {
  213. self.as_ref()
  214. }
  215. fn mut_meta(&mut self) -> &mut BlockMeta {
  216. self.as_mut()
  217. }
  218. fn meta_body(&self) -> &BlockMetaBody {
  219. self.meta().body()
  220. }
  221. fn mut_meta_body(&mut self) -> &mut BlockMetaBody {
  222. self.mut_meta().mut_body()
  223. }
  224. }
  225. impl AsRef<BlockMeta> for &BlockMeta {
  226. fn as_ref(&self) -> &BlockMeta {
  227. self
  228. }
  229. }
  230. impl AsRef<BlockMeta> for &mut BlockMeta {
  231. fn as_ref(&self) -> &BlockMeta {
  232. self
  233. }
  234. }
  235. impl AsMut<BlockMeta> for &mut BlockMeta {
  236. fn as_mut(&mut self) -> &mut BlockMeta {
  237. self
  238. }
  239. }
  240. impl MetaAccess for &mut BlockMeta {}
  241. /// Extensions to the `Read` trait.
  242. trait ReadExt: Read {
  243. /// Reads repeatedly until one of the following occur:
  244. /// 1. The given buffer is full.
  245. /// 2. A call to `read` returns 0.
  246. /// 3. A call to `read` returns an error.
  247. /// The number of bytes read is returned. If an error is returned, then no bytes were read.
  248. fn fill_buf(&mut self, mut dest: &mut [u8]) -> io::Result<usize> {
  249. let dest_len_start = dest.len();
  250. while !dest.is_empty() {
  251. let byte_ct = match self.read(dest) {
  252. Ok(byte_ct) => byte_ct,
  253. Err(err) => {
  254. if dest_len_start == dest.len() {
  255. return Err(err);
  256. } else {
  257. // We're not allowed to return an error since we've already read from self.
  258. error!("an error occurred in fill_buf: {}", err);
  259. break;
  260. }
  261. }
  262. };
  263. if 0 == byte_ct {
  264. break;
  265. }
  266. dest = &mut dest[byte_ct..];
  267. }
  268. Ok(dest_len_start - dest.len())
  269. }
  270. }
  271. impl<T: Read> ReadExt for T {}
  272. trait HashExt: Hashable {
  273. /// Returns the hash produced by [DefaultHasher].
  274. fn default_hash(&self) -> u64 {
  275. let mut hasher = DefaultHasher::new();
  276. self.hash(&mut hasher);
  277. hasher.finish()
  278. }
  279. }
  280. impl<T: Hashable> HashExt for T {}
  281. /// Metadata that is encrypted.
  282. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Hash)]
  283. pub struct BlockMetaSecrets {
  284. /// The inode number of the file.
  285. inode: u64,
  286. /// Mode of file.
  287. mode: u32,
  288. /// Owner UID of file.
  289. uid: u32,
  290. /// Owner GID of file.
  291. gid: u32,
  292. /// Last access time.
  293. atime: Epoch,
  294. /// Last data modification.
  295. mtime: Epoch,
  296. /// Last status change.
  297. ctime: Epoch,
  298. /// Size of the file in bytes.
  299. size: u64,
  300. /// Number of hard links to the file.
  301. nlink: u32,
  302. /// The sector size used by the block.
  303. sect_sz: u32,
  304. tags: BTreeMap<String, Vec<u8>>,
  305. }
  306. impl BlockMetaSecrets {
  307. pub fn new() -> BlockMetaSecrets {
  308. Self::default()
  309. }
  310. pub fn attr(&self) -> Attr {
  311. self.into()
  312. }
  313. pub fn stat(&self) -> stat64 {
  314. self.attr().into()
  315. }
  316. /// Returns the number of sectors occupied by the block's data.
  317. pub fn sectors(&self) -> u64 {
  318. let sect_sz = self.sect_sz as u64;
  319. if self.size % sect_sz == 0 {
  320. self.size / sect_sz
  321. } else {
  322. self.size / sect_sz + 1
  323. }
  324. }
  325. }
  326. impl Default for BlockMetaSecrets {
  327. fn default() -> Self {
  328. Self {
  329. inode: 0,
  330. mode: 0,
  331. uid: 0,
  332. gid: 0,
  333. atime: Epoch::default(),
  334. mtime: Epoch::default(),
  335. ctime: Epoch::default(),
  336. size: 0,
  337. nlink: 0,
  338. sect_sz: SECTOR_SZ_DEFAULT.try_into().unwrap(),
  339. tags: BTreeMap::new(),
  340. }
  341. }
  342. }
  343. impl From<&BlockMetaSecrets> for Attr {
  344. fn from(value: &BlockMetaSecrets) -> Self {
  345. Attr {
  346. ino: value.inode,
  347. size: value.size,
  348. atime: value.atime.value(),
  349. mtime: value.mtime.value(),
  350. ctime: value.ctime.value(),
  351. atimensec: 0,
  352. mtimensec: 0,
  353. ctimensec: 0,
  354. mode: value.mode,
  355. nlink: value.nlink,
  356. uid: value.uid,
  357. gid: value.gid,
  358. rdev: 0,
  359. blksize: value.sect_sz,
  360. blocks: value.sectors(),
  361. flags: 0,
  362. }
  363. }
  364. }
  365. /// This struct contains all of the metadata fields associated with a block, except for its
  366. /// signature. Since this struct implements `Serialize`, this allows for convenient signature
  367. /// calculations.
  368. #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
  369. pub struct BlockMetaBody {
  370. /// A copy of the block key encrypted using this block's parent's key. If this is None, then
  371. /// this block is not encrypted.
  372. inherit: Option<Ciphertext<SymKey>>,
  373. readcaps: BTreeMap<Principal, Ciphertext<SymKey>>,
  374. writecap: Option<Writecap>,
  375. /// A hash which provides integrity for the contents of the block body.
  376. integrity: Option<VarHash>,
  377. /// The public key that corresponds to the private key used to sign these metadata.
  378. signing_key: AsymKeyPub<Sign>,
  379. /// Additional metadata which is subject to confidentiality protection.
  380. secrets: Ciphertext<BlockMetaSecrets>,
  381. #[serde(skip)]
  382. /// The path in the blocktree where this block is located. This is initialized in
  383. /// BlockStream::new.
  384. path: BlockPath,
  385. #[serde(skip)]
  386. /// The cleartext block key.
  387. block_key: Option<SymKey>,
  388. #[serde(skip)]
  389. /// The clear text secret metadata.
  390. secrets_struct: Option<BlockMetaSecrets>,
  391. }
  392. impl BlockMetaBody {
  393. fn new<C: Creds>(creds: &C) -> Result<BlockMetaBody> {
  394. let block_key = SymKey::generate(SymKeyKind::default())?;
  395. let mut readcaps = BTreeMap::new();
  396. readcaps.insert(creds.principal(), creds.ser_encrypt(&block_key)?);
  397. let secrets = BlockMetaSecrets::default();
  398. Ok(BlockMetaBody {
  399. path: BlockPath::default(),
  400. inherit: None,
  401. readcaps,
  402. writecap: creds.writecap().map(|e| e.to_owned()),
  403. integrity: None,
  404. signing_key: creds.public_sign().to_owned(),
  405. secrets: block_key.ser_encrypt(&secrets)?,
  406. block_key: Some(block_key),
  407. secrets_struct: Some(secrets),
  408. })
  409. }
  410. pub fn unlock_block_key<C: Creds>(&mut self, creds: &C) -> Result<()> {
  411. if self.block_key.is_some() {
  412. return Ok(());
  413. }
  414. let readcap = self
  415. .readcaps
  416. .get(&creds.principal())
  417. .ok_or(crypto::Error::NoReadCap)?;
  418. self.block_key = Some(creds.ser_decrypt(readcap)?);
  419. Ok(())
  420. }
  421. pub fn access_secrets<T, F: FnOnce(&mut BlockMetaSecrets) -> Result<T>>(
  422. &mut self,
  423. accessor: F,
  424. ) -> Result<T> {
  425. let secrets = match self.secrets_struct.as_mut() {
  426. Some(secrets) => secrets,
  427. None => {
  428. let block_key = self.block_key()?;
  429. self.secrets_struct = Some(block_key.ser_decrypt(&self.secrets)?);
  430. self.secrets_struct.as_mut().unwrap()
  431. }
  432. };
  433. let prev = secrets.default_hash();
  434. let output = accessor(secrets)?;
  435. if prev != secrets.default_hash() {
  436. self.secrets = self
  437. .block_key
  438. .as_ref()
  439. .ok_or(Error::NoBlockKey)?
  440. .ser_encrypt(secrets)?;
  441. }
  442. Ok(output)
  443. }
  444. pub fn secrets(&self) -> Result<&BlockMetaSecrets> {
  445. self.secrets_struct
  446. .as_ref()
  447. .ok_or_else(|| Error::custom("secrets have not been decrypted"))
  448. }
  449. pub fn block_key(&self) -> Result<&SymKey> {
  450. self.block_key.as_ref().ok_or(Error::NoBlockKey)
  451. }
  452. pub fn use_block_key_for<C: Creds>(&mut self, creds: &C) -> Result<&SymKey> {
  453. let readcap = self
  454. .readcaps
  455. .get(&creds.principal())
  456. .ok_or(crypto::Error::NoReadCap)?;
  457. let block_key = creds.ser_decrypt(readcap)?;
  458. self.block_key = Some(block_key);
  459. self.block_key()
  460. }
  461. pub fn mut_block_key(&mut self) -> &mut Option<SymKey> {
  462. &mut self.block_key
  463. }
  464. pub fn integrity(&self) -> Option<&[u8]> {
  465. self.integrity.as_ref().map(|hash| hash.as_slice())
  466. }
  467. pub fn add_readcap_for<E: Encrypter>(&mut self, owner: Principal, key: &E) -> Result<()> {
  468. let block_key = self.block_key()?;
  469. self.readcaps.insert(owner, key.ser_encrypt(block_key)?);
  470. Ok(())
  471. }
  472. pub fn set_path(&mut self, path: BlockPath) {
  473. self.path = path
  474. }
  475. }
  476. /// Signed metadata associated with a block.
  477. #[derive(Debug, PartialEq, Serialize, Deserialize)]
  478. pub struct BlockMeta {
  479. body: BlockMetaBody,
  480. sig: Signature,
  481. }
  482. impl BlockMeta {
  483. fn new<C: Creds>(creds: &C) -> Result<BlockMeta> {
  484. let body = BlockMetaBody::new(creds)?;
  485. let sig = Signature::empty(body.signing_key.scheme());
  486. Ok(BlockMeta { body, sig })
  487. }
  488. pub fn body(&self) -> &BlockMetaBody {
  489. self.as_ref()
  490. }
  491. pub fn mut_body(&mut self) -> &mut BlockMetaBody {
  492. self.as_mut()
  493. }
  494. }
  495. impl AsRef<BlockMetaBody> for BlockMeta {
  496. fn as_ref(&self) -> &BlockMetaBody {
  497. &self.body
  498. }
  499. }
  500. impl AsMut<BlockMetaBody> for BlockMeta {
  501. fn as_mut(&mut self) -> &mut BlockMetaBody {
  502. &mut self.body
  503. }
  504. }
  505. struct BlockStream<T, C> {
  506. trailered: Trailered<T, BlockMeta>,
  507. meta: BlockMeta,
  508. meta_body_buf: Vec<u8>,
  509. creds: C,
  510. }
  511. impl<T: Read + Seek, C: Creds> BlockStream<T, C> {
  512. fn new(inner: T, creds: C, block_path: BlockPath) -> Result<BlockStream<T, C>> {
  513. let (trailered, meta) = Trailered::<_, BlockMeta>::new(inner)?;
  514. let meta = match meta {
  515. Some(mut meta) => {
  516. meta.assert_valid(&block_path)?;
  517. meta.body.path = block_path;
  518. // We need to use the writecap and signing_key provided by the current credentials.
  519. meta.body.writecap =
  520. Some(creds.writecap().ok_or(Error::MissingWritecap)?.to_owned());
  521. meta.body.signing_key = creds.public_sign().to_owned();
  522. meta.body.use_block_key_for(&creds)?;
  523. meta
  524. }
  525. None => {
  526. let mut meta = BlockMeta::new(&creds)?;
  527. meta.body.path = block_path;
  528. meta.body.add_readcap_for(creds.principal(), &creds)?;
  529. meta.body.writecap =
  530. Some(creds.writecap().ok_or(Error::MissingWritecap)?.to_owned());
  531. meta
  532. }
  533. };
  534. Ok(BlockStream {
  535. trailered,
  536. meta,
  537. meta_body_buf: Vec::new(),
  538. creds,
  539. })
  540. }
  541. }
  542. impl<T: Write + Seek, C: Signer> BlockStream<T, C> {
  543. fn sign_flush_meta(&mut self) -> io::Result<()> {
  544. self.meta_body_buf.clear();
  545. self.meta.sig = self
  546. .creds
  547. .ser_sign_into(&self.meta.body, &mut self.meta_body_buf)?;
  548. self.trailered.flush(&self.meta)
  549. }
  550. }
  551. impl<T: Write + Seek, C: Signer + Principaled + Decrypter> Write for BlockStream<T, C> {
  552. fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  553. self.trailered.write(buf)
  554. }
  555. fn flush(&mut self) -> io::Result<()> {
  556. Err(io::Error::new(
  557. io::ErrorKind::Unsupported,
  558. "flush is not supported, use flush_integ instead",
  559. ))
  560. }
  561. }
  562. impl<T: Write + Seek, C: Signer + Principaled + Decrypter> WriteInteg for BlockStream<T, C> {
  563. fn flush_integ(&mut self, integrity: &[u8]) -> io::Result<()> {
  564. let meta_body = &mut self.meta.body;
  565. let integ = meta_body.integrity.get_or_insert_with(VarHash::default);
  566. integ.as_mut().copy_from_slice(integrity);
  567. self.sign_flush_meta()
  568. }
  569. }
  570. impl<T: Read + Seek, C> Read for BlockStream<T, C> {
  571. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  572. self.trailered.read(buf)
  573. }
  574. }
  575. impl<T: Seek, C> Seek for BlockStream<T, C> {
  576. /// Seeks to the given position in the stream. If a position beyond the end of the stream is
  577. /// specified, the the seek will be to the end of the stream.
  578. fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
  579. self.trailered.seek(pos)
  580. }
  581. }
  582. impl<T, C> AsRef<BlockMeta> for BlockStream<T, C> {
  583. fn as_ref(&self) -> &BlockMeta {
  584. &self.meta
  585. }
  586. }
  587. impl<T, C> AsMut<BlockMeta> for BlockStream<T, C> {
  588. fn as_mut(&mut self) -> &mut BlockMeta {
  589. &mut self.meta
  590. }
  591. }
  592. impl<T, C> MetaAccess for BlockStream<T, C> {}
  593. impl<T: Read + Write + Seek, C: Creds> Block for BlockStream<T, C> {
  594. fn flush_meta(&mut self) -> Result<()> {
  595. self.sign_flush_meta().map_err(|err| err.into())
  596. }
  597. }
  598. pub struct BlockOpenOptions<T, C> {
  599. inner: T,
  600. creds: C,
  601. encrypt: bool,
  602. compress: bool,
  603. block_path: Option<BlockPath>,
  604. }
  605. impl BlockOpenOptions<(), ()> {
  606. pub fn new() -> BlockOpenOptions<(), ()> {
  607. BlockOpenOptions {
  608. inner: (),
  609. creds: (),
  610. encrypt: true,
  611. compress: true,
  612. block_path: Default::default(),
  613. }
  614. }
  615. }
  616. impl<T, C> BlockOpenOptions<T, C> {
  617. pub fn with_inner<U>(self, inner: U) -> BlockOpenOptions<U, C> {
  618. BlockOpenOptions {
  619. inner,
  620. creds: self.creds,
  621. encrypt: self.encrypt,
  622. compress: self.compress,
  623. block_path: self.block_path,
  624. }
  625. }
  626. pub fn with_creds<D>(self, creds: D) -> BlockOpenOptions<T, D> {
  627. BlockOpenOptions {
  628. inner: self.inner,
  629. creds,
  630. encrypt: self.encrypt,
  631. compress: self.compress,
  632. block_path: self.block_path,
  633. }
  634. }
  635. pub fn with_encrypt(mut self, encrypt: bool) -> Self {
  636. self.encrypt = encrypt;
  637. self
  638. }
  639. pub fn with_compress(mut self, compress: bool) -> Self {
  640. self.compress = compress;
  641. self
  642. }
  643. pub fn with_block_path(mut self, block_path: BlockPath) -> Self {
  644. self.block_path = Some(block_path);
  645. self
  646. }
  647. }
  648. impl<T: Read + Write + Seek + 'static, C: Creds + 'static> BlockOpenOptions<T, C> {
  649. pub fn open(self) -> Result<Box<dyn Block>> {
  650. let block_path = self.block_path.ok_or(Error::NoBlockPath)?;
  651. let stream = BlockStream::new(self.inner, self.creds, block_path)?;
  652. let block_key = stream.meta_body().block_key().map(|e| e.to_owned())?;
  653. let mut stream = MerkleStream::new(stream)?;
  654. stream.assert_root_integrity()?;
  655. let sect_sz = stream.sector_sz();
  656. stream.mut_meta_body().access_secrets(|secrets| {
  657. secrets.sect_sz = sect_sz.try_into()?;
  658. Ok(())
  659. })?;
  660. if self.encrypt {
  661. let stream = SecretStream::new(block_key).try_compose(stream)?;
  662. let stream = SectoredBuf::new().try_compose(stream)?;
  663. Ok(Box::new(stream))
  664. } else {
  665. let stream = SectoredBuf::new().try_compose(stream)?;
  666. Ok(Box::new(stream))
  667. }
  668. }
  669. }
  670. impl Default for BlockOpenOptions<(), ()> {
  671. fn default() -> Self {
  672. Self::new()
  673. }
  674. }
  675. impl<T: Write> Decompose<T> for CompressorWriter<T> {
  676. fn into_inner(self) -> T {
  677. self.into_inner()
  678. }
  679. }
  680. impl<T: Read> Decompose<T> for Decompressor<T> {
  681. fn into_inner(self) -> T {
  682. self.into_inner()
  683. }
  684. }
  685. #[derive(Clone)]
  686. pub struct BrotliParams {
  687. buf_sz: usize,
  688. quality: u32,
  689. window_sz: u32,
  690. }
  691. impl BrotliParams {
  692. pub fn new(buf_sz: usize, quality: u32, window_sz: u32) -> BrotliParams {
  693. BrotliParams {
  694. buf_sz,
  695. quality,
  696. window_sz,
  697. }
  698. }
  699. }
  700. impl<T: Write> TryCompose<T, CompressorWriter<T>> for BrotliParams {
  701. type Error = Error;
  702. fn try_compose(self, inner: T) -> Result<CompressorWriter<T>> {
  703. Ok(CompressorWriter::new(
  704. inner,
  705. self.buf_sz,
  706. self.quality,
  707. self.window_sz,
  708. ))
  709. }
  710. }
  711. impl<T: Read> TryCompose<T, Decompressor<T>> for BrotliParams {
  712. type Error = Error;
  713. fn try_compose(self, inner: T) -> Result<Decompressor<T>> {
  714. Ok(Decompressor::new(inner, self.buf_sz))
  715. }
  716. }
  717. /// An envelopment of a key, which is tagged with the principal who the key is meant for.
  718. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)]
  719. pub struct Readcap {
  720. /// The principal this `Readcap` was issued to.
  721. issued_to: Principal,
  722. /// An encipherment of a block key using the public key of the principal.
  723. key: Ciphertext<SymKey>,
  724. }
  725. impl Readcap {
  726. pub fn new(issued_to: VarHash, key: Ciphertext<SymKey>) -> Readcap {
  727. Readcap {
  728. issued_to: Principal(issued_to),
  729. key,
  730. }
  731. }
  732. }
  733. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
  734. pub struct WritecapBody {
  735. /// The principal this `Writecap` was issued to.
  736. issued_to: Principal,
  737. /// The path where this write caps's validity begins.
  738. path: BlockPath,
  739. /// The point in time after which this write cap is no longer valid.
  740. expires: Epoch,
  741. /// The public key used to sign this write cap.
  742. signing_key: AsymKeyPub<Sign>,
  743. }
  744. /// Verifies that a principal is authorized to write blocks in a tree.
  745. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
  746. pub struct Writecap {
  747. /// A container for the fields of this writecap which are covered by the signature.
  748. body: WritecapBody,
  749. /// A digital signature which covers all of the fields in the write cap except for next.
  750. signature: Signature,
  751. /// The next write cap in the chain leading back to the root.
  752. next: Option<Box<Writecap>>,
  753. }
  754. impl Writecap {
  755. /// Returns the root key that was used to sign this writecap.
  756. pub fn root_signing_key(&self) -> &AsymKeyPub<Sign> {
  757. let mut writecap = self;
  758. while writecap.next.is_some() {
  759. writecap = writecap.next.as_ref().unwrap();
  760. }
  761. &writecap.body.signing_key
  762. }
  763. /// Returns the principal of the root key which was used to sign this writecap.
  764. pub fn root_principal(&self) -> Principal {
  765. self.root_signing_key().principal()
  766. }
  767. /// Returns the path to the root block of the blocktree that the root principal owns.
  768. pub fn root_block_path(&self) -> BlockPath {
  769. BlockPath::new(self.root_principal(), vec![])
  770. }
  771. }
  772. /// Fragments are created from blocks using Erasure Encoding and stored with other nodes in the
  773. /// network to provide availability and redundancy of data.
  774. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
  775. pub struct Fragment {
  776. /// The path to the block this fragment is from.
  777. path: BlockPath,
  778. /// The serial number of this fragment.
  779. serial: FragmentSerial,
  780. /// The actual data.
  781. body: Vec<u8>,
  782. }
  783. impl Fragment {
  784. /// Create a new fragment with the given fields. If `path_str` cannot be parsed then a failed
  785. /// `Result` is returned containing a `PathError`.
  786. pub fn new(
  787. path_str: &str,
  788. serial_num: u32,
  789. body: Vec<u8>,
  790. ) -> std::result::Result<Fragment, BlockPathError> {
  791. let result = BlockPath::try_from(path_str);
  792. Ok(Fragment {
  793. path: result?,
  794. serial: FragmentSerial(serial_num),
  795. body,
  796. })
  797. }
  798. }
  799. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
  800. /// Structure for keeping track of block information in a directory.
  801. pub struct BlockRecord {
  802. /// The ID of the block. Note that this is only guaranteed to be unique in the directory this
  803. /// record is stored in.
  804. pub inode: u64,
  805. /// A mapping from fragment serial numbers to fragment records.
  806. /// TODO: Does this need to have a consistent order?
  807. /// TODO: Move this into the block metadata.
  808. pub frags: HashMap<FragmentSerial, FragmentRecord>,
  809. }
  810. impl BlockRecord {
  811. pub fn new(inode: u64) -> BlockRecord {
  812. BlockRecord {
  813. inode,
  814. frags: HashMap::new(),
  815. }
  816. }
  817. }
  818. #[derive(Debug, PartialEq, Serialize, Deserialize)]
  819. /// Structure for keeping track of server information in a directory.
  820. pub struct ServerRecord {
  821. /// The most up-to-date address for this server.
  822. addr: SocketAddr,
  823. /// The public credentials for this server.
  824. pub_creds: PublicCreds,
  825. }
  826. #[derive(Debug, PartialEq, Serialize, Deserialize, EnumDiscriminants)]
  827. #[strum_discriminants(derive(FromRepr, Display, Serialize, Deserialize))]
  828. #[strum_discriminants(name(DirEntryKind))]
  829. pub enum DirEntry {
  830. Directory(BlockRecord),
  831. File(BlockRecord),
  832. Server(ServerRecord),
  833. }
  834. impl DirEntry {
  835. pub fn inode(&self) -> Option<u64> {
  836. match self {
  837. Self::Directory(record) => Some(record.inode),
  838. Self::File(record) => Some(record.inode),
  839. Self::Server(..) => None,
  840. }
  841. }
  842. pub fn kind(&self) -> u8 {
  843. match self {
  844. Self::Directory(..) => libc::DT_DIR,
  845. Self::File(..) => libc::DT_REG,
  846. Self::Server(..) => libc::DT_UNKNOWN,
  847. }
  848. }
  849. }
  850. /// This is the body contained in directory blocks.
  851. #[derive(Debug, PartialEq, Serialize, Deserialize)]
  852. pub struct Directory {
  853. /// This block's descendants.
  854. entries: BTreeMap<String, DirEntry>,
  855. }
  856. impl Directory {
  857. pub fn new() -> Directory {
  858. Directory {
  859. entries: BTreeMap::new(),
  860. }
  861. }
  862. pub fn add_file(&mut self, name: String, inode: u64) -> Result<&mut BlockRecord> {
  863. let entry = match self.entries.entry(name) {
  864. btree_map::Entry::Occupied(entry) => {
  865. return Err(Error::custom(format!(
  866. "directory already contains entry '{}'",
  867. entry.key()
  868. )));
  869. }
  870. btree_map::Entry::Vacant(entry) => entry,
  871. };
  872. let dir_entry = entry.insert(DirEntry::File(BlockRecord {
  873. inode,
  874. frags: HashMap::new(),
  875. }));
  876. match dir_entry {
  877. DirEntry::File(record) => Ok(record),
  878. _ => Err(Error::custom("DirEntry was not the File variant")),
  879. }
  880. }
  881. pub fn entries(&self) -> impl Iterator<Item = (&str, &DirEntry)> {
  882. self.entries
  883. .iter()
  884. .map(|(name, entry)| (name.as_str(), entry))
  885. }
  886. }
  887. impl Default for Directory {
  888. fn default() -> Self {
  889. Self::new()
  890. }
  891. }
  892. /// Keeps track of which principal is storing a fragment.
  893. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
  894. pub struct FragmentRecord {
  895. /// The fragment serial number this record is for.
  896. serial: FragmentSerial,
  897. /// The principal who is storing this fragment.
  898. stored_by: Principal,
  899. }
  900. impl FragmentRecord {
  901. /// Creates a new `FragmentRecord` whose `serial` and `stored_by` fields are set to
  902. /// the given values.
  903. pub fn new(serial: u32, stored_by: VarHash) -> FragmentRecord {
  904. FragmentRecord {
  905. serial: FragmentSerial(serial),
  906. stored_by: Principal(stored_by),
  907. }
  908. }
  909. }
  910. /// An identifier for a security principal, which is any entity that can be authenticated.
  911. #[derive(
  912. Debug, PartialEq, Eq, Serialize, Deserialize, Hashable, Clone, Default, PartialOrd, Ord,
  913. )]
  914. pub struct Principal(VarHash);
  915. impl Principal {
  916. fn kind(&self) -> HashKind {
  917. HashKind::from(&self.0)
  918. }
  919. }
  920. impl Display for Principal {
  921. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  922. self.0.fmt(f)
  923. }
  924. }
  925. /// Trait for types which are owned by a `Principal`.
  926. pub trait Principaled {
  927. /// Returns the `Principal` that owns `self`, using the given hash algorithm.
  928. fn principal_of_kind(&self, kind: HashKind) -> Principal;
  929. /// Returns the `Principal` that owns `self`, using the default hash algorithm.
  930. fn principal(&self) -> Principal {
  931. self.principal_of_kind(HashKind::default())
  932. }
  933. }
  934. impl<T: Principaled> Principaled for &T {
  935. fn principal_of_kind(&self, kind: HashKind) -> Principal {
  936. (*self).principal_of_kind(kind)
  937. }
  938. }
  939. /// An instant in time represented by the number of seconds since January 1st 1970, 00:00:00 UTC.
  940. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
  941. pub struct Epoch(u64);
  942. impl Epoch {
  943. /// Returns the current epoch time.
  944. pub fn now() -> Epoch {
  945. let now = SystemTime::now();
  946. // If the system clock is before the unix epoch, just panic.
  947. let epoch = now.duration_since(SystemTime::UNIX_EPOCH).unwrap();
  948. Epoch(epoch.as_secs())
  949. }
  950. pub fn from_value(value: u64) -> Self {
  951. value.into()
  952. }
  953. pub fn value(self) -> u64 {
  954. self.into()
  955. }
  956. }
  957. impl Copy for Epoch {}
  958. impl From<u64> for Epoch {
  959. fn from(value: u64) -> Self {
  960. Self(value)
  961. }
  962. }
  963. impl From<Epoch> for u64 {
  964. fn from(value: Epoch) -> Self {
  965. value.0
  966. }
  967. }
  968. impl Add<Duration> for Epoch {
  969. type Output = Self;
  970. fn add(self, other: Duration) -> Self {
  971. Epoch(self.0 + other.as_secs())
  972. }
  973. }
  974. impl Sub<Duration> for Epoch {
  975. type Output = Self;
  976. fn sub(self, other: Duration) -> Self {
  977. Epoch(self.0 - other.as_secs())
  978. }
  979. }
  980. /// The serial number of a block fragment.
  981. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hashable)]
  982. pub struct FragmentSerial(u32);
  983. /// A struct which may contain a closure. When this struct is dropped, if it contains a closure
  984. /// then that closure is called. This closure can be removed by calling `disarm`.
  985. pub struct DropTrigger<F: FnOnce()>(Option<F>);
  986. impl<F: FnOnce()> DropTrigger<F> {
  987. pub fn new(trigger: F) -> DropTrigger<F> {
  988. DropTrigger(Some(trigger))
  989. }
  990. pub fn disarm(&mut self) {
  991. self.0.take();
  992. }
  993. }
  994. impl<F: FnOnce()> Drop for DropTrigger<F> {
  995. fn drop(&mut self) {
  996. if let Some(trigger) = self.0.take() {
  997. trigger()
  998. }
  999. }
  1000. }
  1001. #[cfg(test)]
  1002. mod tests {
  1003. use std::{fs::OpenOptions, io::Cursor, path::PathBuf};
  1004. use crate::crypto::{
  1005. tpm::{TpmCredStore, TpmCreds},
  1006. ConcreteCreds, CredStore, CredsPriv,
  1007. };
  1008. use super::*;
  1009. use btserde::{from_vec, to_vec};
  1010. use swtpm_harness::SwtpmHarness;
  1011. use tempdir::TempDir;
  1012. use test_helpers::*;
  1013. #[test]
  1014. fn brotli_compress_decompress() {
  1015. const SECT_SZ: usize = SECTOR_SZ_DEFAULT;
  1016. const SECT_CT: usize = 16;
  1017. let params = BrotliParams::new(SECT_SZ, 8, 20);
  1018. let mut memory = Cursor::new([0u8; SECT_SZ * SECT_CT]);
  1019. {
  1020. let write: CompressorWriter<_> = params
  1021. .clone()
  1022. .try_compose(&mut memory)
  1023. .expect("compose for write failed");
  1024. write_fill(write, SECT_SZ, SECT_CT);
  1025. }
  1026. memory.seek(SeekFrom::Start(0)).expect("seek failed");
  1027. {
  1028. let read: Decompressor<_> = params
  1029. .try_compose(&mut memory)
  1030. .expect("compose for read failed");
  1031. read_check(read, SECT_SZ, SECT_CT);
  1032. }
  1033. }
  1034. /// Tests that the `BlockMetaBody` struct has an updated secrets struct after it is modified
  1035. /// in the `access_secrets` method.
  1036. #[test]
  1037. fn block_meta_body_secrets_updated_after_access() {
  1038. const UID: u32 = 1000;
  1039. let creds = test_helpers::NODE_CREDS.clone();
  1040. let vec = {
  1041. let mut body = BlockMetaBody::new(&creds).expect("failed to create meta body");
  1042. body.access_secrets(|secrets| {
  1043. secrets.uid = UID;
  1044. Ok(())
  1045. })
  1046. .expect("access secrets failed");
  1047. to_vec(&body).expect("to_vec failed")
  1048. };
  1049. let mut body = from_vec::<BlockMetaBody>(&vec).expect("from_vec failed");
  1050. body.unlock_block_key(&creds)
  1051. .expect("unlock_block_key failed");
  1052. let actual_uid = body
  1053. .access_secrets(|secrets| Ok(secrets.uid))
  1054. .expect("access_secrets failed");
  1055. assert_eq!(UID, actual_uid);
  1056. }
  1057. struct BlockTestCase {
  1058. root_creds: TpmCreds,
  1059. node_creds: TpmCreds,
  1060. _swtpm: SwtpmHarness,
  1061. temp_dir: TempDir,
  1062. root_path: BlockPath,
  1063. node_path: BlockPath,
  1064. }
  1065. impl BlockTestCase {
  1066. const ROOT_PASSWORD: &'static str = "(1337Prestidigitation7331)";
  1067. fn new() -> BlockTestCase {
  1068. let temp_dir = TempDir::new("block_test").expect("failed to create temp dir");
  1069. let swtpm = SwtpmHarness::new().expect("failed to start swtpm");
  1070. let context = swtpm.context().expect("failed to retrieve context");
  1071. let cred_store = TpmCredStore::new(context, swtpm.state_path().to_owned())
  1072. .expect("failed to create TpmCredStore");
  1073. let root_creds = cred_store
  1074. .gen_root_creds(Self::ROOT_PASSWORD)
  1075. .expect("failed to get root creds");
  1076. let mut node_creds = cred_store.node_creds().expect("failed to get node creds");
  1077. let components = vec!["nodes".to_string(), "phone".to_string()];
  1078. let writecap = root_creds
  1079. .issue_writecap(
  1080. node_creds.principal(),
  1081. components.clone(),
  1082. Epoch::now() + Duration::from_secs(3600),
  1083. )
  1084. .expect("failed to issue writecap");
  1085. cred_store
  1086. .assign_node_writecap(&mut node_creds, writecap)
  1087. .expect("failed to assign node writecap");
  1088. let case = BlockTestCase {
  1089. temp_dir,
  1090. _swtpm: swtpm,
  1091. node_creds,
  1092. node_path: BlockPath::new(root_creds.principal(), components),
  1093. root_path: BlockPath::new(root_creds.principal(), vec![]),
  1094. root_creds,
  1095. };
  1096. std::fs::create_dir_all(case.fs_path(&case.node_path))
  1097. .expect("failed to create node path");
  1098. case
  1099. }
  1100. fn fs_path(&self, path: &crate::BlockPath) -> PathBuf {
  1101. let mut fs_path = self.temp_dir.path().to_owned();
  1102. fs_path.extend(path.components());
  1103. fs_path
  1104. }
  1105. fn open_new(&mut self, path: crate::BlockPath) -> Box<dyn Block> {
  1106. let file = OpenOptions::new()
  1107. .create_new(true)
  1108. .read(true)
  1109. .write(true)
  1110. .open(&self.fs_path(&path))
  1111. .expect("failed to open file");
  1112. let mut block = BlockOpenOptions::new()
  1113. .with_inner(file)
  1114. .with_creds(self.node_creds.clone())
  1115. .with_encrypt(true)
  1116. .with_block_path(path)
  1117. .open()
  1118. .expect("failed to open block");
  1119. block
  1120. .mut_meta_body()
  1121. .set_path(self.node_creds.writecap().unwrap().body.path.clone());
  1122. block
  1123. }
  1124. fn open_existing(&mut self, path: crate::BlockPath) -> Box<dyn Block> {
  1125. let file = OpenOptions::new()
  1126. .read(true)
  1127. .write(true)
  1128. .open(&self.fs_path(&path))
  1129. .expect("failed to reopen file");
  1130. BlockOpenOptions::new()
  1131. .with_inner(file)
  1132. .with_creds(self.node_creds.clone())
  1133. .with_encrypt(true)
  1134. .with_block_path(path)
  1135. .open()
  1136. .expect("failed to reopen block")
  1137. }
  1138. /// Returns a path in the directory which the node creds have permission to write to.
  1139. fn node_path(&self, file_name: &str) -> BlockPath {
  1140. let mut path = self.node_path.clone();
  1141. path.push_component(file_name.to_owned());
  1142. path
  1143. }
  1144. }
  1145. #[test]
  1146. fn block_can_create_empty() {
  1147. let case = BlockTestCase::new();
  1148. BlockOpenOptions::new()
  1149. .with_inner(BtCursor::new(Vec::<u8>::new()))
  1150. .with_creds(case.node_creds)
  1151. .with_encrypt(true)
  1152. .with_block_path(case.root_path)
  1153. .open()
  1154. .expect("failed to open block");
  1155. }
  1156. #[test]
  1157. fn block_contents_persisted() {
  1158. const EXPECTED: &[u8] = b"Silly sordid sulking sultans.";
  1159. let mut case = BlockTestCase::new();
  1160. let path = case.node_path("test.blk");
  1161. {
  1162. let mut block = case.open_new(path.clone());
  1163. block.write(EXPECTED).expect("failed to write");
  1164. block.flush().expect("flush failed");
  1165. }
  1166. let mut block = case.open_existing(path);
  1167. let mut actual = [0u8; EXPECTED.len()];
  1168. block.read(&mut actual).expect("read failed");
  1169. assert_eq!(EXPECTED, actual);
  1170. }
  1171. #[test]
  1172. fn block_write_twice() {
  1173. const EXPECTED: &[u8] = b"Cool callous calamitous colonels.";
  1174. const MID: usize = EXPECTED.len() / 2;
  1175. let mut case = BlockTestCase::new();
  1176. let path = case.node_path("test.blk");
  1177. {
  1178. let mut block = case.open_new(path.clone());
  1179. block.write(&EXPECTED[..MID]).expect("first write failed");
  1180. block.flush().expect("first flush failed");
  1181. }
  1182. {
  1183. let mut block = case.open_existing(path.clone());
  1184. block
  1185. .seek(SeekFrom::Start(MID.try_into().unwrap()))
  1186. .expect("seek failed");
  1187. block.write(&EXPECTED[MID..]).expect("second write failed");
  1188. block.flush().expect("second flush failed");
  1189. }
  1190. {
  1191. let mut block = case.open_existing(path);
  1192. let mut actual = [0u8; EXPECTED.len()];
  1193. block.read(&mut actual).expect("read failed");
  1194. assert_eq!(EXPECTED, actual);
  1195. }
  1196. }
  1197. #[test]
  1198. fn block_write_with_different_creds() {
  1199. const EXPECTED: &[u8] = b"Cool callous calamitous colonels.";
  1200. const MID: usize = EXPECTED.len() / 2;
  1201. let mut case = BlockTestCase::new();
  1202. let path = case.node_path("test.blk");
  1203. let app_creds = {
  1204. let mut app_creds = ConcreteCreds::generate().expect("failed to generate app creds");
  1205. let writecap = case
  1206. .root_creds
  1207. .issue_writecap(
  1208. app_creds.principal(),
  1209. path.components().map(|e| e.to_string()).collect(),
  1210. Epoch::now() + Duration::from_secs(60),
  1211. )
  1212. .expect("failed to issue writecap");
  1213. app_creds.set_writecap(writecap);
  1214. app_creds
  1215. };
  1216. {
  1217. let mut block = case.open_new(path.clone());
  1218. block
  1219. .mut_meta_body()
  1220. .add_readcap_for(app_creds.principal(), &app_creds)
  1221. .expect("failed to add readcap");
  1222. block.write(&EXPECTED[..MID]).expect("first write failed");
  1223. block.flush().expect("first flush failed");
  1224. }
  1225. {
  1226. let file = OpenOptions::new()
  1227. .read(true)
  1228. .write(true)
  1229. .open(case.fs_path(&path))
  1230. .expect("failed to reopen file");
  1231. let mut block = BlockOpenOptions::new()
  1232. .with_inner(file)
  1233. // Note that this write is performed using app_creds.
  1234. .with_creds(app_creds)
  1235. .with_encrypt(true)
  1236. .with_block_path(path.clone())
  1237. .open()
  1238. .expect("failed to reopen block");
  1239. block
  1240. .seek(SeekFrom::Start(MID.try_into().unwrap()))
  1241. .expect("seek failed");
  1242. block.write(&EXPECTED[MID..]).expect("second write failed");
  1243. block.flush().expect("second flush failed");
  1244. }
  1245. {
  1246. let file = OpenOptions::new()
  1247. .read(true)
  1248. .write(true)
  1249. .open(case.fs_path(&path))
  1250. .expect("failed to reopen file");
  1251. let mut block = BlockOpenOptions::new()
  1252. .with_inner(file)
  1253. .with_creds(case.node_creds)
  1254. .with_encrypt(true)
  1255. .with_block_path(path)
  1256. .open()
  1257. .expect("failed to reopen block");
  1258. let mut actual = [0u8; EXPECTED.len()];
  1259. block.read(&mut actual).expect("read failed");
  1260. assert_eq!(EXPECTED, actual);
  1261. }
  1262. }
  1263. }