use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::addr::Handle;
use crate::limits::EXTERNAL_ID_MAX_BYTES;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ExternalId {
K2Principal(String),
K2Workspace(String),
K2Owner,
K2Connect(String),
Local(Handle),
Link {
channel: crate::id::Id,
token: String,
},
AppService {
app_id: String,
},
K2Server,
Erased(crate::id::Id),
}
pub const ERASED_PREFIX: &str = "erased:";
pub const K2_SERVER: &str = "k2:server";
pub const APP_SERVICE_PREFIX: &str = "app:";
pub const LINK_GUEST_TOKEN_CHARS: usize = 16;
pub fn is_link_token(s: &str) -> bool {
s.len() == LINK_GUEST_TOKEN_CHARS
&& s.bytes()
.all(|c| c.is_ascii_uppercase() || (b'2'..=b'7').contains(&c))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExternalIdError(String);
impl fmt::Display for ExternalIdError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"invalid external id {:?}: expected k2:principal:<uuid>, k2:workspace:<uuid>, k2:connect:<uuid>, k2:owner, k2:server, local:<handle>, link:<channel_id>:<base32>, app:<app_id> or erased:<member_id>",
self.0
)
}
}
impl std::error::Error for ExternalIdError {}
pub fn is_lower_uuid(s: &str) -> bool {
let b = s.as_bytes();
b.len() == 36
&& b.iter().enumerate().all(|(i, c)| match i {
8 | 13 | 18 | 23 => *c == b'-',
_ => c.is_ascii_digit() || (b'a'..=b'f').contains(c),
})
}
impl ExternalId {
pub fn is_agent(&self) -> bool {
matches!(self, ExternalId::K2Workspace(_))
}
pub fn is_link(&self) -> bool {
matches!(self, ExternalId::Link { .. })
}
pub fn is_box_user(&self) -> bool {
matches!(self, ExternalId::K2Owner | ExternalId::K2Connect(_))
}
pub fn is_erased(&self) -> bool {
matches!(self, ExternalId::Erased(_))
}
pub fn service_app(&self) -> Option<&str> {
match self {
ExternalId::AppService { app_id } => Some(app_id),
_ => None,
}
}
pub fn is_service_owner(&self) -> bool {
matches!(self, ExternalId::AppService { .. } | ExternalId::K2Server)
}
pub fn is_app_user(&self) -> bool {
matches!(
self,
ExternalId::K2Principal(_) | ExternalId::AppService { .. }
)
}
pub fn service_owner(app_id: &str) -> ExternalId {
ExternalId::AppService {
app_id: app_id.to_owned(),
}
}
}
impl FromStr for ExternalId {
type Err = ExternalIdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let err = || ExternalIdError(s.to_owned());
if s.len() > EXTERNAL_ID_MAX_BYTES {
return Err(err());
}
if s == "k2:owner" {
return Ok(ExternalId::K2Owner);
}
if s == K2_SERVER {
return Ok(ExternalId::K2Server);
}
if let Some(u) = s.strip_prefix("k2:principal:") {
return if is_lower_uuid(u) {
Ok(ExternalId::K2Principal(u.to_owned()))
} else {
Err(err())
};
}
if let Some(u) = s.strip_prefix("k2:workspace:") {
return if is_lower_uuid(u) {
Ok(ExternalId::K2Workspace(u.to_owned()))
} else {
Err(err())
};
}
if let Some(u) = s.strip_prefix("k2:connect:") {
return if is_lower_uuid(u) {
Ok(ExternalId::K2Connect(u.to_owned()))
} else {
Err(err())
};
}
if let Some(h) = s.strip_prefix("local:") {
return Handle::new(h).map(ExternalId::Local).map_err(|_| err());
}
if let Some(rest) = s.strip_prefix("link:") {
let (c, t) = rest.split_once(':').ok_or_else(err)?;
let channel: crate::id::Id = c.parse().map_err(|_| err())?;
if channel.to_string() != c || !is_link_token(t) {
return Err(err());
}
return Ok(ExternalId::Link {
channel,
token: t.to_owned(),
});
}
if let Some(rest) = s.strip_prefix(ERASED_PREFIX) {
let id: crate::id::Id = rest.parse().map_err(|_| err())?;
if id.to_string() != rest {
return Err(err());
}
return Ok(ExternalId::Erased(id));
}
if let Some(rest) = s.strip_prefix(APP_SERVICE_PREFIX) {
return if crate::mgmt::is_app_id(rest) {
Ok(ExternalId::AppService {
app_id: rest.to_owned(),
})
} else {
Err(err())
};
}
Err(err())
}
}
impl fmt::Display for ExternalId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ExternalId::K2Principal(u) => write!(f, "k2:principal:{u}"),
ExternalId::K2Workspace(u) => write!(f, "k2:workspace:{u}"),
ExternalId::K2Owner => f.write_str("k2:owner"),
ExternalId::K2Connect(u) => write!(f, "k2:connect:{u}"),
ExternalId::Local(h) => write!(f, "local:{h}"),
ExternalId::Link { channel, token } => write!(f, "link:{channel}:{token}"),
ExternalId::AppService { app_id } => write!(f, "app:{app_id}"),
ExternalId::K2Server => f.write_str(K2_SERVER),
ExternalId::Erased(id) => write!(f, "{ERASED_PREFIX}{id}"),
}
}
}
impl Serialize for ExternalId {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for ExternalId {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = Cow::<'de, str>::deserialize(deserializer)?;
s.parse().map_err(serde::de::Error::custom)
}
}
impl JsonSchema for ExternalId {
fn inline_schema() -> bool {
true
}
fn schema_name() -> Cow<'static, str> {
"ExternalId".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "string",
"maxLength": 128,
"pattern": "^(k2:(principal|workspace|connect):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|k2:owner|k2:server|local:[a-z0-9_-]{2,64}|link:[1-9][0-9]{0,18}:[A-Z2-7]{16}|app:[a-z0-9][a-z0-9._-]{0,63}|erased:[1-9][0-9]{0,18})$",
"description": "An external identity: k2:principal:<uuid>, k2:workspace:<uuid>, k2:connect:<uuid>, k2:owner, k2:server (K2's server service owner), local:<handle>, link:<channel_id>:<base32> (a meeting link guest), app:<app_id> (an App's service owner) or erased:<member_id> (an erased member's tombstone id; never accepted as input)."
})
}
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn erased_ids_round_trip_in_canonical_form_only() {
let e: ExternalId = "erased:48831765147549703".parse().expect("erased id");
assert_eq!(
e,
ExternalId::Erased(crate::id::Id::new_const(48_831_765_147_549_703))
);
assert!(e.is_erased());
assert_eq!(e.to_string(), "erased:48831765147549703");
for bad in ["erased:", "erased:0", "erased:01", "erased:x", "erased:1:2"] {
assert!(bad.parse::<ExternalId>().is_err(), "{bad}");
}
assert!(!ExternalId::K2Owner.is_erased());
}
}