1use std::collections::{BTreeSet, HashMap};
78use std::fmt;
79use std::future::Future;
80use std::sync::Arc;
81use std::time::Duration;
82
83use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, RequestContext, SystemClock};
84use adk_server::auth_bridge::{RequestContextError, RequestContextExtractor};
85use async_trait::async_trait;
86use axum::http::Method;
87use axum::http::request::Parts;
88use chrono::{DateTime, Utc};
89use serde::{Deserialize, Serialize};
90
91use crate::error::{KernelError, Result, UNAUTHORIZED_CODE, UNSUPPORTED_CODE};
92
93mod attachments;
94mod kinds;
95mod memory;
96#[cfg(feature = "postgres")]
97pub(crate) mod postgres;
98#[cfg(feature = "redis")]
99pub(crate) mod redis;
100pub(crate) mod secret;
101#[cfg(any(feature = "sqlite", feature = "postgres"))]
102pub(crate) mod sql;
103#[cfg(feature = "sqlite")]
104mod sqlite;
105
106pub use attachments::{AttachmentHolder, DeviceAttachment};
107pub use kinds::{DeviceKind, DeviceRoutes};
108pub use memory::InMemoryDeviceStore;
109#[cfg(feature = "postgres")]
110pub use postgres::PostgresDeviceStore;
111#[cfg(feature = "redis")]
112pub use redis::RedisDeviceStore;
113#[cfg(feature = "sqlite")]
114pub use sqlite::SqliteDeviceStore;
115
116pub const DEVICE_ID_METADATA: &str = "adk.device.id";
118pub const DEVICE_NAME_METADATA: &str = "adk.device.name";
120pub const DEVICE_SCOPES_METADATA: &str = "adk.device.scopes";
122pub const DEVICE_KIND_METADATA: &str = "adk.device.kind";
125
126const MAX_FAILED_CLAIMS: u64 = 20;
128const DEFAULT_RECHECK: Duration = Duration::from_secs(5);
130const MAX_NAME_CHARS: usize = 64;
132const MAX_DEVICE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60);
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
146#[serde(rename_all = "camelCase")]
147#[non_exhaustive]
148pub enum DeviceScope {
149 Decide,
151 Read,
154 Stop,
156}
157
158impl DeviceScope {
159 pub const ALL: [Self; 3] = [Self::Decide, Self::Read, Self::Stop];
161
162 pub fn as_str(self) -> &'static str {
164 match self {
165 Self::Decide => "decide",
166 Self::Read => "read",
167 Self::Stop => "stop",
168 }
169 }
170}
171
172impl fmt::Display for DeviceScope {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 f.write_str(self.as_str())
175 }
176}
177
178impl std::str::FromStr for DeviceScope {
179 type Err = KernelError;
180
181 fn from_str(text: &str) -> Result<Self> {
182 match text.trim().to_ascii_lowercase().as_str() {
183 "decide" => Ok(Self::Decide),
184 "read" => Ok(Self::Read),
185 "stop" => Ok(Self::Stop),
186 other => Err(KernelError::Config {
187 reason: format!("unknown device scope `{other}`: use decide, read or stop"),
188 }),
189 }
190 }
191}
192
193#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(rename_all = "camelCase")]
209#[non_exhaustive]
210pub struct DeviceRecord {
211 pub id: String,
213 pub name: String,
215 pub owner: String,
217 #[serde(default, skip_serializing_if = "Vec::is_empty")]
219 pub groups: Vec<String>,
220 pub scopes: Vec<DeviceScope>,
222 pub token_hash: String,
224 pub created_at: DateTime<Utc>,
226 pub expires_at: DateTime<Utc>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
230 pub revoked_at: Option<DateTime<Utc>>,
231 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub kind: Option<DeviceKind>,
234}
235
236impl DeviceRecord {
237 pub fn new(
239 id: impl Into<String>,
240 name: impl Into<String>,
241 owner: impl Into<String>,
242 token_hash: impl Into<String>,
243 created_at: DateTime<Utc>,
244 expires_at: DateTime<Utc>,
245 ) -> Self {
246 Self {
247 id: id.into(),
248 name: name.into(),
249 owner: owner.into(),
250 groups: Vec::new(),
251 scopes: DeviceScope::ALL.to_vec(),
252 token_hash: token_hash.into(),
253 created_at,
254 expires_at,
255 revoked_at: None,
256 kind: None,
257 }
258 }
259
260 #[must_use]
262 pub fn with_kind(mut self, kind: DeviceKind) -> Self {
263 self.kind = Some(kind);
264 self
265 }
266
267 pub fn kind(&self) -> DeviceKind {
269 self.kind.unwrap_or(DeviceKind::Terminal)
270 }
271
272 #[must_use]
274 pub fn with_scopes(mut self, scopes: impl IntoIterator<Item = DeviceScope>) -> Self {
275 self.scopes = scopes.into_iter().collect::<BTreeSet<_>>().into_iter().collect();
276 self
277 }
278
279 #[must_use]
281 pub fn with_groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
282 self.groups = groups.into_iter().map(Into::into).collect();
283 self
284 }
285
286 pub fn is_active(&self, now: DateTime<Utc>) -> bool {
288 self.revoked_at.is_none() && now < self.expires_at
289 }
290
291 pub fn has_scope(&self, scope: DeviceScope) -> bool {
293 self.scopes.contains(&scope)
294 }
295
296 pub fn view(&self, now: DateTime<Utc>) -> DeviceView {
298 let state = match (self.revoked_at, now < self.expires_at) {
299 (Some(_), _) => DeviceState::Revoked,
300 (None, true) => DeviceState::Active,
301 (None, false) => DeviceState::Expired,
302 };
303 DeviceView {
304 id: self.id.clone(),
305 name: self.name.clone(),
306 owner: self.owner.clone(),
307 scopes: self.scopes.clone(),
308 created_at: self.created_at,
309 expires_at: self.expires_at,
310 revoked_at: self.revoked_at,
311 state,
312 kind: self.kind(),
313 }
314 }
315}
316
317#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
327#[serde(rename_all = "camelCase")]
328#[non_exhaustive]
329pub enum DeviceState {
330 Active,
332 Expired,
334 Revoked,
336}
337
338#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
340#[serde(rename_all = "camelCase")]
341#[non_exhaustive]
342pub struct DeviceView {
343 pub id: String,
345 pub name: String,
347 pub owner: String,
349 pub scopes: Vec<DeviceScope>,
351 pub created_at: DateTime<Utc>,
353 pub expires_at: DateTime<Utc>,
355 #[serde(default, skip_serializing_if = "Option::is_none")]
357 pub revoked_at: Option<DateTime<Utc>>,
358 pub state: DeviceState,
360 #[serde(default = "terminal")]
362 pub kind: DeviceKind,
363}
364
365fn terminal() -> DeviceKind {
366 DeviceKind::Terminal
367}
368
369#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
371#[serde(rename_all = "camelCase")]
372#[non_exhaustive]
373pub struct PairingCode {
374 pub code_hash: String,
376 pub owner: String,
378 #[serde(default, skip_serializing_if = "Vec::is_empty")]
380 pub groups: Vec<String>,
381 pub scopes: Vec<DeviceScope>,
383 #[serde(default, skip_serializing_if = "Option::is_none")]
385 pub name: Option<String>,
386 pub device_ttl_secs: u64,
388 pub issued_at: DateTime<Utc>,
390 pub expires_at: DateTime<Utc>,
392 #[serde(default, skip_serializing_if = "Option::is_none")]
394 pub kind: Option<DeviceKind>,
395}
396
397impl PairingCode {
398 pub fn new(
400 code_hash: impl Into<String>,
401 owner: impl Into<String>,
402 device_ttl: Duration,
403 issued_at: DateTime<Utc>,
404 expires_at: DateTime<Utc>,
405 ) -> Self {
406 Self {
407 code_hash: code_hash.into(),
408 owner: owner.into(),
409 groups: Vec::new(),
410 scopes: DeviceScope::ALL.to_vec(),
411 name: None,
412 device_ttl_secs: device_ttl.as_secs(),
413 issued_at,
414 expires_at,
415 kind: None,
416 }
417 }
418}
419
420#[async_trait]
427pub trait DeviceStore: Send + Sync {
428 async fn put_code(&self, code: PairingCode) -> Result<()>;
430
431 async fn take_code(&self, code_hash: &str) -> Result<Option<PairingCode>>;
434
435 async fn prune_codes(&self, before: DateTime<Utc>) -> Result<usize>;
437
438 async fn clear_codes(&self) -> Result<usize>;
440
441 async fn put_device(&self, device: DeviceRecord) -> Result<()>;
443
444 async fn get_device(&self, id: &str) -> Result<Option<DeviceRecord>>;
446
447 async fn list_devices(&self) -> Result<Vec<DeviceRecord>>;
449
450 async fn count_claim_attempt(&self) -> Result<u64>;
454
455 async fn reset_claim_attempts(&self) -> Result<()>;
457
458 async fn put_attachment(&self, attachment: DeviceAttachment) -> Result<()> {
462 let _ = attachment;
463 Err(no_attachments())
464 }
465
466 async fn put_attachment_if_absent(&self, attachment: DeviceAttachment) -> Result<bool> {
469 let _ = attachment;
470 Err(no_attachments())
471 }
472
473 async fn attachments(
475 &self,
476 holder: &AttachmentHolder,
477 kind: &str,
478 ) -> Result<Vec<DeviceAttachment>> {
479 let _ = (holder, kind);
480 Err(no_attachments())
481 }
482
483 async fn remove_attachment(
485 &self,
486 holder: &AttachmentHolder,
487 kind: &str,
488 key: &str,
489 ) -> Result<bool> {
490 let _ = (holder, kind, key);
491 Err(no_attachments())
492 }
493
494 async fn remove_attachments(&self, holder: &AttachmentHolder) -> Result<usize> {
496 let _ = holder;
497 Err(no_attachments())
498 }
499}
500
501fn no_attachments() -> KernelError {
503 KernelError::Core(AdkError::new(
504 ErrorComponent::Server,
505 ErrorCategory::Unsupported,
506 UNSUPPORTED_CODE,
507 "this device store keeps no attachments: use the in-memory, SQLite, PostgreSQL or Redis \
508 device store",
509 ))
510}
511
512#[derive(Debug, Clone, PartialEq, Eq)]
526#[non_exhaustive]
527pub struct IssueCode {
528 pub owner: String,
530 pub groups: Vec<String>,
532 pub scopes: Vec<DeviceScope>,
534 pub name: Option<String>,
536 pub device_ttl: Option<Duration>,
538 pub kind: Option<DeviceKind>,
540}
541
542impl IssueCode {
543 pub fn new(
546 owner: impl Into<String>,
547 groups: impl IntoIterator<Item = impl Into<String>>,
548 ) -> Self {
549 Self {
550 owner: owner.into(),
551 groups: groups.into_iter().map(Into::into).collect(),
552 scopes: Vec::new(),
553 name: None,
554 device_ttl: None,
555 kind: None,
556 }
557 }
558
559 #[must_use]
561 pub fn with_kind(mut self, kind: DeviceKind) -> Self {
562 self.kind = Some(kind);
563 self
564 }
565
566 #[must_use]
568 pub fn with_scopes(mut self, scopes: impl IntoIterator<Item = DeviceScope>) -> Self {
569 self.scopes = scopes.into_iter().collect();
570 self
571 }
572
573 #[must_use]
575 pub fn with_name(mut self, name: impl Into<String>) -> Self {
576 self.name = Some(name.into());
577 self
578 }
579
580 #[must_use]
582 pub fn with_device_ttl(mut self, ttl: Duration) -> Self {
583 self.device_ttl = Some(ttl);
584 self
585 }
586
587 #[must_use]
600 pub fn normalized(mut self) -> Self {
601 self.scopes = if self.scopes.is_empty() {
602 DeviceScope::ALL.to_vec()
603 } else {
604 self.scopes.iter().copied().collect::<BTreeSet<_>>().into_iter().collect()
605 };
606 self.name = self
607 .name
608 .map(|name| secret::clean_name(&name, MAX_NAME_CHARS))
609 .filter(|name| !name.is_empty());
610 self
611 }
612}
613
614pub(crate) struct PendingClaim {
617 code: PairingCode,
618 device: DeviceRecord,
619 token: String,
620}
621
622impl PendingClaim {
623 pub(crate) fn device(&self) -> &DeviceRecord {
625 &self.device
626 }
627}
628
629#[derive(Debug, Clone, PartialEq, Eq)]
632pub(crate) struct DeviceAdmission {
633 pub(crate) device: String,
634}
635
636#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
638#[serde(rename_all = "camelCase")]
639#[non_exhaustive]
640pub struct IssuedCode {
641 pub code: String,
643 pub expires_at: DateTime<Utc>,
645 pub scopes: Vec<DeviceScope>,
647 #[serde(default, skip_serializing_if = "Option::is_none")]
651 pub url: Option<String>,
652 #[serde(default)]
654 pub device_ttl_secs: u64,
655}
656
657#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
659#[serde(rename_all = "camelCase")]
660#[non_exhaustive]
661pub struct ClaimedDevice {
662 pub device: DeviceView,
664 pub token: String,
666}
667
668impl fmt::Debug for ClaimedDevice {
669 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670 f.debug_struct("ClaimedDevice").field("device", &self.device).finish_non_exhaustive()
671 }
672}
673
674#[derive(Clone)]
680pub struct Pairing {
681 inner: Arc<Inner>,
682}
683
684struct Inner {
685 store: Arc<dyn DeviceStore>,
686 #[cfg(feature = "channels")]
687 channels: Option<Arc<dyn crate::channels::ChannelBindingStore>>,
688 code_ttl: Duration,
689 device_ttl: Duration,
690 home_url: Option<String>,
691 clock: Arc<dyn Clock>,
692 recheck: Duration,
693 revoked: tokio::sync::broadcast::Sender<String>,
694 routes: Option<DeviceRoutes>,
695}
696
697impl fmt::Debug for Pairing {
698 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
699 f.debug_struct("Pairing")
700 .field("code_ttl", &self.inner.code_ttl)
701 .field("device_ttl", &self.inner.device_ttl)
702 .field("home_url", &self.inner.home_url)
703 .finish_non_exhaustive()
704 }
705}
706
707impl Pairing {
708 pub const DEFAULT_CODE_TTL: Duration = Duration::from_secs(10 * 60);
710 pub const DEFAULT_DEVICE_TTL: Duration = Duration::from_secs(90 * 24 * 60 * 60);
712
713 pub fn new(store: Arc<dyn DeviceStore>) -> Self {
715 Self {
716 inner: Arc::new(Inner {
717 store,
718 #[cfg(feature = "channels")]
719 channels: None,
720 code_ttl: Self::DEFAULT_CODE_TTL,
721 device_ttl: Self::DEFAULT_DEVICE_TTL,
722 home_url: None,
723 clock: Arc::new(SystemClock),
724 recheck: DEFAULT_RECHECK,
725 revoked: tokio::sync::broadcast::channel(64).0,
726 routes: None,
727 }),
728 }
729 }
730
731 fn rebuild(self, change: impl FnOnce(&mut Inner)) -> Self {
732 let inner = Arc::try_unwrap(self.inner).unwrap_or_else(|shared| Inner {
733 store: shared.store.clone(),
734 #[cfg(feature = "channels")]
735 channels: shared.channels.clone(),
736 code_ttl: shared.code_ttl,
737 device_ttl: shared.device_ttl,
738 home_url: shared.home_url.clone(),
739 clock: shared.clock.clone(),
740 recheck: shared.recheck,
741 revoked: shared.revoked.clone(),
742 routes: shared.routes.clone(),
743 });
744 let mut inner = inner;
745 change(&mut inner);
746 Self { inner: Arc::new(inner) }
747 }
748
749 #[must_use]
769 pub fn with_device_routes(self, routes: DeviceRoutes) -> Self {
770 self.rebuild(|inner| inner.routes = Some(routes))
771 }
772
773 pub fn scope_for(&self, method: &Method, path: &str) -> Option<DeviceScope> {
776 device_scope_for(method, path)
777 .or_else(|| self.inner.routes.as_ref().and_then(|routes| routes(method, path)))
778 }
779
780 #[must_use]
782 pub fn with_code_ttl(self, ttl: Duration) -> Self {
783 self.rebuild(|inner| inner.code_ttl = ttl)
784 }
785
786 #[must_use]
788 pub fn with_device_ttl(self, ttl: Duration) -> Self {
789 self.rebuild(|inner| inner.device_ttl = ttl.min(MAX_DEVICE_TTL))
790 }
791
792 #[must_use]
795 pub fn with_home_url(self, url: impl Into<String>) -> Self {
796 let url = url.into().trim_end_matches('/').to_string();
797 self.rebuild(|inner| inner.home_url = Some(url))
798 }
799
800 #[must_use]
802 pub fn with_clock(self, clock: Arc<dyn Clock>) -> Self {
803 self.rebuild(|inner| inner.clock = clock)
804 }
805
806 #[must_use]
809 pub fn with_revocation_check(self, interval: Duration) -> Self {
810 self.rebuild(|inner| inner.recheck = interval.max(Duration::from_millis(10)))
811 }
812
813 #[cfg(feature = "channels")]
816 #[must_use]
817 pub fn with_channel_bindings(
818 self,
819 store: Arc<dyn crate::channels::ChannelBindingStore>,
820 ) -> Self {
821 self.rebuild(|inner| inner.channels = Some(store))
822 }
823
824 #[cfg(feature = "channels")]
826 pub fn channel_bindings(&self) -> Option<&Arc<dyn crate::channels::ChannelBindingStore>> {
827 self.inner.channels.as_ref()
828 }
829
830 pub fn store(&self) -> &Arc<dyn DeviceStore> {
832 &self.inner.store
833 }
834
835 pub fn home_url(&self) -> Option<&str> {
837 self.inner.home_url.as_deref()
838 }
839
840 pub fn now(&self) -> DateTime<Utc> {
842 self.inner.clock.now()
843 }
844
845 pub async fn issue(&self, request: IssueCode) -> Result<IssuedCode> {
853 let device_ttl = self.check(&request)?;
854 let request = request.normalized();
855 let phone = request.kind == Some(DeviceKind::Phone);
857 let now = self.now();
858 self.inner.store.prune_codes(now).await?;
859 let code = secret::new_code()?;
860 let expires_at = now + chrono::Duration::from_std(self.inner.code_ttl).unwrap_or_default();
861 let mut stored =
862 PairingCode::new(secret::code_hash(&code), request.owner, device_ttl, now, expires_at);
863 stored.groups = request.groups;
864 stored.scopes = request.scopes.clone();
865 stored.name = request.name;
866 stored.kind = request.kind;
867 self.inner.store.put_code(stored).await?;
868 self.inner.store.reset_claim_attempts().await?;
870 let url = self
871 .inner
872 .home_url
873 .as_ref()
874 .filter(|_| phone)
875 .map(|home| format!("{home}/pair#code={code}"));
876 Ok(IssuedCode {
877 code,
878 expires_at,
879 scopes: request.scopes,
880 url,
881 device_ttl_secs: device_ttl.as_secs(),
882 })
883 }
884
885 pub(crate) fn check(&self, request: &IssueCode) -> Result<Duration> {
893 if request.owner.trim().is_empty() {
894 return Err(KernelError::Config {
895 reason: "a pairing code needs the person the device acts for".into(),
896 });
897 }
898 let device_ttl = request.device_ttl.unwrap_or(self.inner.device_ttl);
899 if device_ttl.is_zero() || device_ttl > MAX_DEVICE_TTL {
900 return Err(KernelError::Config {
901 reason: format!(
902 "a device stays paired for at most 365 days and longer than none, not {} \
903 days: pass `adk-rust pair --days` between 1 and 365",
904 device_ttl.as_secs() / 86_400
905 ),
906 });
907 }
908 Ok(device_ttl)
909 }
910
911 pub async fn claim(&self, code: &str, name: Option<&str>) -> Result<ClaimedDevice> {
924 let pending = self.take_for_claim(code, name).await?;
925 self.finish_claim(pending).await
926 }
927
928 pub(crate) async fn take_for_claim(
930 &self,
931 code: &str,
932 name: Option<&str>,
933 ) -> Result<PendingClaim> {
934 let wrong = || KernelError::Unauthorized {
935 reason: "the pairing code is wrong, used or expired: run `adk-rust pair` for a new \
936 one"
937 .into(),
938 };
939 let store = &self.inner.store;
940 let attempts = store.count_claim_attempt().await?;
941 if attempts > MAX_FAILED_CLAIMS {
942 let cleared = store.clear_codes().await?;
945 if cleared > 0 {
946 tracing::warn!(
947 pairing.cleared = cleared,
948 "too many claims without a success; every waiting code was cancelled"
949 );
950 }
951 return Err(KernelError::Unauthorized {
952 reason: "too many pairing codes were wrong, so every waiting code was \
953 cancelled: run `adk-rust pair` for a new one"
954 .into(),
955 });
956 }
957 let now = self.now();
958 let taken = store.take_code(&secret::code_hash(code)).await?;
959 let Some(code) = taken.filter(|code| now < code.expires_at) else {
960 return Err(wrong());
961 };
962 if let Err(error) = store.reset_claim_attempts().await {
963 tracing::warn!(error = %error, "the count of pairing claims could not be reset");
964 }
965 let id = secret::new_device_id()?;
966 let (token, token_hash) = secret::new_token(&id)?;
967 let name = code
968 .name
969 .clone()
970 .or_else(|| name.map(|name| secret::clean_name(name, MAX_NAME_CHARS)))
971 .filter(|name| !name.is_empty())
972 .unwrap_or_else(|| "Device".to_string());
973 let ttl = Duration::from_secs(code.device_ttl_secs).min(MAX_DEVICE_TTL);
974 let device = DeviceRecord::new(
975 id,
976 name,
977 code.owner.clone(),
978 token_hash,
979 now,
980 now + chrono::Duration::from_std(ttl).unwrap_or_default(),
981 )
982 .with_scopes(code.scopes.clone())
983 .with_groups(code.groups.clone());
984 let device = DeviceRecord { kind: code.kind, ..device };
986 Ok(PendingClaim { code, device, token })
987 }
988
989 pub(crate) async fn finish_claim(&self, pending: PendingClaim) -> Result<ClaimedDevice> {
992 if let Err(error) = self.inner.store.put_device(pending.device.clone()).await {
993 self.abandon_claim(pending).await;
994 return Err(error);
995 }
996 Ok(ClaimedDevice { device: pending.device.view(self.now()), token: pending.token })
997 }
998
999 pub(crate) async fn abandon_claim(&self, pending: PendingClaim) {
1001 if let Err(error) = self.inner.store.put_code(pending.code).await {
1002 tracing::error!(error = %error, "a pairing code could not be put back");
1003 }
1004 }
1005
1006 pub fn until_device_ends(&self, id: String) -> impl Future<Output = ()> + Send + 'static {
1029 let pairing = self.clone();
1030 let mut revoked = self.inner.revoked.subscribe();
1031 async move {
1032 loop {
1033 let wait = match pairing.inner.store.get_device(&id).await {
1034 Ok(Some(device)) if device.is_active(pairing.now()) => {
1035 let left = (device.expires_at - pairing.now()).to_std().unwrap_or_default();
1036 left.min(pairing.inner.recheck)
1037 }
1038 Ok(_) => return,
1039 Err(error) => {
1040 tracing::warn!(device.id = %id, error = %error, "a device could not be re-read");
1041 pairing.inner.recheck
1042 }
1043 };
1044 tokio::select! {
1045 () = tokio::time::sleep(wait) => {}
1046 message = revoked.recv() => match message {
1047 Ok(gone) if gone == id => return,
1048 Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
1049 Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
1050 },
1051 }
1052 }
1053 }
1054 }
1055
1056 pub async fn authenticate(&self, token: &str) -> Result<DeviceRecord> {
1063 let unknown = || KernelError::Unauthorized {
1064 reason: "the device token is not one this kernel issued: pair the device again \
1065 with `adk-rust pair`"
1066 .into(),
1067 };
1068 let (id, secret_text) = secret::parse_token(token).ok_or_else(unknown)?;
1069 let device = self.inner.store.get_device(id).await?.ok_or_else(unknown)?;
1070 if !secret::constant_time_eq(
1071 secret::digest(secret_text).as_bytes(),
1072 device.token_hash.as_bytes(),
1073 ) {
1074 return Err(unknown());
1075 }
1076 if let Some(at) = device.revoked_at {
1077 return Err(KernelError::Unauthorized {
1078 reason: format!(
1079 "{} was removed on {}: pair it again with `adk-rust pair`",
1080 device.name,
1081 at.format("%Y-%m-%d")
1082 ),
1083 });
1084 }
1085 if self.now() >= device.expires_at {
1086 return Err(KernelError::Unauthorized {
1087 reason: format!(
1088 "{}'s pairing ended on {}: pair it again with `adk-rust pair`",
1089 device.name,
1090 device.expires_at.format("%Y-%m-%d")
1091 ),
1092 });
1093 }
1094 Ok(device)
1095 }
1096
1097 pub async fn authorize(
1112 &self,
1113 token: &str,
1114 method: &Method,
1115 path: &str,
1116 ) -> Result<RequestContext> {
1117 let device = self.authenticate(token).await?;
1118 match self.scope_for(method, path) {
1119 Some(scope) if device.has_scope(scope) => Ok(device_context(&device)),
1120 Some(scope) => Err(forbidden(format!(
1121 "{} was paired without the `{scope}` scope, which {method} {path} needs; pair it \
1122 again with `adk-rust pair --scope {scope}`",
1123 device.name
1124 ))),
1125 None => Err(forbidden(format!(
1126 "a paired device may not call {method} {path}: devices read, answer decisions \
1127 and stop everything; anything else happens in the home or on the kernel's own \
1128 terminal"
1129 ))),
1130 }
1131 }
1132
1133 pub async fn devices(&self) -> Result<Vec<DeviceRecord>> {
1139 self.inner.store.list_devices().await
1140 }
1141
1142 pub async fn revoke(&self, id: &str) -> Result<DeviceRecord> {
1152 let Some(mut device) = self.inner.store.get_device(id).await? else {
1153 return Err(KernelError::Core(AdkError::new(
1154 ErrorComponent::Server,
1155 ErrorCategory::NotFound,
1156 crate::error::NOT_FOUND_CODE,
1157 format!("no paired device {id}: list them with `adk-rust pair list`"),
1158 )));
1159 };
1160 if device.revoked_at.is_none() {
1161 device.revoked_at = Some(self.now());
1162 self.inner.store.put_device(device.clone()).await?;
1163 }
1164 match self
1166 .inner
1167 .store
1168 .remove_attachments(&AttachmentHolder::Device(device.id.clone()))
1169 .await
1170 {
1171 Ok(_) => {}
1172 Err(KernelError::Core(error)) if error.category == ErrorCategory::Unsupported => {}
1173 Err(error) => return Err(error),
1174 }
1175 let _ = self.inner.revoked.send(device.id.clone());
1177 Ok(device)
1178 }
1179}
1180
1181pub(crate) fn forbidden(message: String) -> KernelError {
1183 KernelError::Core(AdkError::new(
1184 ErrorComponent::Server,
1185 ErrorCategory::Forbidden,
1186 UNAUTHORIZED_CODE,
1187 message,
1188 ))
1189}
1190
1191fn device_context(device: &DeviceRecord) -> RequestContext {
1193 let scopes = device.scopes.iter().map(|scope| scope.as_str()).collect::<Vec<_>>().join(",");
1194 RequestContext {
1195 user_id: device.owner.clone(),
1196 scopes: device.groups.clone(),
1197 metadata: HashMap::from([
1198 (DEVICE_ID_METADATA.to_string(), device.id.clone()),
1199 (DEVICE_NAME_METADATA.to_string(), device.name.clone()),
1200 (DEVICE_SCOPES_METADATA.to_string(), scopes),
1201 (DEVICE_KIND_METADATA.to_string(), device.kind().as_str().to_string()),
1202 ]),
1203 }
1204}
1205
1206pub fn device_scope_for(method: &Method, path: &str) -> Option<DeviceScope> {
1222 let path = path.split(['?', '#']).next().unwrap_or_default();
1223 let path = path.strip_prefix(crate::control::paths::API_PREFIX).unwrap_or(path);
1224 let segments: Vec<&str> = path.split('/').filter(|segment| !segment.is_empty()).collect();
1225 match (method.as_str(), segments.as_slice()) {
1226 ("GET", ["kernel", "health" | "processes" | "events" | "agenda"])
1227 | ("POST", ["kernel", "attach", _])
1228 | (
1232 "GET",
1233 ["kernel", "settings" | "away" | "memory" | "record" | "agents"]
1234 | ["kernel", "settings" | "agents", _]
1235 | ["kernel", "away", "lines", _]
1236 | ["kernel", "record", "check"],
1237 )
1238 | ("POST", ["kernel", "away", "seen"])
1239 | ("GET", ["approvals"] | ["approvals", _]) => Some(DeviceScope::Read),
1240 ("POST", ["approvals", id, "decide"]) if *id != "delegations" => Some(DeviceScope::Decide),
1241 ("POST", ["kernel", "freeze"]) => Some(DeviceScope::Stop),
1242 _ => None,
1243 }
1244}
1245
1246pub(crate) const TAKE_OVER_TOOL: &str = "harness:take-over";
1249
1250pub(crate) fn device_token(headers: &axum::http::HeaderMap) -> Option<&str> {
1252 let value = headers.get(axum::http::header::AUTHORIZATION)?.to_str().ok()?;
1253 let token = value.strip_prefix("Bearer ").or_else(|| value.strip_prefix("bearer "))?.trim();
1254 token.starts_with(secret::TOKEN_PREFIX).then_some(token)
1255}
1256
1257#[derive(Clone)]
1280pub struct DeviceTokenExtractor {
1281 pairing: Pairing,
1282 fallback: Option<Arc<dyn RequestContextExtractor>>,
1283}
1284
1285impl fmt::Debug for DeviceTokenExtractor {
1286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1287 f.debug_struct("DeviceTokenExtractor")
1288 .field("pairing", &self.pairing)
1289 .field("fallback", &self.fallback.is_some())
1290 .finish()
1291 }
1292}
1293
1294impl DeviceTokenExtractor {
1295 pub fn new(pairing: Pairing) -> Self {
1297 Self { pairing, fallback: None }
1298 }
1299
1300 #[must_use]
1302 pub fn with_fallback(mut self, fallback: Arc<dyn RequestContextExtractor>) -> Self {
1303 self.fallback = Some(fallback);
1304 self
1305 }
1306}
1307
1308#[async_trait]
1309impl RequestContextExtractor for DeviceTokenExtractor {
1310 async fn extract(
1311 &self,
1312 parts: &Parts,
1313 ) -> std::result::Result<RequestContext, RequestContextError> {
1314 let Some(token) = device_token(&parts.headers) else {
1315 return match &self.fallback {
1316 Some(fallback) => fallback.extract(parts).await,
1317 None => Err(RequestContextError::MissingAuth),
1318 };
1319 };
1320 let path =
1321 parts.uri.path_and_query().map_or_else(|| parts.uri.path(), |path| path.as_str());
1322 match self.pairing.authorize(token, &parts.method, path).await {
1323 Ok(context)
1326 if self.pairing.scope_for(&parts.method, path) == Some(DeviceScope::Decide)
1327 && parts.extensions.get::<DeviceAdmission>().map(|admitted| &admitted.device)
1328 != context.metadata.get(DEVICE_ID_METADATA) =>
1329 {
1330 Err(RequestContextError::InvalidToken(
1331 "a device's decision is admitted only behind adk_kernel::control::guard_devices, \
1332 which checks its risk and records it; layer it on the app"
1333 .into(),
1334 ))
1335 }
1336 Ok(context) => Ok(context),
1337 Err(error @ (KernelError::Store { .. } | KernelError::Io(_))) => {
1338 Err(RequestContextError::ExtractionFailed(error.to_string()))
1339 }
1340 Err(error) => Err(RequestContextError::InvalidToken(error.to_string())),
1341 }
1342 }
1343}
1344
1345#[cfg(test)]
1346mod tests {
1347 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
1348
1349 use super::*;
1350
1351 fn pairing() -> Pairing {
1352 Pairing::new(Arc::new(InMemoryDeviceStore::new()))
1353 }
1354
1355 #[derive(Default)]
1358 struct Faulty {
1359 inner: InMemoryDeviceStore,
1360 lookups: AtomicUsize,
1361 slow: AtomicBool,
1362 fail_put_device: AtomicBool,
1363 fail_clear: AtomicBool,
1364 }
1365
1366 fn down() -> KernelError {
1367 KernelError::Store { backend: "test", reason: "down".into() }
1368 }
1369
1370 #[async_trait]
1371 impl DeviceStore for Faulty {
1372 async fn put_code(&self, code: PairingCode) -> Result<()> {
1373 self.inner.put_code(code).await
1374 }
1375 async fn take_code(&self, code_hash: &str) -> Result<Option<PairingCode>> {
1376 self.lookups.fetch_add(1, Ordering::SeqCst);
1377 if self.slow.load(Ordering::SeqCst) {
1378 tokio::time::sleep(Duration::from_millis(20)).await;
1379 }
1380 self.inner.take_code(code_hash).await
1381 }
1382 async fn prune_codes(&self, before: DateTime<Utc>) -> Result<usize> {
1383 self.inner.prune_codes(before).await
1384 }
1385 async fn clear_codes(&self) -> Result<usize> {
1386 if self.fail_clear.load(Ordering::SeqCst) {
1387 return Err(down());
1388 }
1389 self.inner.clear_codes().await
1390 }
1391 async fn put_device(&self, device: DeviceRecord) -> Result<()> {
1392 if self.fail_put_device.swap(false, Ordering::SeqCst) {
1393 return Err(down());
1394 }
1395 self.inner.put_device(device).await
1396 }
1397 async fn get_device(&self, id: &str) -> Result<Option<DeviceRecord>> {
1398 self.inner.get_device(id).await
1399 }
1400 async fn list_devices(&self) -> Result<Vec<DeviceRecord>> {
1401 self.inner.list_devices().await
1402 }
1403 async fn count_claim_attempt(&self) -> Result<u64> {
1404 self.inner.count_claim_attempt().await
1405 }
1406 async fn reset_claim_attempts(&self) -> Result<()> {
1407 self.inner.reset_claim_attempts().await
1408 }
1409 }
1410
1411 #[tokio::test]
1414 async fn only_a_phone_s_code_carries_the_pairing_link() {
1415 let pairing = pairing().with_home_url("https://home.example/ui/");
1416 let phone = pairing
1417 .issue(IssueCode::new("ana", ["operator"]).with_kind(DeviceKind::Phone))
1418 .await
1419 .unwrap();
1420 assert_eq!(phone.url, Some(format!("https://home.example/ui/pair#code={}", phone.code)));
1421 for kind in [None, Some(DeviceKind::Terminal), Some(DeviceKind::Tray)] {
1422 let request = IssueCode::new("ana", ["operator"]);
1423 let request = match kind {
1424 Some(kind) => request.with_kind(kind),
1425 None => request,
1426 };
1427 assert_eq!(pairing.issue(request).await.unwrap().url, None, "{kind:?}");
1428 }
1429 }
1430
1431 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1434 async fn concurrent_wrong_claims_are_counted_before_they_are_checked() {
1435 let store = Arc::new(Faulty::default());
1436 store.slow.store(true, Ordering::SeqCst);
1437 let pairing = Pairing::new(store.clone());
1438 pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1439 let mut claims = Vec::new();
1440 for guess in 0..100 {
1441 let pairing = pairing.clone();
1442 claims.push(tokio::spawn(async move {
1443 pairing.claim(&format!("0000-0000-{guess:04}"), None).await.is_err()
1444 }));
1445 }
1446 for claim in claims {
1447 assert!(claim.await.unwrap());
1448 }
1449 let lookups = store.lookups.load(Ordering::SeqCst);
1450 assert!(lookups <= MAX_FAILED_CLAIMS as usize, "{lookups} guesses reached the codes");
1451 }
1452
1453 #[tokio::test]
1455 async fn replicas_share_the_count_of_wrong_codes() {
1456 let store: Arc<dyn DeviceStore> = Arc::new(InMemoryDeviceStore::new());
1457 let (first, second) = (Pairing::new(store.clone()), Pairing::new(store));
1458 let issued = first.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1459 for _ in 0..MAX_FAILED_CLAIMS / 2 {
1460 assert!(first.claim("0000-0000", None).await.is_err());
1461 assert!(second.claim("0000-0000", None).await.is_err());
1462 }
1463 assert!(second.claim(&issued.code, None).await.is_err(), "the shared lockout fired");
1464 }
1465
1466 #[tokio::test]
1468 async fn a_lockout_whose_clear_fails_keeps_refusing() {
1469 let store = Arc::new(Faulty::default());
1470 store.fail_clear.store(true, Ordering::SeqCst);
1471 let pairing = Pairing::new(store.clone());
1472 let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1473 for _ in 0..=MAX_FAILED_CLAIMS {
1474 assert!(pairing.claim("0000-0000", None).await.is_err());
1475 }
1476 assert!(pairing.claim(&issued.code, None).await.is_err(), "still locked out");
1477 }
1478
1479 #[tokio::test]
1481 async fn a_claim_whose_device_cannot_be_stored_keeps_its_code() {
1482 let store = Arc::new(Faulty::default());
1483 let pairing = Pairing::new(store.clone());
1484 let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1485 store.fail_put_device.store(true, Ordering::SeqCst);
1486 assert!(matches!(pairing.claim(&issued.code, None).await, Err(KernelError::Store { .. })));
1487 assert!(pairing.claim(&issued.code, None).await.is_ok(), "the retry pairs");
1488 }
1489
1490 #[tokio::test]
1492 async fn a_lockout_holds_until_the_next_code() {
1493 let pairing = pairing();
1494 let first = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1495 for _ in 0..MAX_FAILED_CLAIMS {
1496 assert!(pairing.claim("0000-0000-0000", None).await.is_err());
1497 }
1498 let error = pairing.claim(&first.code, None).await.unwrap_err();
1499 assert!(error.to_string().contains("too many"), "{error}");
1500 let second = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1501 assert!(pairing.claim(&first.code, None).await.is_err(), "the first code was cancelled");
1502 assert!(pairing.claim(&second.code, None).await.is_ok(), "a new code pairs");
1503 }
1504
1505 #[tokio::test]
1508 async fn the_extractor_alone_refuses_a_device_decision() {
1509 let pairing = pairing();
1510 let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1511 let token = pairing.claim(&issued.code, None).await.unwrap().token;
1512 let extractor = DeviceTokenExtractor::new(pairing);
1513 let request = axum::http::Request::builder()
1514 .method(Method::POST)
1515 .uri("/api/approvals/a1/decide")
1516 .header("authorization", format!("Bearer {token}"))
1517 .body(())
1518 .unwrap();
1519 let (parts, ()) = request.into_parts();
1520 assert!(extractor.extract(&parts).await.is_err(), "decide needs the guard");
1521 let request = axum::http::Request::builder()
1522 .uri("/api/approvals")
1523 .header("authorization", format!("Bearer {token}"))
1524 .body(())
1525 .unwrap();
1526 let (parts, ()) = request.into_parts();
1527 assert!(extractor.extract(&parts).await.is_ok(), "read needs no guard");
1528 }
1529
1530 #[tokio::test]
1531 async fn a_code_pairs_one_device_with_its_scopes() {
1532 let pairing = pairing();
1533 let issued = pairing
1534 .issue(IssueCode::new("ana", ["operator"]).with_scopes([DeviceScope::Read]))
1535 .await
1536 .unwrap();
1537 assert_eq!(issued.scopes, [DeviceScope::Read]);
1538 assert_eq!(issued.url, None);
1539 let claimed = pairing.claim(&issued.code.to_lowercase(), Some("Pixel")).await.unwrap();
1540 assert_eq!(claimed.device.name, "Pixel");
1541 assert_eq!(claimed.device.scopes, [DeviceScope::Read]);
1542 let device = pairing.authenticate(&claimed.token).await.unwrap();
1543 assert_eq!(
1544 (device.owner.as_str(), device.groups.as_slice()),
1545 ("ana", &["operator".to_string()][..])
1546 );
1547 assert!(pairing.claim(&issued.code, None).await.is_err());
1548 }
1549
1550 #[tokio::test]
1551 async fn the_store_never_holds_the_code_or_the_token() {
1552 let store = Arc::new(InMemoryDeviceStore::new());
1553 let pairing = Pairing::new(store.clone());
1554 let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1555 let claimed = pairing.claim(&issued.code, None).await.unwrap();
1556 let stored = serde_json::to_string(&store.list_devices().await.unwrap()).unwrap();
1557 let (_, secret) = secret::parse_token(&claimed.token).unwrap();
1558 assert!(!stored.contains(secret));
1559 assert!(!stored.contains(&issued.code));
1560 }
1561
1562 #[tokio::test]
1563 async fn revoked_and_expired_tokens_are_refused() {
1564 let clock = adk_core::ManualClock::new(Utc::now());
1565 let pairing =
1566 pairing().with_device_ttl(Duration::from_secs(60)).with_clock(Arc::new(clock.clone()));
1567 let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1568 let claimed = pairing.claim(&issued.code, None).await.unwrap();
1569 pairing.revoke(&claimed.device.id).await.unwrap();
1570 let error = pairing.authenticate(&claimed.token).await.unwrap_err();
1571 assert!(error.to_string().contains("was removed"), "{error}");
1572
1573 let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1574 let claimed = pairing.claim(&issued.code, None).await.unwrap();
1575 clock.advance(Duration::from_secs(61));
1576 let error = pairing.authenticate(&claimed.token).await.unwrap_err();
1577 assert!(error.to_string().contains("pairing ended"), "{error}");
1578 let refused = pairing
1579 .issue(IssueCode::new("ana", ["operator"]).with_device_ttl(Duration::ZERO))
1580 .await
1581 .unwrap_err();
1582 assert!(matches!(refused, KernelError::Config { .. }), "a zero-length pairing is refused");
1583 }
1584
1585 #[tokio::test]
1586 async fn a_wrong_secret_is_refused() {
1587 let pairing = pairing();
1588 let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1589 let claimed = pairing.claim(&issued.code, None).await.unwrap();
1590 let last = if claimed.token.ends_with('0') { '1' } else { '0' };
1591 let forged = format!("{}{last}", &claimed.token[..claimed.token.len() - 1]);
1592 assert!(matches!(
1593 pairing.authenticate(&forged).await,
1594 Err(KernelError::Unauthorized { .. })
1595 ));
1596 }
1597
1598 #[tokio::test]
1599 async fn twenty_wrong_codes_cancel_every_waiting_code() {
1600 let pairing = pairing();
1601 let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await.unwrap();
1602 for _ in 0..MAX_FAILED_CLAIMS {
1603 assert!(pairing.claim("0000-0000", None).await.is_err());
1604 }
1605 assert!(pairing.claim(&issued.code, None).await.is_err(), "the lockout cancelled it");
1606 }
1607
1608 #[tokio::test]
1609 async fn authorize_opens_only_the_scoped_routes() {
1610 let pairing = pairing();
1611 let issued = pairing
1612 .issue(IssueCode::new("ana", ["operator"]).with_scopes([DeviceScope::Read]))
1613 .await
1614 .unwrap();
1615 let token = pairing.claim(&issued.code, None).await.unwrap().token;
1616 let context = pairing.authorize(&token, &Method::GET, "/api/approvals").await.unwrap();
1617 assert_eq!(context.user_id, "ana");
1618 assert_eq!(context.scopes, ["operator"]);
1619 let error =
1620 pairing.authorize(&token, &Method::POST, "/api/approvals/x/decide").await.unwrap_err();
1621 assert_eq!(AdkError::from(error).category, ErrorCategory::Forbidden);
1622 let error =
1623 pairing.authorize(&token, &Method::POST, "/api/kernel/unfreeze").await.unwrap_err();
1624 assert_eq!(AdkError::from(error).category, ErrorCategory::Forbidden);
1625 }
1626}