1use std::collections::BTreeSet;
17use std::io::{self, Read};
18use std::path::{Path, PathBuf};
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::{Mutex, MutexGuard, TryLockError};
21use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
22
23use base64::{Engine as _, engine::general_purpose::STANDARD};
24use lean_ctx_protocol::{EntitlementDeploymentV1, EntitlementKindV1};
25use serde::{Deserialize, Serialize};
26use sha2::{Digest as _, Sha256};
27
28use super::PlanSource;
29use crate::core::billing::signed_entitlements::{
30 EntitlementContext, EntitlementTrustKey, EntitlementVerificationError, VerifiedEntitlement,
31 verify_entitlement,
32};
33use crate::core::billing::{Entitlements, Plan};
34
35const TRUST_LIMIT: usize = 16 * 1024;
36const ENVELOPE_LIMIT: usize = 32 * 1024;
37const CREDENTIAL_LIMIT: usize = 64 * 1024;
38const COMPILED_TRUST_BYTES: &[u8] = include_bytes!("../../data/entitlement-trust-root.json");
39
40static DENIAL_MEMORY: Mutex<Vec<(PathBuf, String)>> = Mutex::new(Vec::new());
43static DENIAL_TRACKING_FAILED: AtomicBool = AtomicBool::new(false);
44#[cfg(test)]
45static TEST_PATHS: Mutex<Option<CachePaths>> = Mutex::new(None);
46#[cfg(test)]
47static TEST_PATHS_SERIAL: Mutex<()> = Mutex::new(());
48
49#[derive(Clone, Debug)]
50pub struct EffectivePlan {
51 pub plan: Plan,
52 pub supporter_recognition: bool,
53 pub source: PlanSource,
54 pub verified_at: Option<i64>,
55 pub grace_days: i64,
56 pub verification_status: &'static str,
57 verified: Option<VerifiedEntitlement>,
58 binding: Option<Binding>,
59 guard: Option<SnapshotGuard>,
60 free_account: Option<FreeAccountSnapshot>,
61}
62
63impl EffectivePlan {
64 fn community(status: &'static str) -> Self {
65 Self {
66 plan: Plan::Community,
67 supporter_recognition: false,
68 source: if status == "expired" {
69 PlanSource::Expired
70 } else {
71 PlanSource::None
72 },
73 verified_at: None,
74 grace_days: 0,
75 verification_status: status,
76 verified: None,
77 binding: None,
78 guard: None,
79 free_account: None,
80 }
81 }
82
83 #[must_use]
85 pub fn allows(&self, capability: &str) -> bool {
86 self.current_allows_at(capability, clock())
87 }
88
89 fn current_allows_at(&self, capability: &str, now: u64) -> bool {
90 if crate::core::product_capabilities::registry()
91 .find(capability)
92 .is_some_and(|entry| entry.minimum_plan() == Plan::Community && !entry.account_required)
93 {
94 return true;
95 }
96 if !self.is_current() {
97 return false;
98 }
99 self.allows_at(capability, now)
100 }
101
102 fn allows_at(&self, capability: &str, now: u64) -> bool {
103 let registry = crate::core::product_capabilities::registry();
104 let Some(entry) = registry.find(capability) else {
105 return false;
106 };
107 if entry.minimum_plan() == Plan::Community {
108 if !entry.account_required {
109 return true;
110 }
111 return self
115 .free_account
116 .as_ref()
117 .is_some_and(|snapshot| snapshot.is_current(now));
118 }
119 match (&self.verified, &self.binding) {
120 (Some(verified), Some(binding)) => verified.allows(capability, binding.context(now)),
121 _ => false,
122 }
123 }
124
125 #[must_use]
127 pub fn entitlements(&self) -> Entitlements {
128 if !self.is_current() {
129 return Plan::Community.entitlements();
130 }
131 self.entitlements_at(clock())
132 }
133
134 fn is_current(&self) -> bool {
135 self.guard.as_ref().is_none_or(SnapshotGuard::is_current)
136 }
137
138 fn entitlements_at(&self, now: u64) -> Entitlements {
139 let (Some(verified), Some(binding)) = (&self.verified, &self.binding) else {
140 return Plan::Community.entitlements();
141 };
142 if verified.validity(binding.context(now)).is_err() {
143 return Plan::Community.entitlements();
144 }
145 let mut result = verified.plan().entitlements();
146 result.seats = verified.claims().seats;
147 if !self.allows_at("pro.hosted_index", now) {
148 result.hosted_index_mb = 0;
149 }
150 if !self.allows_at("team.managed_connectors", now) {
151 result.managed_connectors = 0;
152 }
153 if !self.allows_at("team.audit_retention", now) {
154 result.audit_retention_days = 0;
155 }
156 result.private_registry &= self.allows_at("team.private_registry", now);
157 result.sso_oidc &= self.allows_at("team.sso_oidc", now);
158 result.sso_scim &= self.allows_at("enterprise.sso_scim", now);
159 result.revenue_share &= self.allows_at("team.revenue_share", now);
160 result.cloud_sync &= self.allows_at("pro.cloud_sync", now);
161 result
162 }
163}
164
165#[derive(Clone, Debug)]
166struct Binding {
167 account_id: Option<String>,
168 deployment: EntitlementDeploymentV1,
169 deployment_id: Option<String>,
170 org_id: Option<String>,
171 workspace_id: Option<String>,
172}
173
174impl Binding {
175 fn context(&self, now: u64) -> EntitlementContext<'_> {
176 EntitlementContext {
177 account_id: self.account_id.as_deref(),
178 deployment: self.deployment,
179 deployment_id: self.deployment_id.as_deref(),
180 org_id: self.org_id.as_deref(),
181 workspace_id: self.workspace_id.as_deref(),
182 now,
183 }
184 }
185}
186
187#[derive(Deserialize)]
188#[serde(deny_unknown_fields)]
189struct TrustDocument {
190 schema_version: u16,
191 keys: Vec<TrustKeyDocument>,
192 #[serde(default)]
193 revoked_entitlement_ids: Vec<String>,
194 #[serde(default = "hosted")]
195 deployment: EntitlementDeploymentV1,
196 #[serde(default)]
197 deployment_id: Option<String>,
198 #[serde(default)]
199 org_id: Option<String>,
200 #[serde(default)]
201 workspace_id: Option<String>,
202}
203
204#[derive(Deserialize)]
205#[serde(deny_unknown_fields)]
206struct TrustKeyDocument {
207 key_id: String,
208 public_key_base64: String,
209}
210
211fn hosted() -> EntitlementDeploymentV1 {
212 EntitlementDeploymentV1::Hosted
213}
214
215struct Trust {
216 keys: Vec<EntitlementTrustKey>,
217 revoked: BTreeSet<String>,
218 binding: Binding,
219}
220
221impl Trust {
222 fn parse(bytes: &[u8], anchors: &[EntitlementTrustKey]) -> Result<Self, &'static str> {
223 if anchors.is_empty() {
224 return Err("missing_trust_root");
225 }
226 let trust = Self::parse_unanchored(bytes)?;
227 if trust.keys.iter().any(|key| {
228 !anchors
229 .iter()
230 .any(|anchor| anchor.key_id == key.key_id && anchor.public_key == key.public_key)
231 }) {
232 return Err("untrusted_key");
233 }
234 Ok(trust)
235 }
236
237 fn parse_unanchored(bytes: &[u8]) -> Result<Self, &'static str> {
238 if bytes.len() > TRUST_LIMIT {
239 return Err("invalid_trust");
240 }
241 let doc: TrustDocument = serde_json::from_slice(bytes).map_err(|_| "invalid_trust")?;
242 if doc.schema_version != 1
243 || doc.keys.is_empty()
244 || doc.keys.len() > 16
245 || doc.revoked_entitlement_ids.len() > 256
246 {
247 return Err("invalid_trust");
248 }
249 for id in [&doc.deployment_id, &doc.org_id, &doc.workspace_id]
250 .into_iter()
251 .flatten()
252 {
253 if !valid_id(id) {
254 return Err("invalid_trust");
255 }
256 }
257 let mut key_ids = BTreeSet::new();
258 let mut keys = Vec::with_capacity(doc.keys.len());
259 for entry in doc.keys {
260 if !valid_id(&entry.key_id) || !key_ids.insert(entry.key_id.clone()) {
261 return Err("invalid_trust");
262 }
263 let decoded = STANDARD
264 .decode(&entry.public_key_base64)
265 .map_err(|_| "invalid_trust")?;
266 if STANDARD.encode(&decoded) != entry.public_key_base64 {
267 return Err("invalid_trust");
268 }
269 let public_key: [u8; 32] = decoded.try_into().map_err(|_| "invalid_trust")?;
270 ed25519_dalek::VerifyingKey::from_bytes(&public_key).map_err(|_| "invalid_trust")?;
271 keys.push(EntitlementTrustKey {
272 key_id: entry.key_id,
273 public_key,
274 });
275 }
276 let mut revoked = BTreeSet::new();
277 for id in doc.revoked_entitlement_ids {
278 if !valid_id(&id) || !revoked.insert(id) {
279 return Err("invalid_trust");
280 }
281 }
282 Ok(Self {
283 keys,
284 revoked,
285 binding: Binding {
286 account_id: None,
287 deployment: doc.deployment,
288 deployment_id: doc.deployment_id,
289 org_id: doc.org_id,
290 workspace_id: doc.workspace_id,
291 },
292 })
293 }
294}
295
296fn valid_id(value: &str) -> bool {
297 !value.is_empty()
298 && value.len() <= 256
299 && value.bytes().all(|byte| (0x21..=0x7e).contains(&byte))
300}
301
302#[derive(Clone, Debug)]
303struct CachePaths {
304 trust: PathBuf,
305 credentials: PathBuf,
306 cache: PathBuf,
307 offline: Option<PathBuf>,
308 #[cfg(test)]
309 trust_anchors: Vec<EntitlementTrustKey>,
310}
311
312#[derive(Clone, Debug)]
313struct SnapshotGuard {
314 paths: CachePaths,
315 account_id: Option<String>,
316 trust_bytes: Vec<u8>,
317 entitlement_bytes: Vec<u8>,
318}
319
320#[derive(Clone, Debug)]
321struct FreeAccountSnapshot {
322 paths: CachePaths,
323 trust_bytes: Vec<u8>,
324 credentials_digest: [u8; 32],
325}
326
327impl FreeAccountSnapshot {
328 fn is_current(&self, now: u64) -> bool {
329 let Ok(inputs) = load_inputs(&self.paths) else {
330 return false;
331 };
332 self.paths.offline.is_none()
333 && inputs.trust.binding.deployment != EntitlementDeploymentV1::AirGapped
334 && inputs.trust_bytes == self.trust_bytes
335 && inputs.credentials_digest == Some(self.credentials_digest)
336 && inputs
337 .credentials
338 .as_ref()
339 .is_some_and(|credentials| credentials_bearer(credentials, now).is_some())
340 && !remembered_denial(
341 &self.paths.cache,
342 inputs.trust.binding.account_id.as_deref(),
343 )
344 && inputs
345 .trust
346 .binding
347 .account_id
348 .as_deref()
349 .is_some_and(|account| {
350 !durable_denial_marker(&self.paths, account)
351 && !account_status_denied(&self.paths, account)
352 })
353 }
354}
355
356fn free_account_resolution(
357 paths: &CachePaths,
358 inputs: &Inputs,
359 now: u64,
360 status: &'static str,
361) -> EffectivePlan {
362 let mut effective = EffectivePlan::community(status);
363 effective.free_account =
364 free_account_snapshot(paths, inputs).filter(|snapshot| snapshot.is_current(now));
365 effective
366}
367
368fn free_account_snapshot(paths: &CachePaths, inputs: &Inputs) -> Option<FreeAccountSnapshot> {
369 inputs
370 .credentials_digest
371 .map(|credentials_digest| FreeAccountSnapshot {
372 paths: paths.clone(),
373 trust_bytes: inputs.trust_bytes.clone(),
374 credentials_digest,
375 })
376}
377
378impl SnapshotGuard {
379 fn is_current(&self) -> bool {
380 let Ok(inputs) = load_inputs(&self.paths) else {
381 return false;
382 };
383 if inputs.trust_bytes != self.trust_bytes
384 || inputs.trust.binding.account_id != self.account_id
385 {
386 return false;
387 }
388 if self.paths.offline.is_none()
389 && remembered_denial(&self.paths.cache, self.account_id.as_deref())
390 {
391 return false;
392 }
393 read_leaf(
394 self.paths.offline.as_ref().unwrap_or(&self.paths.cache),
395 ENVELOPE_LIMIT,
396 )
397 .is_ok_and(|bytes| {
398 bytes == self.entitlement_bytes
399 && (self.paths.offline.is_some()
400 || !persisted_denial(&self.paths, self.account_id.as_deref(), &bytes))
401 })
402 }
403}
404
405fn attach_guard(
406 mut effective: EffectivePlan,
407 paths: &CachePaths,
408 inputs: &Inputs,
409 bytes: Vec<u8>,
410) -> EffectivePlan {
411 effective.free_account = free_account_snapshot(paths, inputs);
412 if effective.verified.is_some() {
413 effective.guard = Some(SnapshotGuard {
414 paths: paths.clone(),
415 account_id: inputs.trust.binding.account_id.clone(),
416 trust_bytes: inputs.trust_bytes.clone(),
417 entitlement_bytes: bytes,
418 });
419 }
420 effective
421}
422
423impl CachePaths {
424 fn discover() -> Result<Self, &'static str> {
425 let global = crate::core::paths::config_dir_read_only().map_err(|_| "unsafe_paths")?;
426 let cloud = crate::core::paths::data_dir_read_only()
427 .map_err(|_| "unsafe_paths")?
428 .join("cloud");
429 if !global.is_absolute() || !cloud.is_absolute() {
430 return Err("unsafe_paths");
431 }
432 let offline = match std::env::var_os("LEAN_CTX_OFFLINE_ENTITLEMENT_FILE") {
433 Some(value) => {
434 let path = PathBuf::from(value);
435 if !path.is_absolute() {
436 return Err("invalid_offline_path");
437 }
438 Some(path)
439 }
440 None => None,
441 };
442 Ok(Self {
443 trust: global.join("entitlement-trust.json"),
444 credentials: cloud.join("credentials.json"),
445 cache: cloud.join("entitlement-v1.json"),
446 offline,
447 #[cfg(test)]
448 trust_anchors: Vec::new(),
449 })
450 }
451}
452
453struct Inputs {
454 trust_bytes: Vec<u8>,
455 trust: Trust,
456 credentials: Option<super::Credentials>,
457 credentials_digest: Option<[u8; 32]>,
458}
459
460fn load_inputs(paths: &CachePaths) -> Result<Inputs, &'static str> {
461 let trust_bytes = match read_leaf(&paths.trust, TRUST_LIMIT) {
462 Ok(bytes) => bytes,
463 #[cfg(not(test))]
464 Err(error) if error.kind() == io::ErrorKind::NotFound => COMPILED_TRUST_BYTES.to_vec(),
465 Err(error) if error.kind() == io::ErrorKind::NotFound => return Err("missing_trust"),
466 Err(_) => return Err("unsafe_trust"),
467 };
468 #[cfg(test)]
469 let anchors = if paths.trust_anchors.is_empty() {
470 compiled_trust_root()?.keys
471 } else {
472 paths.trust_anchors.clone()
473 };
474 #[cfg(not(test))]
475 let root = compiled_trust_root()?;
476 #[cfg(not(test))]
477 let anchors = root.keys.clone();
478 let mut trust = Trust::parse(&trust_bytes, &anchors)?;
479 #[cfg(not(test))]
483 {
484 trust.revoked = root.revoked;
485 }
486 let mut credentials_digest = None;
487 let credentials = match read_private_leaf(&paths.credentials, CREDENTIAL_LIMIT) {
488 Ok(bytes) => {
489 credentials_digest = Some(Sha256::digest(&bytes).into());
490 let creds: super::Credentials =
491 serde_json::from_slice(&bytes).map_err(|_| "invalid_credentials")?;
492 if !valid_id(&creds.user_id) {
493 return Err("invalid_credentials");
494 }
495 Some(creds)
496 }
497 Err(error) if error.kind() == io::ErrorKind::NotFound => None,
498 Err(_) => return Err("unsafe_credentials"),
499 };
500 trust.binding.account_id = credentials.as_ref().map(|creds| creds.user_id.clone());
501 Ok(Inputs {
502 trust_bytes,
503 trust,
504 credentials,
505 credentials_digest,
506 })
507}
508
509fn compiled_trust_root() -> Result<Trust, &'static str> {
513 Trust::parse_unanchored(COMPILED_TRUST_BYTES)
514}
515
516pub(super) fn resolve_cached() -> EffectivePlan {
517 #[cfg(test)]
518 if let Some(paths) = TEST_PATHS.lock().ok().and_then(|paths| paths.clone()) {
519 return resolve_at(&paths, clock());
520 }
521 let paths = match CachePaths::discover() {
522 Ok(paths) => paths,
523 Err(status) => return EffectivePlan::community(status),
524 };
525 resolve_at(&paths, clock())
526}
527
528#[cfg(test)]
529pub(super) struct TestPathsGuard {
530 _serial: MutexGuard<'static, ()>,
531}
532
533#[cfg(test)]
534impl Drop for TestPathsGuard {
535 fn drop(&mut self) {
536 *TEST_PATHS
537 .lock()
538 .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
539 }
540}
541
542#[cfg(test)]
543pub(super) fn install_test_paths(
544 trust: PathBuf,
545 credentials: PathBuf,
546 cache: PathBuf,
547 anchors: Vec<(String, [u8; 32])>,
548) -> TestPathsGuard {
549 let serial = TEST_PATHS_SERIAL
550 .lock()
551 .unwrap_or_else(std::sync::PoisonError::into_inner);
552 let paths = CachePaths {
553 trust,
554 credentials,
555 cache,
556 offline: None,
557 trust_anchors: anchors
558 .into_iter()
559 .map(|(key_id, public_key)| EntitlementTrustKey { key_id, public_key })
560 .collect(),
561 };
562 *TEST_PATHS
563 .lock()
564 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(paths);
565 TestPathsGuard { _serial: serial }
566}
567
568#[cfg(test)]
569pub(super) fn accept_test_cache(account: &str, bytes: &[u8]) {
570 let paths = TEST_PATHS
571 .lock()
572 .unwrap_or_else(std::sync::PoisonError::into_inner)
573 .clone()
574 .expect("test entitlement paths must be installed");
575 persist_acceptance(&paths, account, bytes).expect("test acceptance receipt must persist");
576}
577
578fn resolve_at(paths: &CachePaths, now: u64) -> EffectivePlan {
579 let inputs = match load_inputs(paths) {
580 Ok(inputs) => inputs,
581 Err(status) => return EffectivePlan::community(status),
582 };
583 let offline = paths.offline.is_some();
584 if !offline && remembered_denial(&paths.cache, inputs.trust.binding.account_id.as_deref()) {
585 return EffectivePlan::community("denied");
586 }
587 let source_path = paths.offline.as_ref().unwrap_or(&paths.cache);
588 let bytes = match read_leaf(source_path, ENVELOPE_LIMIT) {
589 Ok(bytes) => bytes,
590 Err(error) => {
591 return free_account_resolution(
592 paths,
593 &inputs,
594 now,
595 if error.kind() == io::ErrorKind::NotFound {
596 "missing_entitlement"
597 } else {
598 "unsafe_entitlement"
599 },
600 );
601 }
602 };
603 if !offline && persisted_denial(paths, inputs.trust.binding.account_id.as_deref(), &bytes) {
604 return free_account_resolution(paths, &inputs, now, "denied");
607 }
608 let effective = verify_snapshot(&bytes, &inputs.trust, offline, now, PlanSource::Cached);
609 attach_guard(effective, paths, &inputs, bytes)
610}
611
612fn verify_snapshot(
613 bytes: &[u8],
614 trust: &Trust,
615 offline: bool,
616 now: u64,
617 source: PlanSource,
618) -> EffectivePlan {
619 let verified = match verify_entitlement(bytes, &trust.keys, trust.binding.context(now)) {
620 Ok(verified) => verified,
621 Err(error) => {
622 return EffectivePlan::community(match error {
623 EntitlementVerificationError::Expired => "expired",
624 EntitlementVerificationError::BindingMismatch => "binding_mismatch",
625 EntitlementVerificationError::NotYetValid
626 | EntitlementVerificationError::InvalidClock => "invalid_clock",
627 EntitlementVerificationError::UntrustedKey => "untrusted_key",
628 _ => "invalid_entitlement",
629 });
630 }
631 };
632 let claims = verified.claims();
633 if trust.revoked.contains(&claims.entitlement_id) {
634 return EffectivePlan::community("revoked");
635 }
636 if offline
637 && (claims.kind != EntitlementKindV1::OfflineEnterprise
638 || trust.binding.deployment == EntitlementDeploymentV1::Hosted)
639 {
640 return EffectivePlan::community("invalid_offline_entitlement");
641 }
642 if !offline && claims.kind != EntitlementKindV1::OnlineSubscription {
643 return EffectivePlan::community("offline_artifact_required");
644 }
645 let status = if now < claims.expires_at {
646 "verified_active"
647 } else {
648 "verified_grace"
649 };
650 let verified_at = Some(claims.issued_at as i64);
651 let grace_days = ((claims.grace_until - claims.expires_at) / 86_400) as i64;
652 EffectivePlan {
653 plan: verified.plan(),
654 supporter_recognition: verified.plan() != Plan::Community,
655 source,
656 verified_at,
657 grace_days,
658 verification_status: status,
659 verified: Some(verified),
660 binding: Some(trust.binding.clone()),
661 guard: None,
662 free_account: None,
663 }
664}
665
666enum FetchOutcome {
667 Envelope(Vec<u8>),
668 Outage,
669 Denied,
670 Rejected,
671}
672
673pub(super) struct AuthorizedCloudAccess {
675 pub(super) bearer: String,
676 pub(super) api_key: String,
677 pub(super) account_id: String,
678 resolution: EffectivePlan,
679 capability: String,
680 auth_expires_at: Option<u64>,
681}
682
683impl AuthorizedCloudAccess {
684 pub(super) fn ensure_valid(&self) -> Result<(), String> {
688 self.ensure_valid_at(clock()).map_err(|()| denied_message())
689 }
690
691 fn ensure_valid_at(&self, now: u64) -> Result<(), ()> {
692 if self.auth_expires_at.is_some_and(|expiry| now >= expiry)
693 || !self.resolution.current_allows_at(&self.capability, now)
694 {
695 return Err(());
696 }
697 Ok(())
698 }
699}
700
701pub(super) fn authorize_cloud_write(capability: &str) -> Result<AuthorizedCloudAccess, String> {
702 let paths = CachePaths::discover().map_err(|_| denied_message())?;
703 authorize_at(&paths, capability, clock()).map_err(|()| denied_message())
704}
705
706fn denied_message() -> String {
707 format!(
708 "{} signed account-bound entitlement and current authentication required",
709 super::ENTITLEMENT_DENIAL_PREFIX
710 )
711}
712
713fn authorize_at(
714 paths: &CachePaths,
715 capability: &str,
716 now: u64,
717) -> Result<AuthorizedCloudAccess, ()> {
718 let inputs = load_inputs(paths).map_err(|_| ())?;
721 let entry = crate::core::product_capabilities::registry()
722 .find(capability)
723 .ok_or(())?;
724 if !entry.account_required || !entry.managed_cloud_available {
725 return Err(());
726 }
727 if paths.offline.is_some()
728 || inputs.trust.binding.deployment == EntitlementDeploymentV1::AirGapped
729 || remembered_denial(&paths.cache, inputs.trust.binding.account_id.as_deref())
730 {
731 return Err(());
732 }
733 let credentials = inputs.credentials.as_ref().ok_or(())?;
734 if entry.minimum_plan() == Plan::Community {
735 let effective = free_account_resolution(paths, &inputs, now, "authenticated_free");
736 if !effective.allows_at(capability, now) || !valid_token(&credentials.api_key) {
737 return Err(());
738 }
739 return Ok(AuthorizedCloudAccess {
740 bearer: credentials_bearer(credentials, now).ok_or(())?.to_owned(),
741 api_key: credentials.api_key.clone(),
742 account_id: credentials.user_id.clone(),
743 resolution: effective,
744 capability: capability.to_owned(),
745 auth_expires_at: credentials
746 .oauth_access_token
747 .as_ref()
748 .and(credentials.oauth_expires_at_unix)
749 .and_then(|expiry| u64::try_from(expiry).ok()),
750 });
751 }
752 let bytes = read_leaf(&paths.cache, ENVELOPE_LIMIT).map_err(|_| ())?;
753 if persisted_denial(paths, Some(&credentials.user_id), &bytes) {
754 return Err(());
755 }
756 let effective = verify_snapshot(&bytes, &inputs.trust, false, now, PlanSource::Cached);
757 if effective.verified.is_none() || !effective.allows_at(capability, now) {
758 return Err(());
759 }
760 let bearer = credentials_bearer(credentials, now).ok_or(())?.to_owned();
761 if !valid_token(&credentials.api_key) {
762 return Err(());
763 }
764 Ok(AuthorizedCloudAccess {
765 bearer,
766 api_key: credentials.api_key.clone(),
767 account_id: credentials.user_id.clone(),
768 resolution: attach_guard(effective, paths, &inputs, bytes),
769 capability: capability.to_owned(),
770 auth_expires_at: credentials
771 .oauth_access_token
772 .as_ref()
773 .and(credentials.oauth_expires_at_unix)
774 .and_then(|expiry| u64::try_from(expiry).ok()),
775 })
776}
777
778fn valid_token(value: &str) -> bool {
779 !value.is_empty()
780 && value.len() <= 16 * 1024
781 && value.bytes().all(|byte| (0x21..=0x7e).contains(&byte))
782}
783
784fn credentials_bearer(credentials: &super::Credentials, now: u64) -> Option<&str> {
785 if credentials.oauth_client_id.is_some() || credentials.oauth_access_token.is_some() {
786 let token = credentials.oauth_access_token.as_deref()?;
787 let expiry = credentials.oauth_expires_at_unix?;
788 return (expiry > 0 && (expiry as u64) > now && valid_token(token)).then_some(token);
789 }
790 valid_token(&credentials.api_key).then_some(credentials.api_key.as_str())
791}
792
793pub(super) fn refresh() -> EffectivePlan {
794 let paths = match CachePaths::discover() {
795 Ok(paths) => paths,
796 Err(status) => return EffectivePlan::community(status),
797 };
798 refresh_with(&paths, clock, fetch_online)
799}
800
801fn refresh_with(
802 paths: &CachePaths,
803 now: impl Fn() -> u64,
804 fetch: impl FnOnce(&str) -> FetchOutcome,
805) -> EffectivePlan {
806 let inputs = match load_inputs(paths) {
807 Ok(inputs) => inputs,
808 Err(status) => return EffectivePlan::community(status),
809 };
810 if paths.offline.is_some()
811 || inputs.trust.binding.deployment == EntitlementDeploymentV1::AirGapped
812 {
813 return resolve_at(paths, now());
814 }
815 let Some(credentials) = &inputs.credentials else {
816 return EffectivePlan::community("not_logged_in");
817 };
818 let Ok(lease) = RefreshLease::acquire(&paths.cache) else {
819 return EffectivePlan::community("cache_busy_or_unsafe");
820 };
821 let Some(bearer) = credentials_bearer(credentials, now()) else {
822 return EffectivePlan::community("authentication_expired");
823 };
824 let outcome = fetch(bearer);
825 if lease.ensure_valid().is_err() {
826 if !matches!(outcome, FetchOutcome::Outage) {
827 remember_denial(&paths.cache, &credentials.user_id);
828 }
829 return EffectivePlan::community("cache_persist_failed");
830 }
831 let current = match load_inputs(paths) {
834 Ok(current) => current,
835 Err(status) => return EffectivePlan::community(status),
836 };
837 if current.trust.binding.account_id != inputs.trust.binding.account_id {
838 if !matches!(outcome, FetchOutcome::Outage) {
839 remember_denial(&paths.cache, &credentials.user_id);
840 let _ = persist_denial_status(paths, &credentials.user_id);
841 }
842 return EffectivePlan::community("account_changed");
843 }
844 if current.trust_bytes != inputs.trust_bytes {
845 if !matches!(outcome, FetchOutcome::Outage) {
846 remember_denial(&paths.cache, &credentials.user_id);
847 let _ = persist_denial_status(paths, &credentials.user_id);
848 }
849 return EffectivePlan::community("trust_changed");
850 }
851 match outcome {
852 FetchOutcome::Outage => resolve_at(paths, now()),
853 FetchOutcome::Denied | FetchOutcome::Rejected => {
854 persist_denial(paths, &credentials.user_id)
855 }
856 FetchOutcome::Envelope(bytes) => {
857 let effective = verify_snapshot(&bytes, ¤t.trust, false, now(), PlanSource::Live);
858 if effective.verified.is_none() {
859 return persist_denial(paths, &credentials.user_id);
860 }
861 if atomic_replace(&paths.cache, &bytes).is_err() {
862 remember_denial(&paths.cache, &credentials.user_id);
863 return EffectivePlan::community("cache_persist_failed");
864 }
865 if persist_acceptance(paths, &credentials.user_id, &bytes).is_err() {
866 remember_denial(&paths.cache, &credentials.user_id);
867 return EffectivePlan::community("cache_persist_failed");
868 }
869 clear_denial(&paths.cache, &credentials.user_id);
870 attach_guard(effective, paths, ¤t, bytes)
871 }
872 }
873}
874
875fn fetch_online(bearer: &str) -> FetchOutcome {
876 let base = super::api_url();
877 let Ok(url) = reqwest::Url::parse(&format!(
878 "{}/api/account/entitlement",
879 base.trim_end_matches('/')
880 )) else {
881 return FetchOutcome::Rejected;
882 };
883 if url.scheme() != "https" || !url.username().is_empty() || url.password().is_some() {
885 return FetchOutcome::Rejected;
886 }
887 let agent: ureq::Agent = ureq::config::Config::builder()
888 .tls_config(crate::core::http_client::platform_tls_config())
889 .timeout_global(Some(Duration::from_secs(10)))
890 .max_redirects(0)
891 .http_status_as_error(false)
892 .build()
893 .into();
894 let Ok(response) = agent
895 .get(url.as_str())
896 .header("Authorization", &format!("Bearer {bearer}"))
897 .call()
898 else {
899 return FetchOutcome::Outage;
900 };
901 match response.status().as_u16() {
902 401 | 403 => FetchOutcome::Denied,
903 500..=599 => FetchOutcome::Outage,
904 200 => {
905 let mut bytes = Vec::new();
906 if response
907 .into_body()
908 .into_reader()
909 .take((ENVELOPE_LIMIT + 1) as u64)
910 .read_to_end(&mut bytes)
911 .is_err()
912 {
913 return FetchOutcome::Outage;
914 }
915 if bytes.len() > ENVELOPE_LIMIT {
916 FetchOutcome::Rejected
917 } else {
918 FetchOutcome::Envelope(bytes)
919 }
920 }
921 _ => FetchOutcome::Rejected,
922 }
923}
924
925#[derive(Serialize, Deserialize)]
926#[serde(deny_unknown_fields)]
927struct AccountStatus {
928 schema_version: u16,
929 account_id: String,
930 accepted_sha256: Option<String>,
933}
934
935fn bytes_digest(bytes: &[u8]) -> String {
936 crate::core::agent_identity::hex_encode(&Sha256::digest(bytes))
937}
938
939fn account_status_path(paths: &CachePaths, account: &str) -> PathBuf {
940 paths.cache.with_file_name(format!(
941 "entitlement-status-{}.json",
942 bytes_digest(account.as_bytes())
943 ))
944}
945
946#[cfg(test)]
947fn denial_marker_path(paths: &CachePaths, account: &str) -> PathBuf {
948 paths.cache.with_file_name(format!(
949 "entitlement-denial-{}.marker",
950 bytes_digest(account.as_bytes())
951 ))
952}
953
954fn persisted_denial(paths: &CachePaths, account: Option<&str>, envelope: &[u8]) -> bool {
955 #[cfg(not(test))]
956 let _ = paths;
957 let Some(account) = account else { return true };
958 if durable_denial_marker(paths, account) {
959 return true;
960 }
961 #[cfg(not(test))]
962 let Ok(status_bytes) = secure_account_status(account) else {
963 return true;
964 };
965 #[cfg(test)]
966 let status_bytes = match read_private_leaf(&account_status_path(paths, account), 1024) {
967 Err(error) if error.kind() == io::ErrorKind::NotFound => return true,
968 Err(_) => return true,
969 Ok(bytes) => bytes,
970 };
971 match serde_json::from_slice::<AccountStatus>(&status_bytes) {
972 Ok(status) => {
973 status.schema_version != 1
974 || status.account_id != account
975 || status.accepted_sha256.as_deref() != Some(bytes_digest(envelope).as_str())
976 }
977 Err(_) => true,
978 }
979}
980
981fn account_status_denied(paths: &CachePaths, account: &str) -> bool {
982 #[cfg(not(test))]
983 let _ = paths;
984 #[cfg(not(test))]
985 let result = secure_account_status(account);
986 #[cfg(test)]
987 let result = read_private_leaf(&account_status_path(paths, account), 1024);
988 let bytes = match result {
989 Ok(bytes) => bytes,
990 Err(error) if error.kind() == io::ErrorKind::NotFound => return false,
991 Err(_) => return true,
992 };
993 serde_json::from_slice::<AccountStatus>(&bytes).map_or(true, |status| {
994 status.schema_version != 1
995 || status.account_id != account
996 || status.accepted_sha256.is_none()
997 })
998}
999
1000fn persist_acceptance(paths: &CachePaths, account: &str, bytes: &[u8]) -> io::Result<()> {
1001 #[cfg(not(test))]
1002 let _ = paths;
1003 let status = AccountStatus {
1004 schema_version: 1,
1005 account_id: account.to_owned(),
1006 accepted_sha256: Some(bytes_digest(bytes)),
1007 };
1008 let encoded = serde_json::to_vec(&status).map_err(io::Error::other)?;
1009 #[cfg(test)]
1010 atomic_replace(&account_status_path(paths, account), &encoded)?;
1011 #[cfg(not(test))]
1012 secure_store_account_status(account, &encoded)?;
1013 clear_durable_denial_marker(paths, account)
1014}
1015
1016fn persist_denial(paths: &CachePaths, account: &str) -> EffectivePlan {
1017 remember_denial(&paths.cache, account);
1018 let independently_denied = persist_durable_denial_marker(paths, account).is_ok();
1022 let status_revoked =
1023 persist_denial_status(paths, account).is_ok() || revoke_acceptance(paths, account).is_ok();
1024 let cache_revoked = atomic_replace(&paths.cache, b"").is_ok();
1027 if (!status_revoked && !independently_denied) || !cache_revoked {
1028 return EffectivePlan::community("cache_persist_failed");
1029 }
1030 EffectivePlan::community("denied")
1031}
1032
1033fn durable_denial_marker(paths: &CachePaths, account: &str) -> bool {
1034 #[cfg(test)]
1035 return match read_private_leaf(&denial_marker_path(paths, account), 16) {
1036 Ok(bytes) => bytes == b"denied-v1" || !bytes.is_empty(),
1037 Err(error) => error.kind() != io::ErrorKind::NotFound,
1038 };
1039 #[cfg(not(test))]
1040 {
1041 let _ = paths;
1042 match secure_denial_marker(account) {
1043 Ok(Some(bytes)) => bytes == b"denied-v1" || !bytes.is_empty(),
1044 Ok(None) => false,
1045 Err(_) => true,
1046 }
1047 }
1048}
1049
1050fn persist_durable_denial_marker(paths: &CachePaths, account: &str) -> io::Result<()> {
1051 #[cfg(test)]
1052 return atomic_replace(&denial_marker_path(paths, account), b"denied-v1");
1053 #[cfg(not(test))]
1054 {
1055 let _ = paths;
1056 secure_store_denial_marker(account)
1057 }
1058}
1059
1060fn clear_durable_denial_marker(paths: &CachePaths, account: &str) -> io::Result<()> {
1061 #[cfg(test)]
1062 match std::fs::remove_file(denial_marker_path(paths, account)) {
1063 Ok(()) => Ok(()),
1064 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
1065 Err(error) => Err(error),
1066 }
1067 #[cfg(not(test))]
1068 {
1069 let _ = paths;
1070 secure_delete_denial_marker(account)
1071 }
1072}
1073
1074fn revoke_acceptance(paths: &CachePaths, account: &str) -> io::Result<()> {
1075 #[cfg(test)]
1076 match std::fs::remove_file(account_status_path(paths, account)) {
1077 Ok(()) => Ok(()),
1078 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
1079 Err(error) => Err(error),
1080 }
1081 #[cfg(not(test))]
1082 {
1083 let _ = paths;
1084 secure_delete_account_status(account)
1085 }
1086}
1087
1088fn persist_denial_status(paths: &CachePaths, account: &str) -> io::Result<()> {
1089 #[cfg(not(test))]
1090 let _ = paths;
1091 let denial = AccountStatus {
1092 schema_version: 1,
1093 account_id: account.to_owned(),
1094 accepted_sha256: None,
1095 };
1096 let bytes = serde_json::to_vec(&denial).map_err(io::Error::other)?;
1097 #[cfg(test)]
1098 return atomic_replace(&account_status_path(paths, account), &bytes);
1099 #[cfg(not(test))]
1100 secure_store_account_status(account, &bytes)
1101}
1102
1103#[cfg(all(
1104 not(test),
1105 any(target_os = "macos", target_os = "windows", target_os = "linux")
1106))]
1107fn secure_status_entry(account: &str) -> io::Result<keyring::Entry> {
1108 keyring::Entry::new(
1109 "com.leanctx.entitlement.v1",
1110 &bytes_digest(account.as_bytes()),
1111 )
1112 .map_err(io::Error::other)
1113}
1114
1115#[cfg(all(
1116 not(test),
1117 any(target_os = "macos", target_os = "windows", target_os = "linux")
1118))]
1119fn secure_denial_entry(account: &str) -> io::Result<keyring::Entry> {
1120 keyring::Entry::new(
1121 "com.leanctx.entitlement.denial.v1",
1122 &bytes_digest(account.as_bytes()),
1123 )
1124 .map_err(io::Error::other)
1125}
1126
1127#[cfg(all(
1128 not(test),
1129 any(target_os = "macos", target_os = "windows", target_os = "linux")
1130))]
1131fn secure_denial_marker(account: &str) -> io::Result<Option<Vec<u8>>> {
1132 match secure_denial_entry(account)?.get_secret() {
1133 Ok(bytes) => Ok(Some(bytes)),
1134 Err(keyring::Error::NoEntry) => Ok(None),
1135 Err(error) => Err(io::Error::other(error)),
1136 }
1137}
1138
1139#[cfg(all(
1140 not(test),
1141 any(target_os = "macos", target_os = "windows", target_os = "linux")
1142))]
1143fn secure_store_denial_marker(account: &str) -> io::Result<()> {
1144 secure_denial_entry(account)?
1145 .set_secret(b"denied-v1")
1146 .map_err(io::Error::other)
1147}
1148
1149#[cfg(all(
1150 not(test),
1151 any(target_os = "macos", target_os = "windows", target_os = "linux")
1152))]
1153fn secure_delete_denial_marker(account: &str) -> io::Result<()> {
1154 match secure_denial_entry(account)?.delete_credential() {
1155 Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
1156 Err(error) => Err(io::Error::other(error)),
1157 }
1158}
1159
1160#[cfg(all(
1161 not(test),
1162 any(target_os = "macos", target_os = "windows", target_os = "linux")
1163))]
1164fn secure_account_status(account: &str) -> io::Result<Vec<u8>> {
1165 match secure_status_entry(account)?.get_secret() {
1166 Ok(bytes) => Ok(bytes),
1167 Err(keyring::Error::NoEntry) => Err(io::ErrorKind::NotFound.into()),
1168 Err(error) => Err(io::Error::other(error)),
1169 }
1170}
1171
1172#[cfg(all(
1173 not(test),
1174 any(target_os = "macos", target_os = "windows", target_os = "linux")
1175))]
1176fn secure_store_account_status(account: &str, bytes: &[u8]) -> io::Result<()> {
1177 secure_status_entry(account)?
1178 .set_secret(bytes)
1179 .map_err(io::Error::other)
1180}
1181
1182#[cfg(all(
1183 not(test),
1184 any(target_os = "macos", target_os = "windows", target_os = "linux")
1185))]
1186fn secure_delete_account_status(account: &str) -> io::Result<()> {
1187 match secure_status_entry(account)?.delete_credential() {
1188 Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
1189 Err(error) => Err(io::Error::other(error)),
1190 }
1191}
1192
1193#[cfg(all(
1194 not(test),
1195 not(any(target_os = "macos", target_os = "windows", target_os = "linux"))
1196))]
1197fn secure_account_status(_account: &str) -> io::Result<Vec<u8>> {
1198 Err(io::Error::new(
1199 io::ErrorKind::Unsupported,
1200 "secure entitlement state unavailable",
1201 ))
1202}
1203
1204#[cfg(all(
1205 not(test),
1206 not(any(target_os = "macos", target_os = "windows", target_os = "linux"))
1207))]
1208fn secure_store_account_status(_account: &str, _bytes: &[u8]) -> io::Result<()> {
1209 Err(io::Error::new(
1210 io::ErrorKind::Unsupported,
1211 "secure entitlement state unavailable",
1212 ))
1213}
1214
1215#[cfg(all(
1216 not(test),
1217 not(any(target_os = "macos", target_os = "windows", target_os = "linux"))
1218))]
1219fn secure_delete_account_status(_account: &str) -> io::Result<()> {
1220 Err(io::Error::new(
1221 io::ErrorKind::Unsupported,
1222 "secure entitlement state unavailable",
1223 ))
1224}
1225
1226#[cfg(all(
1227 not(test),
1228 not(any(target_os = "macos", target_os = "windows", target_os = "linux"))
1229))]
1230fn secure_denial_marker(_account: &str) -> io::Result<Option<Vec<u8>>> {
1231 Err(io::Error::new(
1232 io::ErrorKind::Unsupported,
1233 "secure entitlement state unavailable",
1234 ))
1235}
1236
1237#[cfg(all(
1238 not(test),
1239 not(any(target_os = "macos", target_os = "windows", target_os = "linux"))
1240))]
1241fn secure_store_denial_marker(_account: &str) -> io::Result<()> {
1242 Err(io::Error::new(
1243 io::ErrorKind::Unsupported,
1244 "secure entitlement state unavailable",
1245 ))
1246}
1247
1248#[cfg(all(
1249 not(test),
1250 not(any(target_os = "macos", target_os = "windows", target_os = "linux"))
1251))]
1252fn secure_delete_denial_marker(_account: &str) -> io::Result<()> {
1253 Err(io::Error::new(
1254 io::ErrorKind::Unsupported,
1255 "secure entitlement state unavailable",
1256 ))
1257}
1258
1259fn remembered_denial(path: &Path, account: Option<&str>) -> bool {
1260 if DENIAL_TRACKING_FAILED.load(Ordering::Acquire) {
1261 return true;
1262 }
1263 let Ok(denials) = denial_memory() else {
1264 return true;
1265 };
1266 denials.len() >= 256
1268 || denials
1269 .iter()
1270 .any(|(p, a)| p == path && Some(a.as_str()) == account)
1271}
1272
1273fn remember_denial(path: &Path, account: &str) {
1274 match denial_memory() {
1275 Ok(mut denials) => {
1276 if denials.len() < 256 && !denials.iter().any(|(p, a)| p == path && a == account) {
1277 denials.push((path.to_owned(), account.to_owned()));
1278 }
1279 }
1280 Err(()) => DENIAL_TRACKING_FAILED.store(true, Ordering::Release),
1281 }
1282}
1283
1284fn clear_denial(path: &Path, account: &str) {
1285 if let Ok(mut denials) = denial_memory() {
1286 denials.retain(|(p, a)| p != path || a != account);
1287 }
1288}
1289
1290fn denial_memory() -> Result<MutexGuard<'static, Vec<(PathBuf, String)>>, ()> {
1291 let started = Instant::now();
1292 loop {
1293 match DENIAL_MEMORY.try_lock() {
1294 Ok(guard) => return Ok(guard),
1295 Err(TryLockError::WouldBlock) if started.elapsed() < Duration::from_millis(20) => {
1296 std::thread::yield_now();
1297 }
1298 Err(TryLockError::WouldBlock | TryLockError::Poisoned(_)) => return Err(()),
1299 }
1300 }
1301}
1302
1303fn clock() -> u64 {
1304 SystemTime::now()
1305 .duration_since(UNIX_EPOCH)
1306 .map_or(u64::MAX, |duration| duration.as_secs())
1307}
1308
1309#[path = "entitlement_cache_io.rs"]
1310mod secure_io;
1311use secure_io::{RefreshLease, atomic_replace, read_leaf, read_private_leaf};
1312#[cfg(all(test, unix))]
1313use secure_io::{atomic_replace_with, read_leaf_with};
1314
1315#[cfg(test)]
1316#[path = "entitlement_cache_tests.rs"]
1317mod tests;