use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TenantContext {
pub tenant_id: String,
pub env_id: String,
#[serde(default)]
pub user_email: Option<String>,
#[serde(default)]
pub project_id: Option<String>,
#[serde(default)]
pub caller: Option<VerifiedCaller>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct VerifiedCaller {
#[serde(default)]
pub user_verified: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sub: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub groups: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub team: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub role: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub iss: Option<String>,
}
impl TenantContext {
pub fn new(tenant_id: impl Into<String>, env_id: impl Into<String>) -> Self {
Self {
tenant_id: tenant_id.into(),
env_id: env_id.into(),
user_email: None,
project_id: None,
caller: None,
}
}
#[must_use]
pub fn with_user_email(mut self, email: Option<String>) -> Self {
self.user_email = email;
self
}
#[must_use]
pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
self.project_id = project_id;
self
}
#[must_use]
pub fn with_caller(mut self, caller: Option<VerifiedCaller>) -> Self {
self.caller = caller;
self
}
pub fn caller_or_anonymous(&self) -> VerifiedCaller {
self.caller.clone().unwrap_or_default()
}
pub fn key_prefix(&self) -> String {
format!("aw:{}:{}", self.tenant_id, self.env_id)
}
}
const MAX_ID_LEN: usize = 256;
pub fn validate_scope_id(kind: &str, id: &str) -> Result<(), String> {
if id.is_empty() {
return Err(format!("{kind} id is empty"));
}
if id.len() > MAX_ID_LEN {
return Err(format!("{kind} id is longer than {MAX_ID_LEN} bytes"));
}
if id.contains(['/', '\\', ':']) || id.contains("..") || id.chars().any(char::is_control) {
return Err(format!("{kind} id contains a forbidden character"));
}
Ok(())
}
pub fn validate_target_id(id: &str) -> Result<(), String> {
if id.is_empty() {
return Err("target is empty".to_string());
}
if id.len() > MAX_ID_LEN {
return Err(format!("target is longer than {MAX_ID_LEN} bytes"));
}
if id.contains(['/', '\\', '?', '#', '%'])
|| id.contains("..")
|| id.chars().any(|c| c.is_control() || c.is_whitespace())
{
return Err("target contains a forbidden character".to_string());
}
Ok(())
}
pub(crate) const MAX_SESSION_ID_LEN: usize = 512;
pub fn validate_session_id(id: &str) -> Result<(), String> {
if id.is_empty() {
return Err("session id is empty".to_string());
}
if id.len() > MAX_SESSION_ID_LEN {
return Err("session id is too long".to_string());
}
if id.chars().any(char::is_control) {
return Err("session id contains a forbidden character".to_string());
}
Ok(())
}
pub fn is_dot_segment(segment: &str) -> bool {
matches!(segment, "." | "..")
}
pub fn percent_encode_segment(segment: &str) -> String {
let mut out = String::with_capacity(segment.len());
for byte in segment.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
out.push(char::from(byte));
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scope_ids_reject_separators_traversal_and_empties() {
assert!(validate_scope_id("tenant", "acme-1").is_ok());
for bad in ["", "a:b", "a/b", "..", "a..b", "a\\b", "a\nb"] {
assert!(validate_scope_id("tenant", bad).is_err(), "{bad:?}");
}
assert!(validate_scope_id("tenant", &"x".repeat(300)).is_err());
}
#[test]
fn session_ids_allow_provider_ids_but_not_controls_or_oversize() {
assert!(validate_session_id("s1::pack=p::flow=f").is_ok());
assert!(validate_session_id("s::thread=YWJj/ZGVm+==::reply=<a..b@mail.example>").is_ok());
for bad in ["", "a\u{0}b", "a\nb"] {
assert!(validate_session_id(bad).is_err(), "{bad:?}");
}
assert!(validate_session_id(&"x".repeat(513)).is_err());
assert!(validate_session_id(&"x".repeat(512)).is_ok());
}
#[test]
fn percent_encoding_neutralises_path_metacharacters() {
assert_eq!(percent_encode_segment("acme-1_x.y"), "acme-1_x.y");
assert_eq!(percent_encode_segment("a/b?c#d e"), "a%2Fb%3Fc%23d%20e");
assert_eq!(percent_encode_segment("é"), "%C3%A9");
assert_eq!(percent_encode_segment("a..b"), "a..b");
assert!(is_dot_segment("..") && is_dot_segment("."));
assert!(!is_dot_segment("a..b") && !is_dot_segment(""));
}
#[test]
fn target_ids_that_could_steer_a_path_are_rejected() {
for ok in ["bot", "8d2f0c1e-recipe", "agent_1.v2", "a:b"] {
assert!(validate_target_id(ok).is_ok(), "{ok}");
}
for bad in [
"",
"../tenant/me/mcp-servers",
"a/b",
"a?x=1",
"a#f",
"a%2Fb",
"..",
"a\\b",
"a b",
"a\nb",
] {
assert!(validate_target_id(bad).is_err(), "{bad:?}");
}
assert!(validate_target_id(&"x".repeat(MAX_ID_LEN + 1)).is_err());
}
#[test]
fn key_prefix_formats_as_expected() {
let ctx = TenantContext::new("acme", "prod");
assert_eq!(ctx.key_prefix(), "aw:acme:prod");
}
#[test]
fn tenant_context_is_eq_and_hashable() {
let a = TenantContext::new("acme", "prod");
let b = TenantContext::new("acme", "prod");
assert_eq!(a, b);
let mut set = std::collections::HashSet::new();
set.insert(a);
assert!(set.contains(&b));
}
#[test]
fn user_email_defaults_none_and_builder_sets_it() {
let a = TenantContext::new("acme", "prod");
assert_eq!(a.user_email, None);
let b = TenantContext::new("acme", "prod").with_user_email(Some("u@x.com".into()));
assert_eq!(b.user_email.as_deref(), Some("u@x.com"));
assert_eq!(b.key_prefix(), "aw:acme:prod");
}
#[test]
fn project_id_defaults_none_and_builder_sets_it() {
let a = TenantContext::new("acme", "prod");
assert_eq!(
a.project_id, None,
"unknown pack identity must stay None, never a placeholder"
);
let b = TenantContext::new("acme", "prod").with_project_id(Some("customer.support".into()));
assert_eq!(b.project_id.as_deref(), Some("customer.support"));
assert_eq!(b.key_prefix(), "aw:acme:prod");
}
}