use std::fmt;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::codes::Code;
use crate::error::{Error, Fault};
use crate::host;
const UPLOAD_EXTERNAL: &str = "action:storage/upload-external";
const STAT: &str = "action:storage/stat";
const READ: &str = "action:storage/read";
pub const MAX_RANGE_BYTES: u64 = 16 * 1024 * 1024;
const MAX_EXACT_SIZE: u64 = 1 << 53;
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct DocumentHandle {
pub file_hash: String,
pub filename: String,
pub mime_type: String,
pub size: u64,
pub storage_path: String,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct Target {
pub app_id: String,
pub table_name: String,
pub field_name: String,
}
impl Target {
pub fn new(
app_id: impl Into<String>,
table_name: impl Into<String>,
field_name: impl Into<String>,
) -> Target {
Target {
app_id: app_id.into(),
table_name: table_name.into(),
field_name: field_name.into(),
}
}
}
#[non_exhaustive]
#[derive(Clone, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Auth {
Basic {
username: String,
password: String,
},
Bearer {
bearer_token: String,
},
}
impl Auth {
pub fn bearer(bearer_token: impl Into<String>) -> Auth {
Auth::Bearer {
bearer_token: bearer_token.into(),
}
}
pub fn basic(username: impl Into<String>, password: impl Into<String>) -> Auth {
Auth::Basic {
username: username.into(),
password: password.into(),
}
}
}
impl fmt::Debug for Auth {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Auth::Basic { username, .. } => formatter
.debug_struct("Basic")
.field("username", username)
.finish_non_exhaustive(),
Auth::Bearer { .. } => formatter.debug_struct("Bearer").finish_non_exhaustive(),
}
}
}
#[derive(Clone, Debug, Serialize)]
pub struct Source {
pub url: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub auth: Option<Auth>,
}
impl Source {
pub fn url(url: impl Into<String>) -> Source {
Source {
url: url.into(),
auth: None,
}
}
pub fn with_auth(mut self, auth: Auth) -> Source {
self.auth = Some(auth);
self
}
}
pub fn upload_buffer(
bytes: &[u8],
filename: &str,
mime_type: &str,
target: Target,
) -> Result<DocumentHandle, Error> {
if bytes.is_empty() {
return Err(
Error::invalid("An upload needs at least one byte, and this buffer is empty.")
.hint("Pass the file's contents."),
);
}
if filename.trim().is_empty() {
return Err(Error::invalid("An upload needs a filename.")
.hint("Pass the name the file is stored under, such as report.pdf."));
}
if mime_type.trim().is_empty() {
return Err(Error::invalid("An upload needs a media type.")
.hint("Pass the type of the contents, such as application/pdf."));
}
check_target(&target)?;
let source = json!({
"bytes": encode(bytes),
"filename": filename,
"mime_type": mime_type,
});
send(source, target)
}
pub fn upload_external(source: Source, target: Target) -> Result<DocumentHandle, Error> {
if source.url.trim().is_empty() {
return Err(
Error::invalid("An external upload needs a URL to read from.")
.hint("Pass the address of the file, or use upload_buffer for bytes you hold."),
);
}
if let Some(auth) = &source.auth {
check_auth(auth)?;
}
check_target(&target)?;
send(serde_json::to_value(&source)?, target)
}
fn send(source: Value, target: Target) -> Result<DocumentHandle, Error> {
let params = json!({ "source": source, "target": serde_json::to_value(&target)? });
let stored = host::transport()?
.call(UPLOAD_EXTERNAL.to_string(), params)
.map_err(|cause| {
Error::Host(Fault::new(Code::unspecified(), cause.message())).hint(
"Nothing was attached to the record. The store is addressed by content, \
so the same bytes uploaded again answer with the same handle.",
)
})?;
serde_json::from_value(stored).map_err(|cause| {
Error::Json(Fault::new(
Code::unspecified(),
format!("The upload finished and its handle could not be read: {cause}"),
))
.hint(
"Report this. The file is stored under the hash of its contents, \
so uploading the same bytes again answers with the handle.",
)
})
}
pub fn size(handle: &DocumentHandle) -> Result<u64, Error> {
check_handle(handle)?;
let answer = host::transport()?.call(STAT.to_string(), json!({ "handle": handle }))?;
answer
.get("size")
.and_then(Value::as_u64)
.filter(|size| *size < MAX_EXACT_SIZE)
.ok_or_else(|| {
Error::Host(Fault::new(
Code::unspecified(),
format!("{STAT} answered without a size: {answer}"),
))
})
}
pub fn read(handle: &DocumentHandle) -> Result<Vec<u8>, Error> {
let total = size(handle)?;
read_span(handle, 0, total)
}
pub fn read_range(handle: &DocumentHandle, offset: u64, length: u64) -> Result<Vec<u8>, Error> {
check_handle(handle)?;
if length == 0 {
return Err(Error::invalid("A range needs at least one byte.")
.hint("Pass a length of one or more, or ask size() how large the file is."));
}
let total = size(handle)?;
if offset >= total {
return Err(past_end(offset, total));
}
read_span(handle, offset, length.min(total - offset))
}
fn read_span(handle: &DocumentHandle, offset: u64, length: u64) -> Result<Vec<u8>, Error> {
let mut bytes = Vec::new();
let capacity = usize::try_from(length).map_err(|_too_large| too_large(length))?;
bytes
.try_reserve_exact(capacity)
.map_err(|_no_memory| too_large(length))?;
let transport = host::transport()?;
let mut done = 0;
while done < length {
let wanted = MAX_RANGE_BYTES.min(length - done);
let appended = transport.call_bytes(
READ.to_string(),
range(handle, offset + done, wanted),
&mut bytes,
)?;
if appended as u64 != wanted {
return Err(short(offset + done, wanted, appended));
}
done += wanted;
}
Ok(bytes)
}
fn range(handle: &DocumentHandle, offset: u64, length: u64) -> Value {
json!({ "handle": handle, "offset": offset, "length": length })
}
fn too_large(length: u64) -> Error {
Error::failed(format!(
"Reading {length} bytes needs more memory than this action has."
))
.hint("Raise the action's mem_limit, or read the file in parts with read_range.")
}
fn past_end(offset: u64, total: u64) -> Error {
Error::invalid(format!(
"The range starts at byte {offset}, at or past the end of the file, which is {total} bytes."
))
.hint("Ask size() how large the file is, and start the range before its end.")
}
fn short(offset: u64, length: u64, appended: usize) -> Error {
Error::Host(Fault::new(
Code::unspecified(),
format!(
"The file answered {appended} bytes for the {length} at offset {offset}, \
so it is not the size it was when the read began."
),
))
.hint("Read it again.")
}
fn check_handle(handle: &DocumentHandle) -> Result<(), Error> {
let named = [
("storage_path", &handle.storage_path),
("filename", &handle.filename),
("file_hash", &handle.file_hash),
];
for (member, value) in named {
if value.trim().is_empty() {
return Err(Error::invalid(format!("A document handle needs {member}."))
.hint("Pass the handle exactly as the :document field holds it."));
}
}
Ok(())
}
fn check_target(target: &Target) -> Result<(), Error> {
let named = [
("app_id", &target.app_id),
("table_name", &target.table_name),
("field_name", &target.field_name),
];
for (member, value) in named {
if value.trim().is_empty() {
return Err(Error::invalid(format!("A storage target needs {member}."))
.hint("Name the app, the table, and the :document field the handle goes in."));
}
}
Ok(())
}
fn check_auth(auth: &Auth) -> Result<(), Error> {
match auth {
Auth::Basic { username, password } => {
if username.trim().is_empty() {
return Err(Error::invalid("Basic authentication needs a username.")
.hint("Pass the username, or read the URL without a credential."));
}
if password.trim().is_empty() {
return Err(Error::invalid("Basic authentication needs a password.")
.hint("Pass the password, or read the URL without a credential."));
}
}
Auth::Bearer { bearer_token } => {
if bearer_token.trim().is_empty() {
return Err(Error::invalid("Bearer authentication needs a token.")
.hint("Pass the token, or read the URL without a credential."));
}
}
}
Ok(())
}
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const PAD: char = '=';
fn encode(bytes: &[u8]) -> String {
let mut encoded = String::with_capacity(bytes.len().div_ceil(3) * 4);
for group in bytes.chunks(3) {
let mut packed = 0_u32;
for (index, byte) in group.iter().enumerate() {
packed |= u32::from(*byte) << (16 - 8 * index);
}
encoded.push(symbol(packed >> 18));
encoded.push(symbol(packed >> 12));
encoded.push(if group.len() > 1 {
symbol(packed >> 6)
} else {
PAD
});
encoded.push(if group.len() > 2 { symbol(packed) } else { PAD });
}
encoded
}
fn symbol(packed: u32) -> char {
char::from(ALPHABET[(packed & 0b11_1111) as usize])
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::testing;
fn stored() -> Value {
json!({
"file_hash": "c3ab8ff13720e8ad9047dd39466b3c89",
"filename": "report.pdf",
"mime_type": "application/pdf",
"size": 6,
"storage_path": "documents/c3/ab/c3ab8ff13720e8ad9047dd39466b3c89",
})
}
fn target() -> Target {
Target::new("dev.simple.system", "documents", "attachment")
}
fn handle() -> DocumentHandle {
DocumentHandle {
file_hash: "9f86d081884c7d65".to_string(),
filename: "statement.pdf".to_string(),
mime_type: "application/pdf".to_string(),
size: 0,
storage_path: "_staged/9f86d081884c7d65".to_string(),
}
}
fn every_byte(count: usize) -> Vec<u8> {
(0..count).map(|i| ((i * 7 + 3) % 256) as u8).collect()
}
fn serving(file: Vec<u8>) -> testing::Session {
let size = file.len();
testing::install(move |name, _params| {
assert_eq!(name, "action:storage/stat");
Ok(json!({ "size": size }))
})
.with_bytes(move |name, params| {
assert_eq!(name, "action:storage/read");
let offset = params["offset"].as_u64().unwrap() as usize;
let length = params["length"].as_u64().unwrap() as usize;
if offset >= file.len() {
return Err(Error::invalid(
"'offset' is at or past the end of the file.",
));
}
Ok(file[offset..file.len().min(offset + length)].to_vec())
})
}
#[test]
fn a_read_answers_the_file_byte_for_byte() {
let file = every_byte(5_000);
let _session = serving(file.clone());
assert_eq!(read(&handle()).unwrap(), file);
}
#[test]
fn a_read_allocates_once_at_exactly_the_size_the_store_reports() {
let file = every_byte(40 * 1024 * 1024 + 17);
let _session = serving(file.clone());
let bytes = read(&handle()).unwrap();
assert_eq!(bytes.len(), file.len());
assert_eq!(bytes.capacity(), file.len());
assert!(bytes == file);
}
#[test]
fn a_large_read_asks_for_ranges_no_longer_than_the_host_answers() {
let file = every_byte(40 * 1024 * 1024 + 17);
let session = serving(file);
read(&handle()).unwrap();
let ranges: Vec<(u64, u64)> = session
.calls()
.iter()
.filter(|call| call.name == "action:storage/read")
.map(|call| {
(
call.params["offset"].as_u64().unwrap(),
call.params["length"].as_u64().unwrap(),
)
})
.collect();
let mib = 1024 * 1024;
assert_eq!(
ranges,
vec![
(0, 16 * mib),
(16 * mib, 16 * mib),
(32 * mib, 8 * mib + 17)
]
);
}
#[test]
fn every_read_carries_the_handle_it_was_given() {
let session = serving(every_byte(10));
read(&handle()).unwrap();
for call in session.calls() {
assert_eq!(
call.params["handle"],
serde_json::to_value(handle()).unwrap()
);
}
}
#[test]
fn an_empty_file_is_read_without_asking_for_a_range() {
let session = serving(Vec::new());
assert_eq!(read(&handle()).unwrap(), Vec::<u8>::new());
assert_eq!(session.calls().len(), 1);
}
#[test]
fn a_range_answered_short_is_refused_rather_than_handed_over() {
let _session = testing::install(|_name, _params| Ok(json!({ "size": 100 })))
.with_bytes(|_name, _params| Ok(vec![0; 60]));
let error = read(&handle()).unwrap_err();
assert!(error.message().contains("60 bytes for the 100 at offset 0"));
}
#[test]
fn a_host_refusal_reaches_the_caller_with_its_own_message() {
let _session = testing::install(|_name, _params| Ok(json!({ "size": 10 }))).with_bytes(
|_name, _params| Err(Error::invalid("No stored file matches this handle.")),
);
let error = read(&handle()).unwrap_err();
assert!(error
.message()
.contains("action:storage/read failed: No stored file matches this handle."));
}
#[test]
fn a_file_larger_than_this_action_can_hold_is_refused_before_any_range() {
let largest = MAX_EXACT_SIZE - 1;
let session = testing::install(move |_name, _params| Ok(json!({ "size": largest })));
let error = read(&handle()).unwrap_err();
assert_eq!(
error.message(),
format!("Reading {largest} bytes needs more memory than this action has.")
);
assert_eq!(session.calls().len(), 1);
let error = read_range(&handle(), 0, largest).unwrap_err();
assert!(error
.message()
.contains("needs more memory than this action has"));
assert_eq!(
session.calls().len(),
2,
"one size lookup each, and no range"
);
}
#[test]
fn size_answers_what_the_store_reports() {
let _session = testing::install(|_name, _params| Ok(json!({ "size": 81_920 })));
assert_eq!(size(&handle()).unwrap(), 81_920);
}
#[test]
fn a_size_that_is_not_a_count_every_sdk_holds_exactly_is_refused() {
for answer in [
json!({}),
json!({ "size": -1 }),
json!({ "size": 1.5 }),
json!({ "size": "10" }),
json!({ "size": MAX_EXACT_SIZE }),
json!("10"),
] {
let reply = answer.clone();
let _session = testing::install(move |_name, _params| Ok(reply.clone()));
let error = size(&handle()).unwrap_err();
assert_eq!(
error.message(),
format!("action:storage/stat answered without a size: {answer}")
);
}
}
#[test]
fn a_size_refusal_keeps_the_hosts_own_message() {
let _session = testing::install(|_name, _params| {
Err(Error::invalid("No stored file matches this handle."))
});
let error = size(&handle()).unwrap_err();
assert_eq!(
error.message(),
"action:storage/stat failed: No stored file matches this handle."
);
}
#[test]
fn a_range_answers_exactly_that_range_after_asking_for_the_size() {
let file = every_byte(10_000);
let session = serving(file.clone());
assert_eq!(
read_range(&handle(), 4_000, 1_500).unwrap(),
file[4_000..5_500]
);
let names: Vec<String> = session.calls().into_iter().map(|call| call.name).collect();
assert_eq!(names, ["action:storage/stat", "action:storage/read"]);
}
#[test]
fn a_range_running_past_the_end_answers_up_to_the_end() {
let file = every_byte(10_000);
let _session = serving(file.clone());
assert_eq!(read_range(&handle(), 9_990, 100).unwrap(), file[9_990..]);
}
#[test]
fn a_range_starting_at_or_past_the_end_is_refused_before_any_range() {
for offset in [10, 11, 20] {
let session = serving(every_byte(10));
let error = read_range(&handle(), offset, 1).unwrap_err();
assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
assert_eq!(
error.message(),
format!(
"The range starts at byte {offset}, at or past the end of the file, which is 10 bytes."
)
);
assert_eq!(
error.fault().hint(),
"Ask size() how large the file is, and start the range before its end."
);
assert!(ranges(&session).is_empty());
}
}
fn ranges(session: &testing::Session) -> Vec<(u64, u64)> {
session
.calls()
.iter()
.filter(|call| call.name == "action:storage/read")
.map(|call| {
(
call.params["offset"].as_u64().unwrap(),
call.params["length"].as_u64().unwrap(),
)
})
.collect()
}
type Case = (u64, u64, u64, Vec<(u64, u64)>);
#[test]
fn a_range_is_held_at_what_the_file_has_at_every_boundary() {
let mib: u64 = 1024 * 1024;
let largest = every_byte(32 * 1024 * 1024 + 5);
let cases: Vec<Case> = vec![
(16 * mib, 0, 16 * mib, vec![(0, 16 * mib)]),
(16 * mib, 0, 16 * mib + 1, vec![(0, 16 * mib)]),
(
16 * mib + 1,
0,
16 * mib + 1,
vec![(0, 16 * mib), (16 * mib, 1)],
),
(
32 * mib + 5,
0,
32 * mib + 5,
vec![(0, 16 * mib), (16 * mib, 16 * mib), (32 * mib, 5)],
),
(
32 * mib + 5,
0,
48 * mib,
vec![(0, 16 * mib), (16 * mib, 16 * mib), (32 * mib, 5)],
),
(
32 * mib + 5,
16 * mib,
16 * mib + 1,
vec![(16 * mib, 16 * mib), (32 * mib, 1)],
),
(32 * mib, 16 * mib, 16 * mib + 1, vec![(16 * mib, 16 * mib)]),
(10, 9, 5, vec![(9, 1)]),
];
for (size, offset, length, asked) in cases {
let file = largest[..size as usize].to_vec();
let session = serving(file.clone());
let bytes = read_range(&handle(), offset, length).unwrap();
let end = size.min(offset + length) as usize;
assert_eq!(
bytes.len(),
end - offset as usize,
"{size} {offset} {length}"
);
assert_eq!(bytes.capacity(), bytes.len(), "{size} {offset} {length}");
assert!(
bytes == file[offset as usize..end],
"{size} {offset} {length}"
);
assert_eq!(ranges(&session), asked, "{size} {offset} {length}");
assert_eq!(session.calls()[0].name, "action:storage/stat");
}
for (size, offset, length) in [
(0, 0, 1),
(10, 10, 1),
(10, 11, 1),
(10, 20, 32 * mib),
(16 * mib, 16 * mib, 16 * mib + 1),
] {
let session = serving(largest[..size as usize].to_vec());
let error = read_range(&handle(), offset, length).unwrap_err();
assert!(
error.message().contains(&format!(
"at or past the end of the file, which is {size} bytes"
)),
"{size} {offset} {length}: {}",
error.message()
);
assert!(ranges(&session).is_empty(), "{size} {offset} {length}");
}
for size in [0, 16 * mib, 16 * mib + 1, 32 * mib + 5] {
let file = largest[..size as usize].to_vec();
let _session = serving(file.clone());
assert!(read(&handle()).unwrap() == file, "{size}");
}
}
#[test]
fn a_host_that_cannot_read_stored_files_refuses_before_any_range() {
let session = testing::install(|name, _params| {
Err(Error::invalid(format!("Unknown request: {name}")))
})
.with_bytes(|_name, _params| {
Ok(
br#"{"ok":false,"error":{"message":"Unknown request: action:storage/read"}}"#
.to_vec(),
)
});
for error in [
read_range(&handle(), 0, 64).unwrap_err(),
read_range(&handle(), 0, 32 * 1024 * 1024).unwrap_err(),
read(&handle()).unwrap_err(),
] {
assert_eq!(
error.message(),
"action:storage/stat failed: Unknown request: action:storage/stat"
);
}
assert!(ranges(&session).is_empty());
}
#[test]
fn an_empty_range_is_refused_before_anything_is_sent() {
let session = serving(every_byte(10));
assert!(read_range(&handle(), 0, 0).is_err());
assert!(session.calls().is_empty());
}
#[test]
fn a_handle_missing_what_names_the_file_is_refused_before_anything_is_sent() {
let session = serving(every_byte(10));
for broken in [
DocumentHandle {
storage_path: String::new(),
..handle()
},
DocumentHandle {
filename: " ".to_string(),
..handle()
},
DocumentHandle {
file_hash: String::new(),
..handle()
},
] {
assert_eq!(
read(&broken).unwrap_err().code().as_str(),
"INVALID_TOOL_INPUT"
);
}
assert!(session.calls().is_empty());
}
#[test]
fn a_session_with_no_bytes_reply_says_how_to_give_it_one() {
let _session = testing::install(|_name, _params| Ok(json!({ "size": 10 })));
let error = read(&handle()).unwrap_err();
assert!(error.message().contains("was given no way to"));
}
#[test]
fn a_buffer_travels_base64_encoded_beside_its_name_and_type() {
let session = testing::install(|_name, _params| Ok(stored()));
upload_buffer(b"foobar", "report.pdf", "application/pdf", target()).unwrap();
let calls = session.calls();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].name, "action:storage/upload-external");
assert_eq!(
calls[0].params["source"],
json!({
"bytes": "Zm9vYmFy",
"filename": "report.pdf",
"mime_type": "application/pdf",
})
);
assert_eq!(
calls[0].params["target"],
json!({
"app_id": "dev.simple.system",
"table_name": "documents",
"field_name": "attachment",
})
);
}
#[test]
fn a_stored_file_answers_with_every_member_of_its_handle() {
let _session = testing::install(|_name, _params| Ok(stored()));
let handle = upload_buffer(b"foobar", "report.pdf", "application/pdf", target()).unwrap();
assert_eq!(
handle,
DocumentHandle {
file_hash: "c3ab8ff13720e8ad9047dd39466b3c89".to_string(),
filename: "report.pdf".to_string(),
mime_type: "application/pdf".to_string(),
size: 6,
storage_path: "documents/c3/ab/c3ab8ff13720e8ad9047dd39466b3c89".to_string(),
}
);
}
#[test]
fn an_empty_buffer_is_refused_before_anything_is_sent() {
let session = testing::install(|_name, _params| Ok(stored()));
let error = upload_buffer(&[], "report.pdf", "application/pdf", target()).unwrap_err();
assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
assert!(session.calls().is_empty());
}
#[test]
fn a_blank_name_or_type_is_refused_before_anything_is_sent() {
let session = testing::install(|_name, _params| Ok(stored()));
for (filename, mime_type) in [(" ", "application/pdf"), ("report.pdf", "")] {
let error = upload_buffer(b"foobar", filename, mime_type, target()).unwrap_err();
assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
}
assert!(session.calls().is_empty());
}
#[test]
fn a_target_missing_a_member_names_the_one_it_is_missing() {
let session = testing::install(|_name, _params| Ok(stored()));
let incomplete = [
(Target::new("", "documents", "attachment"), "app_id"),
(
Target::new("dev.simple.system", " ", "attachment"),
"table_name",
),
(
Target::new("dev.simple.system", "documents", ""),
"field_name",
),
];
for (target, member) in incomplete {
let error = upload_buffer(b"foobar", "report.pdf", "application/pdf", target)
.expect_err("an incomplete target names nothing to attach to");
assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
assert!(error.message().contains(member), "{}", error.message());
}
assert!(session.calls().is_empty());
}
#[test]
fn a_url_upload_carries_the_url_alone_when_it_needs_no_credential() {
let session = testing::install(|_name, _params| Ok(stored()));
upload_external(Source::url("https://example.com/report.pdf"), target()).unwrap();
assert_eq!(
session.calls()[0].params["source"],
json!({ "url": "https://example.com/report.pdf" }),
"a source with no credential carries no auth member"
);
}
#[test]
fn a_credential_travels_under_its_own_scheme() {
let session = testing::install(|_name, _params| Ok(stored()));
upload_external(
Source::url("https://example.com/report.pdf").with_auth(Auth::bearer("t-1234")),
target(),
)
.unwrap();
upload_external(
Source::url("https://example.com/report.pdf").with_auth(Auth::basic("ada", "s3cret")),
target(),
)
.unwrap();
let calls = session.calls();
assert_eq!(
calls[0].params["source"]["auth"],
json!({ "type": "bearer", "bearer_token": "t-1234" })
);
assert_eq!(
calls[1].params["source"]["auth"],
json!({ "type": "basic", "username": "ada", "password": "s3cret" })
);
}
#[test]
fn a_blank_url_is_refused_before_anything_is_sent() {
let session = testing::install(|_name, _params| Ok(stored()));
let error = upload_external(Source::url(" "), target()).unwrap_err();
assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
assert!(session.calls().is_empty());
}
#[test]
fn a_credential_with_nothing_in_it_is_refused_before_anything_is_sent() {
let session = testing::install(|_name, _params| Ok(stored()));
let blank = [
Auth::bearer(" "),
Auth::basic("", "s3cret"),
Auth::basic("ada", " "),
];
for auth in blank {
let error = upload_external(
Source::url("https://example.com/report.pdf").with_auth(auth),
target(),
)
.expect_err("a credential that says nothing cannot read the URL");
assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
}
assert!(session.calls().is_empty());
}
#[test]
fn a_refused_upload_keeps_the_hosts_own_message() {
let _session = testing::install(|_name, _params| Err(Error::failed("the store is full")));
let error =
upload_buffer(b"foobar", "report.pdf", "application/pdf", target()).unwrap_err();
assert!(matches!(error, Error::Host(_)));
assert!(error.message().contains("the store is full"));
assert!(!error.is_retryable());
}
#[test]
fn a_handle_that_cannot_be_read_is_reported_rather_than_returned() {
let _session = testing::install(|_name, _params| Ok(json!({ "filename": "report.pdf" })));
let error =
upload_buffer(b"foobar", "report.pdf", "application/pdf", target()).unwrap_err();
assert!(matches!(error, Error::Json(_)));
assert!(error.message().contains("could not be read"));
}
#[test]
fn an_upload_with_no_host_to_send_it_to_says_so() {
let error =
upload_buffer(b"foobar", "report.pdf", "application/pdf", target()).unwrap_err();
assert!(error.message().contains("No host is installed"));
}
#[test]
fn bytes_encode_to_the_standard_alphabet_with_standard_padding() {
assert_eq!(encode(b""), "");
assert_eq!(encode(b"f"), "Zg==");
assert_eq!(encode(b"fo"), "Zm8=");
assert_eq!(encode(b"foo"), "Zm9v");
assert_eq!(encode(b"foob"), "Zm9vYg==");
assert_eq!(encode(b"fooba"), "Zm9vYmE=");
assert_eq!(encode(b"foobar"), "Zm9vYmFy");
}
#[test]
fn the_last_two_symbols_of_the_alphabet_are_plus_and_slash() {
assert_eq!(encode(&[0xfb, 0xff]), "+/8=");
assert_eq!(encode(&[0xff, 0xff, 0xff]), "////");
assert_eq!(encode(&[0x00, 0x00, 0x00]), "AAAA");
}
#[test]
fn every_byte_value_survives_the_encoding() {
let every: Vec<u8> = (0..=255).collect();
let encoded = encode(&every);
assert_eq!(encoded.len(), 344, "256 bytes fill 86 groups of four");
assert!(encoded.ends_with("/w=="));
assert!(encoded
.chars()
.all(|symbol| symbol == PAD || ALPHABET.contains(&(symbol as u8))));
}
#[test]
fn a_credential_is_not_written_out_by_a_debug_rendering() {
let source =
Source::url("https://example.com/report.pdf").with_auth(Auth::bearer("t-1234"));
let rendered = format!("{source:?}");
assert!(!rendered.contains("t-1234"));
assert!(rendered.contains("Bearer"));
let basic = format!("{:?}", Auth::basic("ada", "s3cret"));
assert!(!basic.contains("s3cret"));
assert!(basic.contains("ada"));
}
}