use std::time::Duration;
use serde::{Deserialize, Serialize};
use crate::{AttemptId, ContentDigest, Error, RequestId, Result, encoding, path::is_absolute};
pub const MAX_ACTIVE: usize = 2;
pub const DEADLINE: Duration = Duration::from_secs(300);
pub const MAX_HISTORY: usize = 256;
pub const MAX_PATH: usize = crate::path::MAX_BYTES;
pub const MAX_ENTRIES: usize = 4096;
pub const MAX_BYTES: u64 = 256 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
pub version: u32,
pub attempt_id: AttemptId,
pub request_id: RequestId,
pub action: Action,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Action {
Download {
#[serde(with = "encoding")]
path: Vec<u8>,
},
Upload {
#[serde(with = "encoding")]
path: Vec<u8>,
identity: ContentDigest,
durable: bool,
},
}
impl Action {
pub fn path(&self) -> &[u8] {
match self {
Self::Download { path } | Self::Upload { path, .. } => path,
}
}
pub fn validate(&self) -> Result<()> {
let path = self.path();
if !is_absolute(path) || path.split(|byte| *byte == b'/').any(|part| part == b"..") {
return Err(Error::Invalid(
"copy requires an absolute guest path without parent traversal",
));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Receipt {
pub request_id: RequestId,
pub identity: ContentDigest,
pub entries: usize,
pub bytes: u64,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Response {
Ready,
Complete { receipt: Receipt },
Rejected { message: String },
Uncertain { message: String },
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Ack {
pub request_id: RequestId,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_actions_reject_parent_traversal_nulls_and_relative_paths() {
for path in [
b"relative".as_slice(),
b"/../escape",
b"/one/../two",
b"/bad\0name",
] {
assert!(
Action::Download {
path: path.to_vec()
}
.validate()
.is_err()
);
}
assert!(
Action::Download {
path: b"/raw-\xff".to_vec()
}
.validate()
.is_ok()
);
}
#[test]
fn test_upload_identities_must_be_sha256_digests() {
for identity in ["A".repeat(64), "z".repeat(64), "a".repeat(63)] {
let request = serde_json::json!({"kind":"upload","path":"Lw==","identity":format!("sha256:{identity}"),"durable":true});
assert!(serde_json::from_value::<Action>(request).is_err());
}
let request = serde_json::json!({"kind":"upload","path":"Lw==","identity":format!("sha256:{}", "a".repeat(64)),"durable":true});
assert!(serde_json::from_value::<Action>(request).is_ok());
}
}