use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use sha2::{Digest, Sha256};
use web_time::{SystemTime, UNIX_EPOCH};
pub const FILES_EXTENSION: &str = "io.modelcontextprotocol/files";
pub const FILE_SCHEMA_KEYWORD: &str = "x-mcp-file";
pub const DEFAULT_MAX_INLINE_BYTES: u64 = 1024 * 1024;
pub const DEFAULT_STATE_TTL: Duration = Duration::from_secs(15 * 60);
#[cfg(test)]
mod tests;
const STATE_PREFIX: &str = "mcf1.";
const MAX_SCHEMA_DEPTH: usize = 64;
pub fn file_schema(accept: &[&str], max_size: Option<u64>, require_digest: bool) -> Value {
let mut marker = Map::new();
if !accept.is_empty() {
marker.insert("accept".into(), json!(accept));
}
if let Some(max_size) = max_size {
marker.insert("maxSize".into(), json!(max_size));
}
let mut required = vec!["id", "mimeType", "size"];
if require_digest {
required.push("digest");
}
json!({
"type": "object",
FILE_SCHEMA_KEYWORD: marker,
"properties": {
"id": { "type": "string", "minLength": 1, "maxLength": 128 },
"name": { "type": "string" },
"mimeType": { "type": "string" },
"size": { "type": "integer", "minimum": 0 },
"digest": {
"type": "object",
"properties": {
"algorithm": { "const": "sha-256" },
"value": { "type": "string" }
},
"required": ["algorithm", "value"]
},
"data": { "type": "string" }
},
"required": required
})
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileDigest {
pub algorithm: String,
pub value: String,
}
impl FileDigest {
pub fn sha256(bytes: &[u8]) -> Self {
Self {
algorithm: "sha-256".into(),
value: encode_base64url(&Sha256::digest(bytes)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FileInput {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub mime_type: String,
pub size: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub digest: Option<FileDigest>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data: Option<String>,
}
impl FileInput {
pub fn inline(
id: impl Into<String>,
name: Option<String>,
mime_type: impl Into<String>,
bytes: &[u8],
) -> Self {
let mut file = Self::metadata(id, name, mime_type, bytes);
if !bytes.is_empty() {
file.data = Some(encode_base64(bytes));
}
file
}
pub fn metadata(
id: impl Into<String>,
name: Option<String>,
mime_type: impl Into<String>,
bytes: &[u8],
) -> Self {
Self {
id: id.into(),
name,
mime_type: mime_type.into(),
size: bytes.len() as u64,
digest: Some(FileDigest::sha256(bytes)),
data: None,
}
}
pub fn from_value(value: &Value) -> Result<Self, String> {
serde_json::from_value(value.clone())
.map_err(|error| format!("invalid file input: {error}"))
}
pub fn bytes(&self) -> Result<Vec<u8>, String> {
let bytes = match &self.data {
Some(data) => decode_base64(data).ok_or("file data is not valid base64")?,
None if self.size == 0 => Vec::new(),
None => return Err(format!("file {} has no data", self.id)),
};
check_bytes(self, &bytes)?;
Ok(bytes)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UploadForm {
pub fields: Vec<FormField>,
pub file_field: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FormField {
pub name: String,
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct UploadTarget {
pub file_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub form: Option<UploadForm>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub headers: Option<BTreeMap<String, String>>,
pub credentials: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<String>,
#[serde(default, rename = "_meta", skip_serializing_if = "Option::is_none")]
pub meta: Option<Map<String, Value>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct DownloadTarget {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub mime_type: String,
pub size: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub digest: Option<FileDigest>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub headers: Option<BTreeMap<String, String>>,
pub credentials: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<String>,
#[serde(default, rename = "_meta", skip_serializing_if = "Option::is_none")]
pub meta: Option<Map<String, Value>>,
}
pub fn downloads_meta(downloads: &[DownloadTarget]) -> Value {
json!({ FILES_EXTENSION: { "downloads": downloads } })
}
#[derive(Debug, Clone)]
pub struct StagedTarget {
pub target: UploadTarget,
pub handle: String,
}
#[async_trait::async_trait]
#[allow(
clippy::double_must_use,
reason = "async_trait annotates generated futures"
)]
pub trait FileStaging: Send + Sync {
async fn issue(&self, file: &FileInput, expires: SystemTime) -> Result<StagedTarget, String>;
async fn confirm(&self, handle: &str, file: &FileInput) -> Result<Option<Vec<u8>>, String>;
async fn consume(&self, state_id: &str, expires: SystemTime) -> Result<bool, String>;
}
#[derive(Clone)]
pub struct McpFilesOptions {
pub max_inline_bytes: u64,
pub staging: Option<Arc<dyn FileStaging>>,
pub signing_key: Vec<u8>,
pub state_ttl: Duration,
}
impl Default for McpFilesOptions {
fn default() -> Self {
Self {
max_inline_bytes: DEFAULT_MAX_INLINE_BYTES,
staging: None,
signing_key: Vec::new(),
state_ttl: DEFAULT_STATE_TTL,
}
}
}
impl std::fmt::Debug for McpFilesOptions {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("McpFilesOptions")
.field("max_inline_bytes", &self.max_inline_bytes)
.field("staging", &self.staging.is_some())
.field("state_ttl", &self.state_ttl)
.finish_non_exhaustive()
}
}
impl McpFilesOptions {
pub fn validate(&self) -> Result<(), String> {
if self.staging.is_some() && self.signing_key.len() < 32 {
return Err("file staging requires a signing key of at least 32 bytes".into());
}
if self.state_ttl.is_zero() {
return Err("file requestState lifetime must be positive".into());
}
Ok(())
}
pub(crate) fn settings(&self) -> Value {
let mut settings = Map::new();
if self.staging.is_some() {
settings.insert("upload".into(), json!({}));
}
if self.max_inline_bytes > 0 {
settings.insert("maxInlineBytes".into(), json!(self.max_inline_bytes));
}
Value::Object(settings)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct Declared {
pub(crate) upload: bool,
pub(crate) download: bool,
}
impl Declared {
pub(crate) fn from_capabilities(capabilities: Option<&Value>) -> Self {
let settings = capabilities
.and_then(|capabilities| capabilities.get("extensions"))
.and_then(|extensions| extensions.get(FILES_EXTENSION))
.filter(|settings| settings.is_object())
.filter(|settings| settings.get("revision").is_none());
Self {
upload: settings
.is_some_and(|settings| settings.get("upload").is_some_and(Value::is_object)),
download: settings
.is_some_and(|settings| settings.get("download").is_some_and(Value::is_object)),
}
}
}
pub(crate) enum Prepared {
Run {
arguments: Option<Map<String, Value>>,
request_state: Option<String>,
binding: Option<Binding>,
},
Respond(Value),
Reject(Value),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Binding {
tool: String,
arguments: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
principal: Option<String>,
files: Vec<StagedFile>,
expires: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct StagedFile {
id: String,
handle: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct State {
#[serde(flatten)]
binding: Binding,
nonce: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
inner: Option<String>,
}
#[derive(Debug, Clone, Default)]
struct Constraints {
accept: Vec<Vec<String>>,
max_size: Option<u64>,
require_digest: bool,
}
type Pointer = Vec<Segment>;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Segment {
Key(String),
Index(usize),
}
pub(crate) struct Call<'a> {
pub(crate) tool: &'a str,
pub(crate) schema: &'a Map<String, Value>,
pub(crate) nested: bool,
pub(crate) arguments: Option<Map<String, Value>>,
pub(crate) declared: Declared,
pub(crate) request_state: Option<String>,
pub(crate) principal: Option<&'a str>,
pub(crate) modern: bool,
}
fn missing_capability(capability: &str) -> Value {
json!({
"code": -32021,
"message": format!("request did not declare the {FILES_EXTENSION} {capability} capability"),
"data": {
"requiredCapabilities": {
"extensions": { FILES_EXTENSION: { capability: {} } }
}
}
})
}
fn invalid_state(message: &str) -> Prepared {
Prepared::Reject(json!({ "code": -32602, "message": message }))
}
pub(crate) fn tool_error(message: impl Into<String>) -> Value {
json!({
"resultType": "complete",
"content": [{ "type": "text", "text": message.into() }],
"isError": true
})
}
impl McpFilesOptions {
pub(crate) async fn prepare(&self, call: Call<'_>) -> Prepared {
let Call {
tool,
schema,
nested,
mut arguments,
declared,
request_state,
principal,
modern,
} = call;
let target = arguments.as_ref().map(|arguments| {
if nested {
arguments.get("arguments").cloned().unwrap_or(Value::Null)
} else {
Value::Object(arguments.clone())
}
});
let Some(target) = target else {
return Prepared::Run {
arguments,
request_state,
binding: None,
};
};
let mut found = BTreeMap::new();
let root = Value::Object(schema.clone());
collect_value(&root, &root, &target, &mut Vec::new(), &mut found, 0);
if found.is_empty() {
return Prepared::Run {
arguments,
request_state,
binding: None,
};
}
let mut ids = BTreeSet::new();
let mut inline_total = 0u64;
let mut pending = Vec::new();
for (pointer, constraints) in &found {
let Some(value) = lookup(&target, pointer) else {
continue;
};
let file = match parse_file(value) {
Ok(file) => file,
Err(message) => return Prepared::Respond(tool_error(message)),
};
if !ids.insert(file.id.clone()) {
return Prepared::Respond(tool_error(format!("duplicate file id {}", file.id)));
}
if let Err(message) = check_metadata(&file, constraints) {
return Prepared::Respond(tool_error(message));
}
match &file.data {
Some(data) if !(file.size == 0 && data.is_empty()) => {
let Some(bytes) = decode_base64(data) else {
return Prepared::Respond(tool_error(format!(
"file {} data is not valid base64",
file.id
)));
};
inline_total = inline_total.saturating_add(bytes.len() as u64);
if inline_total > self.max_inline_bytes {
return Prepared::Respond(tool_error(format!(
"inline file data exceeds {} bytes",
self.max_inline_bytes
)));
}
if let Err(message) = check_bytes(&file, &bytes) {
return Prepared::Respond(tool_error(message));
}
}
_ if file.size == 0 => {
if let Err(message) = check_bytes(&file, &[]) {
return Prepared::Respond(tool_error(message));
}
}
_ => pending.push((pointer.clone(), file, constraints.clone())),
}
}
if pending.is_empty() {
return Prepared::Run {
arguments,
request_state,
binding: None,
};
}
if let Some(state) = request_state
.as_deref()
.filter(|state| state.starts_with(STATE_PREFIX))
{
return self
.retry(
tool,
nested,
arguments.take().unwrap_or_default(),
principal,
state,
pending,
)
.await;
}
let Some(staging) = self.staging.as_ref() else {
return Prepared::Respond(tool_error(
"this server does not accept files out of band; send the file inline",
));
};
if !modern {
return Prepared::Respond(tool_error(
"out-of-band file uploads require protocol version 2026-07-28",
));
}
if !declared.upload {
return Prepared::Reject(missing_capability("upload"));
}
if let Err(message) = self.validate() {
return Prepared::Respond(tool_error(message));
}
let expires_at = SystemTime::now() + self.state_ttl;
let expires = unix_seconds(expires_at);
let mut uploads = Vec::new();
let mut files = Vec::new();
for (_, file, _) in &pending {
match staging.issue(file, expires_at).await {
Ok(StagedTarget { mut target, handle }) => {
target.file_id = file.id.clone();
uploads.push(target);
files.push(StagedFile {
id: file.id.clone(),
handle,
});
}
Err(message) => {
return Prepared::Respond(tool_error(format!(
"could not prepare an upload for file {}: {message}",
file.id
)));
}
}
}
let binding = Binding {
tool: tool.to_string(),
arguments: arguments_digest(&target),
principal: principal.map(str::to_string),
files,
expires,
};
Prepared::Respond(json!({
"resultType": "upload_required",
"uploads": uploads,
"requestState": self.sign(&binding, None),
}))
}
async fn retry(
&self,
tool: &str,
nested: bool,
mut arguments: Map<String, Value>,
principal: Option<&str>,
state: &str,
pending: Vec<(Pointer, FileInput, Constraints)>,
) -> Prepared {
let Some(State { binding, inner, .. }) = self.verify(state) else {
return invalid_state("requestState failed verification");
};
if binding.expires <= unix_seconds(SystemTime::now()) {
return invalid_state("requestState has expired");
}
let target = if nested {
arguments.get("arguments").cloned().unwrap_or(Value::Null)
} else {
Value::Object(arguments.clone())
};
if binding.tool != tool
|| binding.arguments != arguments_digest(&target)
|| binding.principal.as_deref() != principal
{
return invalid_state("tool name, arguments, or principal differ from requestState");
}
let Some(staging) = self.staging.as_ref() else {
return invalid_state("requestState failed verification");
};
let mut confirmed = Vec::new();
for (pointer, file, constraints) in pending {
let Some(staged) = binding.files.iter().find(|staged| staged.id == file.id) else {
return invalid_state("requestState does not bind every file");
};
let bytes = match staging.confirm(&staged.handle, &file).await {
Ok(Some(bytes)) => bytes,
Ok(None) => {
return Prepared::Respond(tool_error(format!(
"file {} has not arrived; the tool did not run",
file.id
)));
}
Err(message) => {
return Prepared::Respond(tool_error(format!(
"file {} could not be confirmed: {message}; the tool did not run",
file.id
)));
}
};
if let Err(message) =
check_bytes(&file, &bytes).and_then(|()| check_metadata(&file, &constraints))
{
return Prepared::Respond(tool_error(format!("{message}; the tool did not run")));
}
confirmed.push((pointer, bytes));
}
let expires_at = UNIX_EPOCH + Duration::from_secs(binding.expires);
match staging.consume(&state_id(state), expires_at).await {
Ok(true) => {}
Ok(false) => return invalid_state("requestState was already used"),
Err(message) => {
return Prepared::Respond(tool_error(format!(
"requestState could not be recorded: {message}; the tool did not run"
)));
}
}
let mut target = target;
for (pointer, bytes) in confirmed {
if let Some(Value::Object(file)) = lookup_mut(&mut target, &pointer) {
file.insert("data".into(), Value::String(encode_base64(&bytes)));
}
}
let arguments = if nested {
arguments.insert("arguments".into(), target);
arguments
} else {
match target {
Value::Object(map) => map,
_ => Map::new(),
}
};
Prepared::Run {
arguments: Some(arguments),
request_state: inner,
binding: Some(binding),
}
}
pub(crate) fn finish(&self, result: &mut Value, binding: Option<&Binding>, declared: Declared) {
if let Some(binding) = binding
&& result.get("resultType").and_then(Value::as_str) == Some("input_required")
{
let inner = result
.get("requestState")
.and_then(Value::as_str)
.map(str::to_string);
result["requestState"] = Value::String(self.sign(binding, inner));
}
if !declared.download {
strip_downloads(result);
}
}
fn sign(&self, binding: &Binding, inner: Option<String>) -> String {
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed| elapsed.as_nanos())
.unwrap_or_default();
let nonce = format!("{nanos:x}.{:x}", SEQUENCE.fetch_add(1, Ordering::Relaxed));
let state = State {
binding: binding.clone(),
nonce,
inner,
};
let payload = encode_base64url(&serde_json::to_vec(&state).unwrap_or_default());
let mac = hmac_sha256(&self.signing_key, payload.as_bytes());
format!("{STATE_PREFIX}{payload}.{}", encode_base64url(&mac))
}
fn verify(&self, state: &str) -> Option<State> {
if self.signing_key.is_empty() {
return None;
}
let (payload, mac) = state.strip_prefix(STATE_PREFIX)?.split_once('.')?;
let expected = hmac_sha256(&self.signing_key, payload.as_bytes());
let mac = decode_base64url(mac)?;
if !constant_time_eq(&expected, &mac) {
return None;
}
serde_json::from_slice(&decode_base64url(payload)?).ok()
}
}
pub(crate) fn strip_downloads(result: &mut Value) {
if let Some(meta) = result.get_mut("_meta").and_then(Value::as_object_mut)
&& let Some(settings) = meta.get_mut(FILES_EXTENSION).and_then(Value::as_object_mut)
{
settings.remove("downloads");
if settings.is_empty() {
meta.remove(FILES_EXTENSION);
}
if meta.is_empty()
&& let Some(object) = result.as_object_mut()
{
object.remove("_meta");
}
}
}
fn state_id(state: &str) -> String {
encode_base64url(&Sha256::digest(state.as_bytes()))
}
fn unix_seconds(time: SystemTime) -> u64 {
time.duration_since(UNIX_EPOCH)
.map(|elapsed| elapsed.as_secs())
.unwrap_or_default()
}
fn parse_file(value: &Value) -> Result<FileInput, String> {
let object = value
.as_object()
.ok_or("a file argument must be an object")?;
if object.get("data").is_some_and(Value::is_null) {
return Err("file data is not valid base64".into());
}
let file = FileInput::from_value(value)?;
let length = file.id.chars().count();
if !(1..=128).contains(&length) {
return Err("a file id must be 1 to 128 characters".into());
}
if let Some(digest) = &file.digest
&& (digest.algorithm != "sha-256"
|| decode_base64url(&digest.value).is_none_or(|value| value.len() != 32))
{
return Err(format!("file {} has an unsupported digest", file.id));
}
Ok(file)
}
fn check_metadata(file: &FileInput, constraints: &Constraints) -> Result<(), String> {
if let Some(max_size) = constraints.max_size
&& file.size > max_size
{
return Err(format!("file {} is larger than {max_size} bytes", file.id));
}
for accept in &constraints.accept {
if !accepts(accept, &file.mime_type) {
return Err(format!(
"file {} has a media type this tool does not accept",
file.id
));
}
}
if constraints.require_digest && file.digest.is_none() {
return Err(format!("file {} requires a digest", file.id));
}
Ok(())
}
fn check_bytes(file: &FileInput, bytes: &[u8]) -> Result<(), String> {
if bytes.len() as u64 != file.size {
return Err(format!("file {} does not match its declared size", file.id));
}
if let Some(digest) = &file.digest
&& FileDigest::sha256(bytes).value != digest.value
{
return Err(format!("file {} does not match its digest", file.id));
}
Ok(())
}
fn essence(media_type: &str) -> String {
media_type
.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
}
fn accepts(accept: &[String], media_type: &str) -> bool {
if accept.is_empty() {
return true;
}
let media_type = essence(media_type);
let Some((kind, _)) = media_type.split_once('/') else {
return false;
};
accept.iter().any(|pattern| {
let pattern = essence(pattern);
pattern == "*/*"
|| pattern == media_type
|| pattern
.strip_suffix("/*")
.is_some_and(|range| range == kind)
})
}
fn resolve<'a>(root: &'a Value, schema: &'a Value) -> &'a Value {
let mut schema = schema;
for _ in 0..MAX_SCHEMA_DEPTH {
let Some(reference) = schema.get("$ref").and_then(Value::as_str) else {
return schema;
};
match reference
.strip_prefix('#')
.and_then(|pointer| root.pointer(pointer))
{
Some(target) => schema = target,
None => return schema,
}
}
schema
}
fn collect_value(
root: &Value,
schema: &Value,
value: &Value,
path: &mut Pointer,
found: &mut BTreeMap<Pointer, Constraints>,
depth: usize,
) {
if depth > MAX_SCHEMA_DEPTH {
return;
}
let schema = resolve(root, schema);
let Some(object) = schema.as_object() else {
return;
};
if let Some(marker) = object.get(FILE_SCHEMA_KEYWORD).and_then(Value::as_object)
&& value.is_object()
{
let entry = found.entry(path.clone()).or_default();
if let Some(accept) = marker.get("accept").and_then(Value::as_array) {
entry.accept.push(
accept
.iter()
.filter_map(Value::as_str)
.map(str::to_string)
.collect(),
);
}
if let Some(max_size) = marker.get("maxSize").and_then(Value::as_u64) {
entry.max_size = Some(
entry
.max_size
.map_or(max_size, |current| current.min(max_size)),
);
}
if object
.get("required")
.and_then(Value::as_array)
.is_some_and(|required| required.iter().any(|name| name == "digest"))
{
entry.require_digest = true;
}
return;
}
for keyword in ["allOf", "anyOf", "oneOf"] {
if let Some(branches) = object.get(keyword).and_then(Value::as_array) {
for branch in branches {
collect_value(root, branch, value, path, found, depth + 1);
}
}
}
match value {
Value::Object(members) => {
let properties = object.get("properties").and_then(Value::as_object);
for (key, member) in members {
let schema = properties
.and_then(|properties| properties.get(key))
.or_else(|| {
object
.get("additionalProperties")
.filter(|schema| schema.is_object())
});
if let Some(schema) = schema {
path.push(Segment::Key(key.clone()));
collect_value(root, schema, member, path, found, depth + 1);
path.pop();
}
}
}
Value::Array(items) => {
let prefix = object.get("prefixItems").and_then(Value::as_array);
for (index, item) in items.iter().enumerate() {
let schema = prefix
.and_then(|prefix| prefix.get(index))
.or_else(|| object.get("items").filter(|schema| schema.is_object()));
if let Some(schema) = schema {
path.push(Segment::Index(index));
collect_value(root, schema, item, path, found, depth + 1);
path.pop();
}
}
}
_ => {}
}
}
fn lookup<'a>(value: &'a Value, pointer: &[Segment]) -> Option<&'a Value> {
pointer
.iter()
.try_fold(value, |value, segment| match segment {
Segment::Key(key) => value.get(key),
Segment::Index(index) => value.get(index),
})
}
fn lookup_mut<'a>(value: &'a mut Value, pointer: &[Segment]) -> Option<&'a mut Value> {
pointer
.iter()
.try_fold(value, |value, segment| match segment {
Segment::Key(key) => value.get_mut(key),
Segment::Index(index) => value.get_mut(index),
})
}
fn arguments_digest(value: &Value) -> String {
let mut canonical = String::new();
write_canonical(value, &mut canonical);
encode_base64url(&Sha256::digest(canonical.as_bytes()))
}
fn write_canonical(value: &Value, out: &mut String) {
match value {
Value::Object(members) => {
out.push('{');
let sorted: BTreeMap<_, _> = members.iter().collect();
for (index, (key, member)) in sorted.into_iter().enumerate() {
if index > 0 {
out.push(',');
}
out.push_str(&Value::String(key.clone()).to_string());
out.push(':');
write_canonical(member, out);
}
out.push('}');
}
Value::Array(items) => {
out.push('[');
for (index, item) in items.iter().enumerate() {
if index > 0 {
out.push(',');
}
write_canonical(item, out);
}
out.push(']');
}
Value::Number(number) => out.push_str(&canonical_number(&number.to_string())),
other => out.push_str(&other.to_string()),
}
}
fn canonical_number(token: &str) -> String {
let (negative, token) = match token.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, token),
};
let (mantissa, exponent) = match token.find(['e', 'E']) {
Some(index) => (
&token[..index],
token[index + 1..].parse::<i64>().unwrap_or(0),
),
None => (token, 0),
};
let (integer, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
let digits = format!("{integer}{fraction}");
let mut exponent = exponent - fraction.len() as i64;
let digits = digits.trim_start_matches('0');
if digits.is_empty() {
return "0".into();
}
let trimmed = digits.trim_end_matches('0');
exponent += (digits.len() - trimmed.len()) as i64;
format!("{}{trimmed}e{exponent}", if negative { "-" } else { "" })
}
fn hmac_sha256(key: &[u8], message: &[u8]) -> [u8; 32] {
let mut block = [0u8; 64];
if key.len() > 64 {
block[..32].copy_from_slice(&Sha256::digest(key));
} else {
block[..key.len()].copy_from_slice(key);
}
let mut inner = Sha256::new();
inner.update(block.map(|byte| byte ^ 0x36));
inner.update(message);
let mut outer = Sha256::new();
outer.update(block.map(|byte| byte ^ 0x5c));
outer.update(inner.finalize());
outer.finalize().into()
}
fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
left.len() == right.len()
&& left
.iter()
.zip(right)
.fold(0u8, |difference, (left, right)| difference | (left ^ right))
== 0
}
const STANDARD: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const URL_SAFE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
fn encode_with(bytes: &[u8], alphabet: &[u8; 64], pad: bool) -> String {
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let triple = (u32::from(chunk[0]) << 16)
| (u32::from(*chunk.get(1).unwrap_or(&0)) << 8)
| u32::from(*chunk.get(2).unwrap_or(&0));
for index in 0..4 {
if index <= chunk.len() {
out.push(char::from(
alphabet[((triple >> (18 - 6 * index)) & 63) as usize],
));
} else if pad {
out.push('=');
}
}
}
out
}
fn decode_with(input: &str, alphabet: &[u8; 64], padded: bool) -> Option<Vec<u8>> {
let bytes = input.as_bytes();
let body = if padded {
if !bytes.len().is_multiple_of(4) {
return None;
}
let padding = bytes.iter().rev().take_while(|byte| **byte == b'=').count();
if padding > 2 {
return None;
}
&bytes[..bytes.len() - padding]
} else {
bytes
};
if body.len() % 4 == 1 {
return None;
}
let mut out = Vec::with_capacity(body.len() * 3 / 4);
let mut buffer = 0u32;
let mut bits = 0u32;
for byte in body {
let sextet = alphabet.iter().position(|candidate| candidate == byte)? as u32;
buffer = (buffer << 6) | sextet;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((buffer >> bits) as u8);
buffer &= (1 << bits) - 1;
}
}
(buffer == 0).then_some(out)
}
pub fn encode_base64(bytes: &[u8]) -> String {
encode_with(bytes, STANDARD, true)
}
pub fn decode_base64(input: &str) -> Option<Vec<u8>> {
decode_with(input, STANDARD, true)
}
fn encode_base64url(bytes: &[u8]) -> String {
encode_with(bytes, URL_SAFE, false)
}
fn decode_base64url(input: &str) -> Option<Vec<u8>> {
decode_with(input, URL_SAFE, false)
}