-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunsafe_obj.rs
More file actions
143 lines (131 loc) · 4.86 KB
/
Copy pathunsafe_obj.rs
File metadata and controls
143 lines (131 loc) · 4.86 KB
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
//! Helpers for reaching into `sia_storage`'s private flow.
//!
//! - [`extract_data_key`] pulls the raw object data key out of an [`Object`]
//! via the `share_object` URL fragment, since `sia_storage` exposes no
//! public accessor.
//! - [`unsafe_object`] reconstructs an [`Object`] from a known data key + slab
//! list by sealing under the caller's app key and re-opening it. Used on the
//! download side, where the data key flowed in via the IPFS descriptor and
//! the slab placements come from the bridge.
//!
//! Both are demo workarounds; replace once `sia_storage` exposes the
//! corresponding public surface.
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE;
use chacha20poly1305::aead::{Aead, OsRng};
use chacha20poly1305::{AeadCore, KeyInit, XChaCha20Poly1305};
use sia_core::blake2::{Blake2b256, Digest};
use sia_core::encoding::SiaEncodable;
use sia_core::signing::PrivateKey;
use sia_storage::{AppKey, DateTime, EncryptionKey, Hash256, Object, Sdk, SealedObject, Slab, Utc};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum DataKeyError {
#[error("share_object failed: {0}")]
Share(String),
#[error("share URL is missing the encryption_key fragment")]
MissingFragment,
#[error("base64 decode failed: {0}")]
Base64(#[from] base64::DecodeError),
#[error("decoded encryption key has wrong length")]
InvalidKey,
}
/// Extracts the plaintext data key from `object` by parsing the SDK's share
/// URL fragment.
pub fn extract_data_key(sdk: &Sdk, object: &Object) -> Result<[u8; 32], DataKeyError> {
let url = sdk
.share_object(object, DateTime::<Utc>::MAX_UTC)
.map_err(|e| DataKeyError::Share(format!("{e:?}")))?;
let encoded = url
.fragment()
.and_then(|f| f.strip_prefix("encryption_key="))
.ok_or(DataKeyError::MissingFragment)?;
let bytes = URL_SAFE.decode(encoded)?;
bytes.try_into().map_err(|_| DataKeyError::InvalidKey)
}
#[derive(Debug, Error)]
pub enum UnsafeObjectError {
#[error("seal/open round trip failed: {0}")]
Open(String),
}
/// Reconstructs a [`sia_storage::Object`] from a data key + slab list. Seals
/// under `app_key` and immediately re-opens — yields an `Object` that
/// `Sdk::download` can stream.
pub fn unsafe_object(
app_key: &AppKey,
data_key: [u8; 32],
slabs: Vec<Slab>,
) -> Result<Object, UnsafeObjectError> {
let pk = PrivateKey::from_seed(&app_key.export());
let object_id = compute_object_id(&slabs);
let dk = EncryptionKey::from(data_key);
let encrypted_data_key = seal_data_key(&pk, &object_id, &dk);
let data_signature = {
let sig_hash = data_sig_hash(&object_id, &encrypted_data_key);
app_key.sign(sig_hash.as_ref())
};
let metadata_signature = {
let sig_hash = meta_sig_hash(&object_id, &[], &[]);
app_key.sign(sig_hash.as_ref())
};
let now = Utc::now();
let so = SealedObject {
encrypted_data_key,
slabs,
encrypted_metadata: Vec::new(),
encrypted_metadata_key: Vec::new(),
data_signature,
metadata_signature,
created_at: now,
updated_at: now,
};
so.open(app_key)
.map_err(|e| UnsafeObjectError::Open(format!("{e:?}")))
}
fn derive_encryption_key(key: &[u8], salt: &[u8], domain: &[u8]) -> EncryptionKey {
let hkdf = hkdf::SimpleHkdf::<Blake2b256>::new(Some(salt), key);
let mut okm = [0u8; 32];
hkdf.expand(domain, &mut okm).unwrap();
okm.into()
}
fn seal_data_key(
app_key: &PrivateKey,
object_id: &Hash256,
encryption_key: &EncryptionKey,
) -> Vec<u8> {
let derived = derive_encryption_key(app_key.as_ref(), object_id.as_ref(), b"dataKey");
let cipher = XChaCha20Poly1305::new(derived.as_ref().into());
let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
let ct = cipher
.encrypt(&nonce, encryption_key.as_ref().as_ref())
.expect("xchacha20poly1305 encrypt");
[nonce.to_vec(), ct].concat()
}
fn compute_object_id(slabs: &[Slab]) -> Hash256 {
let mut state = Blake2b256::default();
for slab in slabs.iter() {
slab.digest()
.encode(&mut state)
.expect("hashing slab digest");
let combined: u64 = ((slab.offset as u64) << 32) | (slab.length as u64);
combined.encode(&mut state).expect("hashing offset|length");
}
state.finalize().into()
}
fn data_sig_hash(object_id: &Hash256, encrypted_data_key: &[u8]) -> Hash256 {
let mut state = Blake2b256::default();
object_id.encode(&mut state).unwrap();
state.update(encrypted_data_key);
state.finalize().into()
}
fn meta_sig_hash(
object_id: &Hash256,
encrypted_meta_key: &[u8],
encrypted_metadata: &[u8],
) -> Hash256 {
let mut state = Blake2b256::default();
object_id.encode(&mut state).unwrap();
state.update(encrypted_meta_key);
state.update(encrypted_metadata);
state.finalize().into()
}