1use std::{collections::BTreeSet, fmt, str::FromStr};
2
3use anyhow::{Context, Result, bail};
4use iroh::{EndpointId, SecretKey};
5use n0_future::time::Duration;
6use rcan::{Capability, Expires, Rcan};
7use serde::{Deserialize, Serialize};
8
9macro_rules! cap_enum(
10 ($enum:item) => {
11 #[derive(
12 Debug,
13 Eq,
14 PartialEq,
15 Ord,
16 PartialOrd,
17 Serialize,
18 Deserialize,
19 Clone,
20 Copy,
21 strum::Display,
22 strum::EnumString,
23 )]
24 #[strum(serialize_all = "kebab-case")]
25 #[serde(rename_all = "kebab-case")]
26 $enum
27 }
28);
29
30#[derive(Debug, Eq, PartialEq, Serialize, Deserialize, Clone)]
31#[serde(rename_all = "kebab-case")]
32pub enum Caps {
33 V0(CapSet<Cap>),
34}
35
36impl Default for Caps {
37 fn default() -> Self {
38 Self::V0(CapSet::default())
39 }
40}
41
42impl std::ops::Deref for Caps {
43 type Target = CapSet<Cap>;
44
45 fn deref(&self) -> &Self::Target {
46 let Self::V0(slf) = self;
47 slf
48 }
49}
50
51#[derive(
60 Debug,
61 Eq,
62 PartialEq,
63 Ord,
64 PartialOrd,
65 Serialize,
66 Deserialize,
67 Clone,
68 Copy,
69 derive_more::From,
70 strum::Display,
71)]
72#[serde(rename_all = "kebab-case")]
73pub enum Cap {
74 #[strum(to_string = "all")]
75 All,
76 #[strum(to_string = "client")]
77 Client,
78 #[strum(to_string = "relay:{0}")]
79 Relay(RelayCap),
80 #[strum(to_string = "metrics:{0}")]
81 Metrics(MetricsCap),
82 #[strum(to_string = "net-diagnostics:{0}")]
83 NetDiagnostics(NetDiagnosticsCap),
84 #[strum(to_string = "logs:{0}")]
85 Logs(LogsCap),
86}
87
88impl FromStr for Cap {
89 type Err = anyhow::Error;
90
91 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
92 if s == "all" {
93 Ok(Self::All)
94 } else if let Some((domain, inner)) = s.split_once(":") {
95 Ok(match domain {
96 "metrics" => Self::Metrics(MetricsCap::from_str(inner)?),
97 "relay" => Self::Relay(RelayCap::from_str(inner)?),
98 "net-diagnostics" => Self::NetDiagnostics(NetDiagnosticsCap::from_str(inner)?),
99 "logs" => Self::Logs(LogsCap::from_str(inner)?),
100 _ => bail!("invalid cap domain"),
101 })
102 } else {
103 Err(anyhow::anyhow!("invalid cap string"))
104 }
105 }
106}
107
108cap_enum!(
109 pub enum MetricsCap {
110 PutAny,
111 }
112);
113
114cap_enum!(
115 pub enum RelayCap {
116 Use,
117 }
118);
119
120cap_enum!(
121 pub enum NetDiagnosticsCap {
122 PutAny,
123 GetAny,
124 }
125);
126
127cap_enum!(
128 pub enum LogsCap {
130 Push,
132 SetLevel,
134 }
135);
136
137impl Caps {
138 pub fn new(caps: impl IntoIterator<Item = impl Into<Cap>>) -> Self {
139 Self::V0(CapSet::new(caps))
140 }
141
142 pub fn for_shared_secret() -> Self {
148 Self::new([Cap::Client])
149 }
150
151 pub fn all() -> Self {
154 Self::new([Cap::All])
155 }
156
157 pub fn extend(self, caps: impl IntoIterator<Item = impl Into<Cap>>) -> Self {
158 let Self::V0(mut set) = self;
159 set.extend(caps.into_iter().map(Into::into));
160 Self::V0(set)
161 }
162
163 pub fn from_strs<'a>(strs: impl IntoIterator<Item = &'a str>) -> Result<Self> {
164 Ok(Self::V0(CapSet::from_strs(strs)?))
165 }
166
167 pub fn to_strings(&self) -> Vec<String> {
168 let Self::V0(set) = self;
169 set.to_strings()
170 }
171}
172
173impl Capability for Caps {
174 fn permits(&self, other: &Self) -> bool {
175 let Self::V0(slf) = self;
176 let Self::V0(other) = other;
177 slf.permits(other)
178 }
179}
180
181impl From<Cap> for Caps {
182 fn from(cap: Cap) -> Self {
183 Self::new([cap])
184 }
185}
186
187impl Capability for Cap {
188 fn permits(&self, other: &Self) -> bool {
189 match (self, other) {
190 (Cap::All, _) => true,
191 (Cap::Client, other) => client_capabilities(other),
192 (Cap::Relay(slf), Cap::Relay(other)) => slf.permits(other),
193 (Cap::Metrics(slf), Cap::Metrics(other)) => slf.permits(other),
194 (Cap::NetDiagnostics(slf), Cap::NetDiagnostics(other)) => slf.permits(other),
195 (Cap::Logs(slf), Cap::Logs(other)) => slf.permits(other),
196 (_, _) => false,
197 }
198 }
199}
200
201fn client_capabilities(other: &Cap) -> bool {
202 match other {
203 Cap::All => false,
204 Cap::Client => true,
205 Cap::Relay(RelayCap::Use) => true,
206 Cap::Metrics(MetricsCap::PutAny) => true,
207 Cap::NetDiagnostics(NetDiagnosticsCap::PutAny) => true,
208 Cap::NetDiagnostics(NetDiagnosticsCap::GetAny) => true,
209 Cap::Logs(LogsCap::Push) => true,
210 Cap::Logs(LogsCap::SetLevel) => true,
211 }
212}
213
214impl Capability for MetricsCap {
215 fn permits(&self, other: &Self) -> bool {
216 match (self, other) {
217 (MetricsCap::PutAny, MetricsCap::PutAny) => true,
218 }
219 }
220}
221
222impl Capability for RelayCap {
223 fn permits(&self, other: &Self) -> bool {
224 match (self, other) {
225 (RelayCap::Use, RelayCap::Use) => true,
226 }
227 }
228}
229
230impl Capability for NetDiagnosticsCap {
231 fn permits(&self, other: &Self) -> bool {
232 match (self, other) {
233 (NetDiagnosticsCap::PutAny, NetDiagnosticsCap::PutAny) => true,
234 (NetDiagnosticsCap::GetAny, NetDiagnosticsCap::GetAny) => true,
235 (_, _) => false,
236 }
237 }
238}
239
240impl Capability for LogsCap {
241 fn permits(&self, other: &Self) -> bool {
242 match (self, other) {
243 (LogsCap::Push, LogsCap::Push) => true,
244 (LogsCap::SetLevel, LogsCap::SetLevel) => true,
245 (_, _) => false,
246 }
247 }
248}
249
250#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Serialize, Deserialize)]
252pub struct CapSet<C: Capability + Ord>(BTreeSet<C>);
253
254impl<C: Capability + Ord> Default for CapSet<C> {
255 fn default() -> Self {
256 Self(BTreeSet::new())
257 }
258}
259
260impl<C: Capability + Ord> CapSet<C> {
261 pub fn new(set: impl IntoIterator<Item = impl Into<C>>) -> Self {
262 Self(BTreeSet::from_iter(set.into_iter().map(Into::into)))
263 }
264
265 pub fn iter(&self) -> impl Iterator<Item = &'_ C> + '_ {
266 self.0.iter()
267 }
268
269 pub fn is_empty(&self) -> bool {
270 self.0.is_empty()
271 }
272
273 pub fn len(&self) -> usize {
274 self.0.len()
275 }
276
277 pub fn contains(&self, cap: impl Into<C>) -> bool {
278 let cap = cap.into();
279 self.0.contains(&cap)
280 }
281
282 pub fn extend(&mut self, caps: impl IntoIterator<Item = impl Into<C>>) {
283 self.0.extend(caps.into_iter().map(Into::into));
284 }
285
286 pub fn insert(&mut self, cap: impl Into<C>) -> bool {
287 self.0.insert(cap.into())
288 }
289
290 pub fn from_strs<'a, E>(strs: impl IntoIterator<Item = &'a str>) -> Result<Self>
291 where
292 C: FromStr<Err = E>,
293 Result<C, E>: anyhow::Context<C, E>,
294 {
295 let mut caps = Self::default();
296 for s in strs {
297 let cap = C::from_str(s).with_context(|| format!("Unknown capability: {s}"))?;
298 caps.insert(cap);
299 }
300 Ok(caps)
301 }
302
303 pub fn to_strings(&self) -> Vec<String>
304 where
305 C: fmt::Display,
306 {
307 self.iter().map(ToString::to_string).collect()
308 }
309}
310
311impl<C: Capability + Ord> Capability for CapSet<C> {
312 fn permits(&self, other: &Self) -> bool {
313 other
314 .iter()
315 .all(|other_cap| self.iter().any(|self_cap| self_cap.permits(other_cap)))
316 }
317}
318
319#[cfg(not(target_arch = "wasm32"))]
321pub fn create_api_token_from_ssh_key(
322 user_ssh_key: &ssh_key::PrivateKey,
323 local_id: EndpointId,
324 max_age: Duration,
325 capability: Caps,
326) -> Result<Rcan<Caps>> {
327 let issuer: ed25519_dalek::SigningKey = user_ssh_key
328 .key_data()
329 .ed25519()
330 .context("only Ed25519 keys supported")?
331 .private
332 .clone()
333 .into();
334
335 let audience = local_id.as_verifying_key();
336 let can =
337 Rcan::issuing_builder(&issuer, audience, capability).sign(Expires::valid_for(max_age));
338 Ok(can)
339}
340
341pub fn create_grant_token(
345 local_secret: SecretKey,
346 remote_id: EndpointId,
347 max_age: Duration,
348 capability: Caps,
349) -> Result<Rcan<Caps>> {
350 let issuer = ed25519_dalek::SigningKey::from_bytes(&local_secret.to_bytes());
351 let audience = remote_id.as_verifying_key();
352 let can =
353 Rcan::issuing_builder(&issuer, audience, capability).sign(Expires::valid_for(max_age));
354 Ok(can)
355}
356
357pub fn create_api_token_from_secret_key(
359 private_key: SecretKey,
360 local_id: EndpointId,
361 max_age: Duration,
362 capability: Caps,
363) -> Result<Rcan<Caps>> {
364 let issuer = ed25519_dalek::SigningKey::from_bytes(&private_key.to_bytes());
365 let audience = local_id.as_verifying_key();
366 let can =
367 Rcan::issuing_builder(&issuer, audience, capability).sign(Expires::valid_for(max_age));
368 Ok(can)
369}
370
371#[cfg(test)]
372mod tests {
373 use super::*;
374
375 #[test]
376 fn smoke() {
377 let all = Caps::default()
378 .extend([RelayCap::Use])
379 .extend([MetricsCap::PutAny]);
380
381 println!("all: {all:?}");
383 let strings = all.to_strings();
384 println!("strings: {strings:?}");
385 let parsed = Caps::from_strs(strings.iter().map(|s| s.as_str())).unwrap();
386 assert_eq!(all, parsed);
387
388 let s = ["metrics:put-any", "relay:use"];
390 let caps = Caps::from_strs(s).unwrap();
391 assert_eq!(
392 caps,
393 Caps::new([MetricsCap::PutAny]).extend([RelayCap::Use])
394 );
395
396 let full = Caps::new([Cap::All]);
397
398 assert!(full.permits(&full));
399 assert!(full.permits(&all));
400 assert!(!all.permits(&full));
401
402 let metrics = Caps::new([MetricsCap::PutAny]);
403 let relay = Caps::new([RelayCap::Use]);
404
405 for cap in [&metrics, &relay] {
406 assert!(full.permits(cap));
407 assert!(all.permits(cap));
408 assert!(!cap.permits(&full));
409 assert!(!cap.permits(&all));
410 }
411
412 assert!(!metrics.permits(&relay));
413 assert!(!relay.permits(&metrics));
414 }
415
416 #[test]
417 fn client_caps() {
418 let client = Caps::new([Cap::Client]);
419
420 let all = Caps::new([Cap::All]);
421 let metrics = Caps::new([MetricsCap::PutAny]);
422 let relay = Caps::new([RelayCap::Use]);
423 assert!(client.permits(&metrics));
424 assert!(client.permits(&relay));
425 assert!(!client.permits(&all));
426 }
427}