Skip to main content

posemesh_compute_node/auth/
robot.rs

1use super::siwe::{AccessBundle, SiweError};
2use super::token_manager::{
3    AccessAuthenticator, SystemClock, TokenManager, TokenManagerConfig, TokenProvider,
4    TokenProviderError,
5};
6use crate::config::RobotNodeConfig;
7use anyhow::{anyhow, Context, Result};
8use async_trait::async_trait;
9use chrono::{DateTime, Utc};
10use reqwest::{Client, Response};
11use serde::{Deserialize, Serialize};
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::Arc;
14use std::time::Duration;
15use tokio::sync::Mutex;
16use url::Url;
17use uuid::Uuid;
18
19const REGISTER_PATH: &str = "/internal/v1/robots/register";
20const VERIFY_PATH: &str = "/internal/v1/auth/robot/verify";
21
22type ManagerCell = Arc<Mutex<Option<Arc<RobotTokenManager>>>>;
23type RobotTokenManager = TokenManager<RobotAuthenticator, SystemClock>;
24
25#[derive(Serialize)]
26struct RegisterRequest<'a> {
27    registration_credentials: &'a str,
28    version: &'a str,
29    capabilities: &'a [String],
30}
31
32#[derive(Serialize)]
33struct VerifyRequest<'a> {
34    registration_credentials: &'a str,
35}
36
37#[derive(Deserialize)]
38struct AccessResponse {
39    robot_id: Option<Uuid>,
40    access_token: Option<String>,
41    access_expires_at: Option<String>,
42}
43
44struct RobotAuthenticator {
45    base_url: Arc<String>,
46    registration_credentials: Arc<String>,
47    node_version: Arc<String>,
48    capabilities: Arc<Vec<String>>,
49    client: Client,
50    registered: AtomicBool,
51}
52
53impl RobotAuthenticator {
54    fn new(
55        base_url: Url,
56        registration_credentials: String,
57        node_version: String,
58        capabilities: Vec<String>,
59        request_timeout: Duration,
60    ) -> Result<Self> {
61        let registration_credentials = registration_credentials.trim().to_string();
62        if registration_credentials.is_empty() {
63            return Err(anyhow!("robot registration credentials must not be empty"));
64        }
65        let node_version = node_version.trim().to_string();
66        if node_version.is_empty() {
67            return Err(anyhow!("robot node version must not be empty"));
68        }
69
70        let client = Client::builder()
71            .use_rustls_tls()
72            .timeout(request_timeout)
73            .build()
74            .context("build DDS robot authentication client")?;
75
76        Ok(Self {
77            base_url: Arc::new(base_url.to_string()),
78            registration_credentials: Arc::new(registration_credentials),
79            node_version: Arc::new(node_version),
80            capabilities: Arc::new(capabilities),
81            client,
82            registered: AtomicBool::new(false),
83        })
84    }
85
86    async fn register(&self) -> std::result::Result<AccessBundle, SiweError> {
87        let endpoint = self.endpoint(REGISTER_PATH);
88        let response = self
89            .client
90            .post(endpoint)
91            .json(&RegisterRequest {
92                registration_credentials: self.registration_credentials.as_str(),
93                version: self.node_version.as_str(),
94                capabilities: self.capabilities.as_slice(),
95            })
96            .send()
97            .await?;
98        decode_access_response(response).await
99    }
100
101    async fn verify(&self) -> std::result::Result<AccessBundle, SiweError> {
102        let endpoint = self.endpoint(VERIFY_PATH);
103        let response = self
104            .client
105            .post(endpoint)
106            .json(&VerifyRequest {
107                registration_credentials: self.registration_credentials.as_str(),
108            })
109            .send()
110            .await?;
111        decode_access_response(response).await
112    }
113
114    fn endpoint(&self, path: &str) -> String {
115        format!("{}{}", self.base_url.trim_end_matches('/'), path)
116    }
117}
118
119#[async_trait]
120impl AccessAuthenticator for RobotAuthenticator {
121    async fn login(&self) -> std::result::Result<AccessBundle, SiweError> {
122        if self.registered.load(Ordering::Acquire) {
123            return self.verify().await;
124        }
125
126        let bundle = self.register().await?;
127        self.registered.store(true, Ordering::Release);
128        Ok(bundle)
129    }
130}
131
132async fn decode_access_response(
133    response: Response,
134) -> std::result::Result<AccessBundle, SiweError> {
135    if !response.status().is_success() {
136        return Err(SiweError::UpstreamStatus(response.status()));
137    }
138
139    let body: AccessResponse = response.json().await?;
140    if body.robot_id.filter(|id| !id.is_nil()).is_none() {
141        return Err(SiweError::MissingField("robot_id"));
142    }
143    let token = body
144        .access_token
145        .filter(|value| !value.is_empty())
146        .ok_or(SiweError::MissingField("access_token"))?;
147    let expires_at_raw = body
148        .access_expires_at
149        .ok_or(SiweError::MissingField("access_expires_at"))?;
150    let expires_at = DateTime::parse_from_rfc3339(&expires_at_raw)?.with_timezone(&Utc);
151
152    Ok(AccessBundle::new(token, expires_at))
153}
154
155/// Robot machine-authentication lifecycle for the compute-node engine.
156///
157/// A new instance always registers first. Once registration succeeds, all
158/// token refreshes use the verify endpoint and never fall back to SIWE.
159pub struct RobotMachineAuth {
160    authenticator: Arc<RobotAuthenticator>,
161    config: TokenManagerConfig,
162    manager: ManagerCell,
163}
164
165impl RobotMachineAuth {
166    pub fn from_config(cfg: &RobotNodeConfig, capabilities: Vec<String>) -> Result<Self> {
167        let token_config = TokenManagerConfig {
168            safety_ratio: cfg.token_safety_ratio as f64,
169            max_retries: cfg.token_reauth_max_retries,
170            jitter: Duration::from_millis(cfg.token_reauth_jitter_ms),
171        };
172
173        Self::new(
174            cfg.dds_base_url.clone(),
175            cfg.registration_credentials().to_string(),
176            cfg.node_version.clone(),
177            capabilities,
178            Duration::from_secs(cfg.request_timeout_secs.max(1)),
179            token_config,
180        )
181    }
182
183    pub fn new(
184        dds_base_url: Url,
185        registration_credentials: impl Into<String>,
186        node_version: impl Into<String>,
187        capabilities: Vec<String>,
188        request_timeout: Duration,
189        token_config: TokenManagerConfig,
190    ) -> Result<Self> {
191        let authenticator = Arc::new(RobotAuthenticator::new(
192            dds_base_url,
193            registration_credentials.into(),
194            node_version.into(),
195            capabilities,
196            request_timeout,
197        )?);
198        Ok(Self {
199            authenticator,
200            config: token_config,
201            manager: Arc::new(Mutex::new(None)),
202        })
203    }
204
205    pub async fn start(&self) -> Result<RobotHandle> {
206        let mut guard = self.manager.lock().await;
207        if let Some(existing) = guard.as_ref() {
208            return Ok(RobotHandle {
209                manager: existing.clone(),
210            });
211        }
212
213        let manager = Arc::new(TokenManager::new(
214            Arc::clone(&self.authenticator),
215            Arc::new(SystemClock),
216            self.config.clone(),
217        ));
218
219        manager
220            .bearer()
221            .await
222            .map_err(|err| anyhow!("initial DDS robot authentication failed: {err}"))?;
223
224        // Track the authenticated manager before starting its owned task. If
225        // startup is cancelled at this boundary, `shutdown` can still stop it.
226        *guard = Some(manager.clone());
227        manager.start_bg().await;
228
229        Ok(RobotHandle { manager })
230    }
231
232    /// Stop and discard any token manager installed by [`Self::start`].
233    ///
234    /// Calling this after a cancelled startup is safe even when initial DDS
235    /// authentication never completed.
236    pub async fn shutdown(&self) {
237        let manager = self.manager.lock().await.take();
238        if let Some(manager) = manager {
239            manager.stop_bg().await;
240        }
241    }
242}
243
244#[derive(Clone)]
245pub struct RobotHandle {
246    manager: Arc<RobotTokenManager>,
247}
248
249impl RobotHandle {
250    pub async fn bearer(&self) -> Result<String, TokenProviderError> {
251        self.manager.bearer().await
252    }
253
254    pub async fn shutdown(&self) {
255        self.manager.stop_bg().await;
256    }
257}
258
259#[async_trait]
260impl TokenProvider for RobotHandle {
261    async fn bearer(&self) -> super::token_manager::TokenProviderResult<String> {
262        self.manager.bearer().await
263    }
264
265    async fn on_unauthorized(&self) {
266        self.manager.on_unauthorized_retry().await;
267    }
268}