use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use thiserror::Error;
pub const MAX_AGENT_ID_LEN: usize = 512;
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PrincipalError {
#[error("agent id must not be empty; use a URI such as `urn:adk:agent:<name>`")]
Empty,
#[error(
"agent id is {len} bytes, more than the {MAX_AGENT_ID_LEN}-byte limit; use a shorter URI"
)]
TooLong {
len: usize,
},
#[error("agent id must not contain control characters (found U+{code_point:04X})")]
ContainsControl {
code_point: u32,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct AgentId(String);
impl AgentId {
pub fn new(value: impl Into<String>) -> Result<Self, PrincipalError> {
let value = value.into();
if value.is_empty() {
return Err(PrincipalError::Empty);
}
if value.len() > MAX_AGENT_ID_LEN {
return Err(PrincipalError::TooLong { len: value.len() });
}
if let Some(control) = value.chars().find(|c| c.is_control()) {
return Err(PrincipalError::ContainsControl { code_point: control as u32 });
}
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for AgentId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for AgentId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl FromStr for AgentId {
type Err = PrincipalError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::new(s)
}
}
impl TryFrom<String> for AgentId {
type Error = PrincipalError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl TryFrom<&str> for AgentId {
type Error = PrincipalError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl From<AgentId> for String {
fn from(id: AgentId) -> Self {
id.0
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum SubjectKind {
#[default]
Human,
Service,
Agent,
Visitor,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubjectRef {
pub kind: SubjectKind,
pub id: String,
}
impl SubjectRef {
pub fn new(kind: SubjectKind, id: impl Into<String>) -> Self {
Self { kind, id: id.into() }
}
pub fn human(id: impl Into<String>) -> Self {
Self::new(SubjectKind::Human, id)
}
pub fn service(id: impl Into<String>) -> Self {
Self::new(SubjectKind::Service, id)
}
pub fn agent(id: &AgentId) -> Self {
Self::new(SubjectKind::Agent, id.as_str())
}
pub fn visitor(id: impl Into<String>) -> Self {
Self::new(SubjectKind::Visitor, id)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentPrincipal {
pub id: AgentId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tenant: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub class: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instance: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sponsor: Option<SubjectRef>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub attributes: BTreeMap<String, String>,
}
impl AgentPrincipal {
pub fn new(id: AgentId) -> Self {
Self {
id,
tenant: None,
class: None,
instance: None,
sponsor: None,
attributes: BTreeMap::new(),
}
}
pub fn with_tenant(mut self, tenant: impl Into<String>) -> Self {
self.tenant = Some(tenant.into());
self
}
pub fn with_class(mut self, class: impl Into<String>) -> Self {
self.class = Some(class.into());
self
}
pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
self.instance = Some(instance.into());
self
}
pub fn with_sponsor(mut self, sponsor: SubjectRef) -> Self {
self.sponsor = Some(sponsor);
self
}
pub fn with_attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.attributes.insert(key.into(), value.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActingContext {
pub agent: AgentPrincipal,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_behalf_of: Option<SubjectRef>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub delegation_chain: Vec<SubjectRef>,
}
impl ActingContext {
pub fn new(agent: AgentPrincipal) -> Self {
Self { agent, on_behalf_of: None, delegation_chain: Vec::new() }
}
pub fn on_behalf_of(mut self, subject: SubjectRef) -> Self {
self.on_behalf_of = Some(subject);
self
}
pub fn delegated_by(mut self, subject: SubjectRef) -> Self {
self.delegation_chain.push(subject);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn agent_id_validation() {
assert_eq!(AgentId::new(""), Err(PrincipalError::Empty));
assert_eq!(
AgentId::new("a".repeat(MAX_AGENT_ID_LEN + 1)),
Err(PrincipalError::TooLong { len: MAX_AGENT_ID_LEN + 1 })
);
assert_eq!(
AgentId::new("urn:adk:\u{7f}"),
Err(PrincipalError::ContainsControl { code_point: 0x7f })
);
assert_eq!(AgentId::new("x\0y"), Err(PrincipalError::ContainsControl { code_point: 0 }));
assert!(AgentId::new("a".repeat(MAX_AGENT_ID_LEN)).is_ok());
assert!(AgentId::new("urn:adk:agent:fakturering/ΓΈ").is_ok());
}
#[test]
fn agent_id_deserialization_validates() {
let parsed: AgentId = serde_json::from_value(json!("urn:adk:agent:a")).unwrap();
assert_eq!(parsed.as_str(), "urn:adk:agent:a");
assert!(serde_json::from_value::<AgentId>(json!("")).is_err());
assert!(serde_json::from_value::<AgentId>(json!("a\tb")).is_err());
}
#[test]
fn acting_context_round_trips_in_camel_case() {
let acting = ActingContext::new(
AgentPrincipal::new(AgentId::new("spiffe://example.org/agent/billing").unwrap())
.with_tenant("acme")
.with_class("billing")
.with_instance("r1")
.with_sponsor(SubjectRef::human("alice"))
.with_attribute("tier", "gold"),
)
.on_behalf_of(SubjectRef::service("crm"))
.delegated_by(SubjectRef::human("alice"));
let value = serde_json::to_value(&acting).unwrap();
assert_eq!(
value,
json!({
"agent": {
"id": "spiffe://example.org/agent/billing",
"tenant": "acme",
"class": "billing",
"instance": "r1",
"sponsor": {"kind": "human", "id": "alice"},
"attributes": {"tier": "gold"}
},
"onBehalfOf": {"kind": "service", "id": "crm"},
"delegationChain": [{"kind": "human", "id": "alice"}]
})
);
let back: ActingContext = serde_json::from_value(value).unwrap();
assert_eq!(back, acting);
let minimal =
ActingContext::new(AgentPrincipal::new(AgentId::new("urn:adk:agent:a").unwrap()));
let back: ActingContext =
serde_json::from_value(serde_json::to_value(&minimal).unwrap()).unwrap();
assert_eq!(back, minimal);
}
#[test]
fn contexts_recorded_with_an_invocation_id_still_read() {
let back: ActingContext = serde_json::from_value(json!({
"agent": {"id": "urn:adk:agent:a"},
"invocationId": "inv-old"
}))
.unwrap();
assert_eq!(
back,
ActingContext::new(AgentPrincipal::new(AgentId::new("urn:adk:agent:a").unwrap()))
);
}
}