Skip to main content

lean_ctx/core/hive/
auth.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Enrollment (device flow), access tokens and lease renewal.
3//!
4//! The instance's Ed25519 key is its only long-lived secret: every access
5//! token is minted from a fresh signed assertion and cached until shortly
6//! before it expires. Nothing here runs inside a tool call.
7
8use std::time::Duration;
9
10use chrono::{DateTime, Utc};
11use serde_json::{Value, json};
12
13use super::HiveError;
14use super::instance_key::InstanceKeys;
15use super::lease::{VerifiedLease, load_lease, store_lease, verify_keyset, verify_lease};
16use super::state::{HiveStore, INSTANCE_FILE, InstanceRecord, TOKEN_FILE, TokenRecord};
17use super::transport::HiveClient;
18use lean_ctx_protocol::hive::enroll::{
19    AccessTokenV1, DEVICE_SETUP_REQUEST_SCHEMA, DEVICE_TOKEN_REQUEST_SCHEMA, DeviceCodeRequestV1,
20    DeviceCodeV1, DeviceSetupProjectV1, DeviceSetupRequestV1, EngineOs, EnrollmentV1,
21    TOKEN_REQUEST_SCHEMA, token_assertion_input,
22};
23use lean_ctx_protocol::hive::lease::HiveLeaseEnvelopeV1;
24
25/// Tokens are refreshed this long before they expire.
26const TOKEN_REFRESH_MARGIN_SECONDS: i64 = 120;
27
28pub fn engine_os() -> EngineOs {
29    if cfg!(target_os = "macos") {
30        EngineOs::Macos
31    } else if cfg!(target_os = "linux") {
32        EngineOs::Linux
33    } else if cfg!(windows) {
34        EngineOs::Windows
35    } else {
36        EngineOs::Other
37    }
38}
39
40fn stamp(time: DateTime<Utc>) -> String {
41    time.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
42}
43
44fn protocol(what: &str) -> impl Fn(lean_ctx_protocol::ValidationError) -> HiveError + '_ {
45    move |e| HiveError::Protocol(format!("{what}: {e}"))
46}
47
48fn decode<T: serde::de::DeserializeOwned>(value: Value, what: &str) -> Result<T, HiveError> {
49    serde_json::from_value(value).map_err(|e| HiveError::Protocol(format!("{what}: {e}")))
50}
51
52/// Step 1: ask Hive for a device code; `label` is the user's `--label`, if
53/// any (the approval page shows it, Hive task #11).
54pub fn start_device_flow(
55    client: &HiveClient,
56    label: Option<&str>,
57) -> Result<DeviceCodeV1, HiveError> {
58    let request = DeviceCodeRequestV1::new(env!("CARGO_PKG_VERSION"), engine_os())
59        .with_label(label.map(str::to_string));
60    request.validate().map_err(protocol("--label"))?;
61    let body = serde_json::to_value(&request).map_err(|e| HiveError::Protocol(e.to_string()))?;
62    let code: DeviceCodeV1 = decode(client.post("/device/code", &body)?, "device code")?;
63    code.validate().map_err(protocol("device code"))?;
64    Ok(code)
65}
66
67/// The project an engine names at connect (C0 2.1 device setup): the
68/// checkout's folder name and the remote it sees, plus what it shares.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct SetupAnnouncement {
71    pub project: Option<(String, Option<String>)>,
72    pub shares: Vec<String>,
73}
74
75/// Step 1b (C0 2.1): name the project and what this machine shares, so the
76/// approval page asks "Share this project" too. Only when the Hive offers
77/// it; `false` when it did not take it (the terminal then asks, as before).
78pub fn announce_setup(client: &HiveClient, code: &DeviceCodeV1, setup: &SetupAnnouncement) -> bool {
79    if !code.offers_device_setup() {
80        return false;
81    }
82    let request = DeviceSetupRequestV1 {
83        schema: DEVICE_SETUP_REQUEST_SCHEMA.into(),
84        device_code: code.device_code.clone(),
85        project: setup
86            .project
87            .clone()
88            .map(|(name, remote)| DeviceSetupProjectV1 { name, remote }),
89        shares: setup.shares.clone(),
90    };
91    let Ok(body) = serde_json::to_value(&request) else {
92        return false;
93    };
94    match client.post("/device/setup", &body) {
95        Ok(_) => true,
96        Err(error) => {
97            tracing::info!("hive device setup: {error}");
98            false
99        }
100    }
101}
102
103/// What the device approval answered beyond the enrollment: the page's
104/// answer to "Share this project" (C0 2.1). `None`: the page did not ask
105/// (no setup, or an older Hive); `Some(None)`: an older page approved it.
106pub type SharingAnswer = Option<Option<bool>>;
107
108/// Step 2: poll until the user approved (or the code expired), then verify
109/// and persist the enrollment. `sleep` is injectable for tests.
110pub fn finish_device_flow(
111    store: &HiveStore,
112    client: &HiveClient,
113    code: &DeviceCodeV1,
114    label: &str,
115    root: &[u8; 32],
116    sleep: &dyn Fn(Duration),
117) -> Result<(InstanceRecord, SharingAnswer), HiveError> {
118    let keys = InstanceKeys::load_or_create(store)?;
119    let request = json!({
120        "schema": DEVICE_TOKEN_REQUEST_SCHEMA,
121        "device_code": code.device_code,
122        "instance_public_key": keys.public_key_b64(),
123        "instance_kx_public_key": keys.kx_public_key_b64(),
124        "instance_label": label,
125        "engine_version": env!("CARGO_PKG_VERSION"),
126        "os": engine_os(),
127    });
128    let mut interval = u64::from(code.interval.max(1));
129    let deadline = std::time::Instant::now() + Duration::from_secs(u64::from(code.expires_in));
130    loop {
131        sleep(Duration::from_secs(interval));
132        match client.post("/device/token", &request) {
133            Ok(body) => {
134                let local_now = Utc::now();
135                let keys_raw = body["keys"].clone();
136                let sharing: SharingAnswer = body
137                    .get("sharing")
138                    .filter(|s| s.is_object())
139                    .map(|s| s["share"].as_bool());
140                return decode::<EnrollmentV1>(body, "enrollment")
141                    .and_then(|enrollment| {
142                        complete_enrollment(
143                            store,
144                            client.origin(),
145                            &enrollment,
146                            &keys_raw,
147                            root,
148                            label,
149                            local_now,
150                        )
151                    })
152                    .map(|instance| (instance, sharing))
153                    .map_err(|error| unenrolled(store, label, error));
154            }
155            Err(HiveError::Server { status: 400, code })
156                if code == "authorization_pending" || code == "slow_down" =>
157            {
158                if code == "slow_down" {
159                    interval += 5;
160                }
161            }
162            Err(other) => return Err(other),
163        }
164        if std::time::Instant::now() >= deadline {
165            return Err(HiveError::DeviceFlow(super::error::CODE_EXPIRED.into()));
166        }
167    }
168}
169
170/// Hive enrolled the instance key, but this engine refused the answer
171/// (Hive task #1): the key is spent, since Hive now knows it and refuses
172/// it a second time ("instance key is already enrolled"). A machine without
173/// an enrollment of its own drops it with whatever the refused answer left,
174/// so the next connect starts from a fresh key, and the error says so.
175fn unenrolled(store: &HiveStore, label: &str, error: HiveError) -> HiveError {
176    if !matches!(store.instance(), Ok(None)) {
177        return error;
178    }
179    let next = match store.forget(true) {
180        Ok(()) => format!(
181            "Its unused instance key was removed: fix the cause and run `lean-ctx hive connect` again. Hive may list an engine \"{label}\" that never connected; remove it there."
182        ),
183        Err(e) => format!(
184            "Its unused instance key could not be removed ({e}); run `lean-ctx hive disconnect` before connecting again."
185        ),
186    };
187    match error {
188        HiveError::Protocol(m) => HiveError::Protocol(format!("{m}. {next}")),
189        HiveError::Config(m) => HiveError::Config(format!("{m}. {next}")),
190        other => other,
191    }
192}
193
194/// Verify an enrollment answer against the root key and persist it.
195pub fn complete_enrollment(
196    store: &HiveStore,
197    origin: &str,
198    enrollment: &EnrollmentV1,
199    keys_raw: &Value,
200    root: &[u8; 32],
201    label: &str,
202    local_now: DateTime<Utc>,
203) -> Result<InstanceRecord, HiveError> {
204    enrollment.validate().map_err(protocol("enrollment"))?;
205    let keyset = verify_keyset(keys_raw, root)?;
206    let verified = verify_lease(
207        &enrollment.lease,
208        &keyset,
209        &enrollment.instance_id,
210        local_now,
211        None,
212    )?;
213    if verified.lease.org_id != enrollment.org.id {
214        return Err(HiveError::Protocol(
215            "the lease is for another workspace".into(),
216        ));
217    }
218    store_lease(store, &verified, keys_raw, local_now)?;
219    let record = InstanceRecord {
220        instance_id: enrollment.instance_id.clone(),
221        org_id: enrollment.org.id.clone(),
222        org_name: enrollment.org.name.clone(),
223        org_kind: enrollment.org.kind.clone(),
224        company_name: enrollment.org.company.as_ref().map(|c| c.name.clone()),
225        label: label.to_string(),
226        url: origin.to_string(),
227        org_salt_id: enrollment.org_salt_id.clone(),
228        web_url: enrollment
229            .web_url
230            .as_deref()
231            .and_then(|url| super::config::normalize_origin(url).ok()),
232        enrolled_at: stamp(local_now),
233    };
234    super::worker::prepare_enrollment(store)?;
235    store.write_config(INSTANCE_FILE, &record)?;
236    // A new enrolment starts a new sharing period (Hive' `since`): an
237    // earlier engine-side off no longer bounds it (K2 review 3, NEW-1).
238    super::metrics_v2::buffer::clear_local_on_since(store.data_dir());
239    store.remove_config(TOKEN_FILE)?;
240    store.record_success(
241        "enroll",
242        &stamp(verified.service_time(local_now).with_timezone(&Utc)),
243    );
244    Ok(record)
245}
246
247/// A connected instance: its record, verified lease and keys.
248pub struct Session {
249    pub store: HiveStore,
250    pub instance: InstanceRecord,
251    pub lease: VerifiedLease,
252    root: [u8; 32],
253}
254
255impl Session {
256    /// Load and re-verify the local enrollment. `root` is the root key of the
257    /// origin the instance is enrolled with.
258    pub fn load(store: HiveStore, root: [u8; 32]) -> Result<Self, HiveError> {
259        let instance = store.instance()?.ok_or(HiveError::NotConnected)?;
260        // A revoked instance fails closed here, before any Hive call.
261        if let Some(revoked) = super::revoked::recorded(&store, &instance) {
262            return Err(revoked);
263        }
264        let lease = load_lease(&store, &root, &instance.instance_id)?;
265        super::root_cert::check_lease_org(&store, &instance.url, &lease.lease)?;
266        Ok(Self {
267            store,
268            instance,
269            lease,
270            root,
271        })
272    }
273
274    /// The root key the enrollment was verified with.
275    pub fn root_key(&self) -> &[u8; 32] {
276        &self.root
277    }
278
279    fn service_now(&self) -> DateTime<Utc> {
280        self.lease.service_time(Utc::now()).with_timezone(&Utc)
281    }
282
283    /// The current access token (minted when needed), for transports that
284    /// authenticate outside [`HiveClient`] (the bus WebSocket upgrade).
285    /// `force` mints a new one.
286    pub fn bearer_token(&self, force: bool) -> Result<zeroize::Zeroizing<String>, HiveError> {
287        self.access_token(force).map(zeroize::Zeroizing::new)
288    }
289
290    /// True when this Hive answered the instance card (C0 2.0): requests
291    /// then carry `Hive-Protocol: 2.0`. Against a 1.x Hive (prod before
292    /// the cutover) nothing changes.
293    fn speaks_v2(&self) -> bool {
294        super::bus::relay_v2::speaks_v2(&self.store)
295    }
296
297    /// An authenticated client, minting an access token when needed.
298    pub fn client(&self) -> Result<HiveClient, HiveError> {
299        self.client_as(self.speaks_v2())
300    }
301
302    fn client_as(&self, v2: bool) -> Result<HiveClient, HiveError> {
303        let token = self.access_token(false)?;
304        Ok(HiveClient::new(&self.instance.url)?
305            .with_token(&self.instance.instance_id, &token)
306            .speaking_v2(v2))
307    }
308
309    /// Run `call` with an authenticated client; on 401 mint a new token once.
310    pub fn with_client<T>(
311        &self,
312        call: impl Fn(&HiveClient) -> Result<T, HiveError>,
313    ) -> Result<T, HiveError> {
314        self.with_client_as(self.speaks_v2(), call)
315    }
316
317    fn with_client_as<T>(
318        &self,
319        v2: bool,
320        call: impl Fn(&HiveClient) -> Result<T, HiveError>,
321    ) -> Result<T, HiveError> {
322        let result = match call(&self.client_as(v2)?) {
323            Err(HiveError::Unauthorized) => {
324                let token = self.access_token(true)?;
325                let client = HiveClient::new(&self.instance.url)?
326                    .with_token(&self.instance.instance_id, &token)
327                    .speaking_v2(v2);
328                call(&client)
329            }
330            other => other,
331        };
332        result.map_err(|e| self.noted(e))
333    }
334
335    /// A revocation answer is recorded (the engine then fails closed) and
336    /// named with this workspace; a used-up quota holds the paths it counts
337    /// (`throttle`); a feature's `plan_required` names the lease's plan;
338    /// any other error passes unchanged.
339    pub(crate) fn noted(&self, error: HiveError) -> HiveError {
340        let error = super::revoked::note(&self.store, &self.instance, error)
341            .with_plan(self.lease.lease.plan);
342        super::throttle::note_on(&self.store, None, error, chrono::Utc::now())
343    }
344
345    /// An authenticated client for one call that must end by `deadline`,
346    /// minting the token (if needed) inside the same budget and without the
347    /// 401 retry of [`Self::with_client`] (C5c, rule 3 exception).
348    pub fn bounded_client(&self, deadline: std::time::Instant) -> Result<HiveClient, HiveError> {
349        let left = |what: &str| {
350            deadline
351                .checked_duration_since(std::time::Instant::now())
352                .filter(|d| !d.is_zero())
353                .ok_or_else(|| HiveError::Offline(format!("{what}: time budget used up")))
354        };
355        let mint = HiveClient::bounded(&self.instance.url, left("token")?)?;
356        let token = self.access_token_via(false, &mint)?;
357        Ok(HiveClient::bounded(&self.instance.url, left("request")?)?
358            .with_token(&self.instance.instance_id, &token)
359            .speaking_v2(self.speaks_v2()))
360    }
361
362    fn access_token(&self, force: bool) -> Result<String, HiveError> {
363        self.access_token_via(force, &HiveClient::new(&self.instance.url)?)
364    }
365
366    fn access_token_via(&self, force: bool, client: &HiveClient) -> Result<String, HiveError> {
367        let now = self.service_now().timestamp();
368        if !force
369            && let Some(cached) = self.store.read_config::<TokenRecord>(TOKEN_FILE)?
370            && cached.expires_at - TOKEN_REFRESH_MARGIN_SECONDS > now
371        {
372            return Ok(cached.access_token);
373        }
374        let keys = InstanceKeys::load(&self.store)?;
375        let mut nonce_bytes = [0u8; 18];
376        getrandom::fill(&mut nonce_bytes).map_err(|e| HiveError::Local(format!("random: {e}")))?;
377        use base64::Engine as _;
378        let nonce = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(nonce_bytes);
379        let assertion = keys.sign_b64(&token_assertion_input(
380            &self.instance.instance_id,
381            now,
382            &nonce,
383        ));
384        let request = json!({
385            "schema": TOKEN_REQUEST_SCHEMA, "iat": now, "nonce": nonce, "assertion": assertion,
386        });
387        let path = format!("/instances/{}/token", self.instance.instance_id);
388        let answer = client.post(&path, &request).map_err(|e| self.noted(e))?;
389        let token: AccessTokenV1 = decode(answer, "access token")?;
390        token.validate().map_err(protocol("access token"))?;
391        self.store.write_config(
392            TOKEN_FILE,
393            &TokenRecord {
394                access_token: token.access_token.clone(),
395                expires_at: now + i64::from(token.expires_in),
396            },
397        )?;
398        self.store
399            .record_success("token", &stamp(self.service_now()));
400        Ok(token.access_token)
401    }
402
403    /// Renew the lease and persist it; returns the new lease. Always as 1.x:
404    /// the lease is checked against the v1 key set stored at enrollment
405    /// (which also feeds the runtime lease), and a 1.x request gets exactly
406    /// that set's signer (E13 negotiation).
407    pub fn renew(&mut self) -> Result<&VerifiedLease, HiveError> {
408        let path = format!("/instances/{}/lease/renew", self.instance.instance_id);
409        let body = self.with_client_as(false, |client| client.post(&path, &json!({})))?;
410        let local_now = Utc::now();
411        let envelope: HiveLeaseEnvelopeV1 = decode(body, "lease")?;
412        let keys_raw: Value = self
413            .store
414            .read_config(super::state::KEYS_FILE)?
415            .ok_or(HiveError::NotConnected)?;
416        let keyset = verify_keyset(&keys_raw, &self.root)?;
417        let verified = verify_lease(
418            &envelope,
419            &keyset,
420            &self.instance.instance_id,
421            local_now,
422            None,
423        )?;
424        store_lease(&self.store, &verified, &keys_raw, local_now)?;
425        self.store.record_success(
426            "lease",
427            &stamp(verified.service_time(local_now).with_timezone(&Utc)),
428        );
429        self.lease = verified;
430        Ok(&self.lease)
431    }
432
433    /// Free the seat in Hive.
434    pub fn delete_instance(&self) -> Result<(), HiveError> {
435        let path = format!("/instances/{}", self.instance.instance_id);
436        self.with_client(|client| client.delete(&path))
437    }
438}