1use std::fmt;
6
7use lean_ctx_protocol::cloud::lease::CloudPlan;
8use lean_ctx_protocol::cloud::{
9 CloudErrorBody, CloudErrorCode, CloudErrorDetailV1, CloudUploadKind,
10};
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum CloudError {
14 Offline(String),
16 NotConnected,
18 Unauthorized,
20 PlanRequired(Box<PlanNeed>),
23 InstanceLimit(Box<InstanceCap>),
26 QuotaExceeded(Box<Quota>),
30 StorageFull(Box<StorageFull>),
34 UploadRateLimited {
38 retry_after: Option<u64>,
39 per_hour: Option<u64>,
41 },
42 PolicyDenied(PolicyDenial),
45 LeaseLapsed,
47 Revoked(Revocation),
51 Forbidden,
53 Vetoed,
56 UploadDisabled(CloudUploadKind),
59 FeatureDisabled {
63 feature: Option<String>,
64 },
65 NotFound,
66 Conflict {
67 expected: Option<u64>,
68 actual: Option<u64>,
69 },
70 ScreeningBlocked,
71 UpgradeRequired {
72 min: Option<String>,
73 },
74 RateLimited {
75 retry_after: Option<u64>,
76 },
77 DeviceFlow(String),
79 TrialUnsupported {
83 origin: String,
85 },
86 Protocol(String),
89 Config(String),
91 Local(String),
93 Refused(String),
96 Task {
98 refusal: TaskRefusal,
99 number: Option<u64>,
100 detail: Option<String>,
102 },
103 Server {
105 status: u16,
106 code: String,
107 },
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct Quota {
113 pub status: u16,
115 pub resource: String,
118 pub limit: Option<u64>,
119 pub used: Option<u64>,
120 pub reset_at: Option<String>,
122 pub retry_after: Option<u64>,
124 pub cooldown_days: Option<u32>,
126 pub next_step: Option<NextStep>,
128}
129
130#[derive(Debug, Clone, PartialEq, Eq, Default)]
132pub struct InstanceCap {
133 pub resource: Option<String>,
136 pub limit: Option<u64>,
137 pub used: Option<u64>,
138 pub seats: Option<u64>,
140 pub per_seat: Option<u64>,
141 pub next_step: Option<NextStep>,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Default)]
146pub struct StorageFull {
147 pub limit: Option<u64>,
148 pub used: Option<u64>,
149 pub next_step: Option<NextStep>,
150}
151
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum NextStep {
155 Subscribe,
156 TopUp,
157 UpgradeTeam,
158 AddSeats,
159 Contact,
160 Wait,
161}
162
163impl NextStep {
164 #[must_use]
166 pub fn of_wire(value: Option<&str>) -> Option<Self> {
167 Some(match value? {
168 "subscribe" => Self::Subscribe,
169 "top_up" => Self::TopUp,
170 "upgrade_team" => Self::UpgradeTeam,
171 "add_seats" => Self::AddSeats,
172 "contact" => Self::Contact,
173 "wait" => Self::Wait,
174 _ => return None,
175 })
176 }
177
178 #[must_use]
181 pub fn hint(self) -> Option<&'static str> {
182 Some(match self {
183 Self::Subscribe => "choose a plan in the Cloud",
184 Self::TopUp => "a top-up in the Cloud adds more",
185 Self::UpgradeTeam => "Team gives every seat its own allowance",
186 Self::AddSeats => "every seat you add in the Cloud brings its own allowance",
187 Self::Contact => "contact us to extend your Enterprise contract",
188 Self::Wait => return None,
189 })
190 }
191}
192
193fn write_hint(f: &mut fmt::Formatter<'_>, next: Option<NextStep>) -> fmt::Result {
195 match next.and_then(NextStep::hint) {
196 Some(hint) => write!(f, "; {hint}"),
197 None => Ok(()),
198 }
199}
200
201fn bytes_text(bytes: u64) -> String {
203 const UNITS: [(&str, u64); 4] = [
204 ("TiB", 1 << 40),
205 ("GiB", 1 << 30),
206 ("MiB", 1 << 20),
207 ("KiB", 1 << 10),
208 ];
209 for (unit, size) in UNITS {
210 if bytes >= size {
211 let tenths = u128::from(bytes) * 10 / u128::from(size);
212 return if tenths % 10 == 0 {
213 format!("{} {unit}", tenths / 10)
214 } else {
215 format!("{}.{} {unit}", tenths / 10, tenths % 10)
216 };
217 }
218 }
219 format!("{bytes} B")
220}
221
222#[must_use]
225pub fn amount_text(resource: &str, value: u64) -> String {
226 if resource.ends_with("_bytes") {
227 bytes_text(value)
228 } else if resource.ends_with("_usd_micros") {
229 format!("${}.{:02}", value / 1_000_000, value % 1_000_000 / 10_000)
230 } else {
231 value.to_string()
232 }
233}
234
235#[derive(Debug, Clone, PartialEq, Eq, Default)]
237pub struct PlanNeed {
238 pub feature: Option<String>,
241 pub plan_needed: Option<String>,
243 pub limit: Option<u64>,
245 pub used: Option<u64>,
246 pub message: Option<String>,
248 pub plan: Option<CloudPlan>,
251 pub reason: Option<String>,
255 pub next_step: Option<NextStep>,
257 pub plans_url: Option<String>,
260 pub trial_reason: Option<String>,
263}
264
265pub const LOCKED_MARK: &str = "this workspace is locked (read and export only)";
268
269pub const PLAN_LIMITS: &str = "Personal up to 3 hosts registered, up to 2 connected at once; Team and Enterprise up to 3 hosts registered, up to 2 connected at once per seat";
273
274pub const HOSTS_REGISTERED: &str = "hosts registered";
277
278pub const HOSTS_CONNECTED: &str = "hosts connected at once";
281
282pub const FREE_REGISTERED: &str = "to free one, revoke a host you no longer use on the Hosts page";
285
286pub const FREE_CONNECTED: &str =
288 "to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine)";
289
290impl PlanNeed {
291 #[must_use]
293 pub fn locked(&self) -> Option<&str> {
294 self.reason
295 .as_deref()
296 .filter(|r| matches!(*r, "trial_ended" | "plan_ended"))
297 }
298
299 #[must_use]
301 pub fn trial_used(&self) -> bool {
302 self.reason.as_deref() == Some(TRIAL_USED)
303 }
304
305 fn plan_word(&self) -> &'static str {
307 let team = self.plan_needed.as_deref() == Some("team")
308 || matches!(self.plan, Some(CloudPlan::Team | CloudPlan::Enterprise));
309 if team { "Team" } else { "Personal" }
310 }
311}
312
313#[must_use]
315pub fn locked_line(reason: &str, plan_word: &str) -> String {
316 let what = if reason == "trial_ended" {
317 format!("Your {plan_word} trial has ended")
318 } else {
319 "Your plan has ended".to_string()
320 };
321 format!("{what}: {LOCKED_MARK}. Choose a plan in the Cloud to sync again.")
322}
323
324fn plans_from(needed: &str) -> Option<&'static str> {
326 Some(match needed {
327 "personal" => "Personal, Team and Enterprise",
328 "team" => "Team and Enterprise",
329 "enterprise" => "Enterprise",
330 _ => return None,
331 })
332}
333
334fn write_plan_need(f: &mut fmt::Formatter<'_>, need: &PlanNeed) -> fmt::Result {
335 if need.trial_used() {
336 let plan = need.plan_word();
337 match need.trial_reason.as_deref() {
338 Some("trial_ended") => write!(
339 f,
340 "the {plan} trial of this address has ended; no second trial starts. Choose a plan"
341 )?,
342 Some("no_plan") => write!(
343 f,
344 "this address has no {plan} trial left and no plan; no second trial starts. Choose a plan"
345 )?,
346 _ => write!(
347 f,
348 "this address already had its {plan} trial; no second trial starts. Choose a plan"
349 )?,
350 }
351 return match need.plans_url.as_deref().filter(|u| u.starts_with("http")) {
352 Some(url) => write!(f, " at {url}, then run `lean-ctx cloud connect`"),
353 None => f.write_str(" in the Cloud, then run `lean-ctx cloud connect`"),
354 };
355 }
356 if let Some(reason) = need.locked() {
358 return f.write_str(&locked_line(reason, need.plan_word()));
359 }
360 let Some(feature) = need.feature.as_deref() else {
361 return write!(
363 f,
364 "your plan does not include the Cloud on this machine ({PLAN_LIMITS})"
365 );
366 };
367 let plans = need.plan_needed.as_deref().and_then(plans_from);
368 let on = need
369 .plan
370 .filter(|p| *p != CloudPlan::Unknown)
371 .map(|p| match p {
372 CloudPlan::NoPlan => "; this workspace has no plan".to_string(),
373 p => format!("; this workspace is on {}", p.display_name()),
374 })
375 .unwrap_or_default();
376 match feature {
377 "repos" | "vaults" | "private_vaults" => {
378 f.write_str("this workspace has used all its vaults")?;
379 if let (Some(used), Some(limit)) = (need.used, need.limit) {
380 write!(f, " ({used} of {limit})")?;
381 }
382 if let Some(plans) = plans {
383 write!(f, "; more are included in {plans}")?;
384 }
385 write!(
386 f,
387 "{on}; remove or publish a vault in the Cloud, or upgrade the plan"
388 )
389 }
390 other => {
391 match (&need.message, plans) {
392 (Some(message), _) => f.write_str(message.trim_end_matches('.'))?,
393 (None, Some(plans)) => {
394 write!(f, "{} is included in {plans}", other.replace('_', " "))?;
395 }
396 (None, None) => write!(
397 f,
398 "this workspace's plan does not include {}",
399 other.replace('_', " ")
400 )?,
401 }
402 f.write_str(&on)
403 }
404 }
405}
406
407pub const MONTHLY_RESOURCES: &[&str] =
409 &["transfer_bytes", "bus_messages", "model_credit_usd_micros"];
410
411impl Quota {
412 #[must_use]
414 pub fn waits(&self) -> bool {
415 self.status == 429 || MONTHLY_RESOURCES.contains(&self.resource.as_str())
416 }
417
418 #[must_use]
420 pub fn cooling_slot(&self) -> bool {
421 self.resource == "registered_instances"
422 && self.cooldown_days.is_some_and(|d| d > 0)
423 && self.reset_at.is_some()
424 }
425}
426
427#[derive(Debug, Clone, PartialEq, Eq, Default)]
429pub struct PolicyDenial {
430 pub member: Option<String>,
432 pub level: Option<String>,
434 pub action: Option<String>,
436}
437
438fn wire_token(value: Option<&str>, max: usize) -> Option<String> {
440 value
441 .filter(|s| {
442 (1..=max).contains(&s.len())
443 && s.bytes().all(|b| {
444 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-')
445 })
446 })
447 .map(str::to_string)
448}
449
450pub(crate) fn wire_time(value: Option<&str>) -> Option<String> {
452 let parsed = lean_ctx_time::OffsetDateTime::parse_from_rfc3339(value?).ok()?;
453 Some(
454 parsed
455 .to_utc()
456 .to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
457 )
458}
459
460pub const TRIAL_USED: &str = "trial_used";
462pub const NOT_READY: &str = "not_ready";
465pub const VAULT_CREATE_FORBIDDEN: &str = "vault_create_forbidden";
468
469fn web_url(value: Option<&str>) -> Option<String> {
475 value
476 .filter(|s| {
477 (s.starts_with("https://")
478 || s.starts_with("http://")
479 || (s.starts_with('/') && !s.starts_with("//")))
480 && s.len() <= 512
481 && !s.chars().any(hidden_in_url)
482 })
483 .map(str::to_string)
484}
485
486fn hidden_in_url(c: char) -> bool {
488 use unicode_general_category::{GeneralCategory, get_general_category};
489 c.is_control()
490 || c.is_whitespace()
491 || get_general_category(c) == GeneralCategory::Format
492 || lean_ctx_protocol::cloud::invisible(c)
493}
494
495fn same_origin(url: &str, base: &str) -> bool {
498 let Some(start) = url.find("://").map(|i| i + 3) else {
499 return false;
500 };
501 let end = url[start..]
502 .find(['/', '?', '#'])
503 .map_or(url.len(), |i| start + i);
504 url[..end].eq_ignore_ascii_case(base)
505}
506
507#[derive(Debug, Clone, PartialEq, Eq, Default)]
509pub struct Revocation {
510 pub workspace: Option<String>,
512 pub reason: Option<String>,
514 pub revoked_at: Option<u64>,
516 pub instance_id: Option<String>,
518}
519
520impl Revocation {
521 fn of_statement(statement: &serde_json::Value) -> Self {
524 let token = |v: &serde_json::Value, max: usize| {
525 v.as_str()
526 .filter(|s| {
527 (1..=max).contains(&s.len())
528 && s.bytes().all(|b| {
529 b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-'
530 })
531 })
532 .map(str::to_string)
533 };
534 Self {
535 workspace: None,
536 reason: token(&statement["reason"], 32),
537 revoked_at: statement["revoked_at"].as_u64(),
538 instance_id: token(&statement["instance_id"], 36),
539 }
540 }
541}
542
543#[derive(Debug, Clone, Copy, PartialEq, Eq)]
545pub enum PermitCheck {
546 Presence,
548 Role,
550 Unknown,
552}
553
554#[derive(Debug, Clone, Copy, PartialEq, Eq)]
556pub enum TaskRefusal {
557 Claimed,
559 NotOpen,
561 StaleClaim,
563 Closed,
565 SelfVerify,
567 NotSubmitted,
569 NotPermitted(PermitCheck),
571 OptinScope,
574 OptinChanged,
577 OptinInactive,
580 DailyBudget { retry_after: Option<u64> },
583 StaleBase,
586 PersonUnproven,
589 SignatureExpired,
592}
593
594impl TaskRefusal {
595 fn from_reason(
596 code: CloudErrorCode,
597 reason: Option<&str>,
598 retry_after: Option<u64>,
599 check: Option<&str>,
600 ) -> Option<Self> {
601 Some(match (code, reason?) {
602 (CloudErrorCode::InvalidState, "task_claimed") => Self::Claimed,
603 (CloudErrorCode::InvalidState, "task_not_open") => Self::NotOpen,
604 (CloudErrorCode::InvalidState, "stale_claim") => Self::StaleClaim,
605 (CloudErrorCode::InvalidState, "task_closed") => Self::Closed,
606 (CloudErrorCode::ForbiddenRight, "self_verify") => Self::SelfVerify,
607 (CloudErrorCode::InvalidState, "not_submitted") => Self::NotSubmitted,
608 (CloudErrorCode::ForbiddenRight, "not_permitted") => Self::NotPermitted(match check {
609 Some("presence") => PermitCheck::Presence,
610 Some("role") => PermitCheck::Role,
611 _ => PermitCheck::Unknown,
612 }),
613 (CloudErrorCode::ForbiddenRight, "optin_scope") => Self::OptinScope,
614 (CloudErrorCode::ForbiddenRight, "person_unproven") => Self::PersonUnproven,
615 (CloudErrorCode::ForbiddenRight, "signature_expired") => Self::SignatureExpired,
616 (CloudErrorCode::InvalidState, "optin_changed") => Self::OptinChanged,
617 (CloudErrorCode::InvalidState, "optin_inactive") => Self::OptinInactive,
618 (CloudErrorCode::RateLimited, "daily_budget") => Self::DailyBudget { retry_after },
619 (CloudErrorCode::InvalidState | CloudErrorCode::RevisionConflict, "stale_base") => {
620 Self::StaleBase
621 }
622 _ => return None,
623 })
624 }
625
626 #[must_use]
629 pub fn ends_claim(self) -> bool {
630 matches!(self, Self::StaleClaim | Self::Closed | Self::OptinInactive)
631 }
632}
633
634impl fmt::Display for TaskRefusal {
635 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
636 match self {
637 Self::Claimed => f.write_str("another agent holds the task"),
638 Self::NotOpen => f.write_str("the task is not open"),
639 Self::StaleClaim => f.write_str("this claim is no longer the task's claim"),
640 Self::Closed => f.write_str("the task is closed"),
641 Self::SelfVerify => f.write_str(
642 "the agent that did the work does not check its own result; another agent verifies it",
643 ),
644 Self::NotSubmitted => f.write_str("the task has no result waiting for a check"),
645 Self::NotPermitted(PermitCheck::Presence) => f.write_str(
646 "this agent is not on the bus: its session (or the relay) must be running and announce it with the task's role",
647 ),
648 Self::NotPermitted(PermitCheck::Role) => {
649 f.write_str("this agent is on the bus in another role than the task needs")
650 }
651 Self::NotPermitted(PermitCheck::Unknown) => f.write_str(
652 "the task's role or the owner's worker consent does not allow this agent",
653 ),
654 Self::OptinScope => f.write_str("this instance's opt-in does not cover this vault"),
655 Self::OptinChanged => f.write_str("the opt-in changed; it is read again"),
656 Self::OptinInactive => f.write_str(
657 "this instance is not opted in (or the owner stopped worker mode on the web)",
658 ),
659 Self::StaleBase => f.write_str(
660 "the task's priority or labels changed meanwhile; read it again and retry",
661 ),
662 Self::PersonUnproven => f.write_str(
663 "the app's signature on this task did not check out; propose it again in the app",
664 ),
665 Self::SignatureExpired => f.write_str(
666 "the app's signature on this task is too old; propose it again in the app",
667 ),
668 Self::DailyBudget { retry_after } => match retry_after {
669 Some(s) => write!(f, "today's task budget is used up (resets in {s} s)"),
670 None => f.write_str("today's task budget is used up"),
671 },
672 }
673 }
674}
675
676fn bus_role(role: Option<&String>) -> Option<&str> {
679 role.map(String::as_str).filter(|r| {
680 (1..=64).contains(&r.len())
681 && r.bytes()
682 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
683 })
684}
685
686pub(crate) fn safe_message(message: &str) -> Option<String> {
689 let text: String = message
690 .chars()
691 .map(|c| if c.is_control() { ' ' } else { c })
692 .take(300)
693 .collect();
694 let text = text.trim();
695 (!text.is_empty()).then(|| text.to_string())
696}
697
698fn permit_line(refusal: TaskRefusal, detail: &CloudErrorDetailV1) -> Option<String> {
702 let TaskRefusal::NotPermitted(check) = refusal else {
703 return None;
704 };
705 let mut line =
706 safe_message(&detail.message).unwrap_or_else(|| match permit_roles(refusal, detail) {
707 Some(roles) => format!("{refusal} ({roles})"),
708 None => refusal.to_string(),
709 });
710 match check {
711 PermitCheck::Presence => line.push_str(
712 " [check: presence] Run `lean-ctx cloud bus relay --for 30`: it says who this machine announced, or why an agent is missing. The Cloud keeps an agent present only while a relay stays connected (the daemon's), so claim while it runs.",
713 ),
714 PermitCheck::Role => line.push_str(" [check: role]"),
715 PermitCheck::Unknown => {}
716 }
717 Some(line)
718}
719
720fn permit_roles(refusal: TaskRefusal, detail: &CloudErrorDetailV1) -> Option<String> {
722 let role = bus_role(detail.role.as_ref())?;
723 match refusal {
724 TaskRefusal::NotPermitted(PermitCheck::Presence) => {
725 Some(format!("the task needs role {role}"))
726 }
727 TaskRefusal::NotPermitted(PermitCheck::Role) => {
728 Some(match bus_role(detail.agent_role.as_ref()) {
729 Some(agent_role) => {
730 format!("the agent works as {agent_role}, the task needs {role}")
731 }
732 None => format!("the task needs role {role}"),
733 })
734 }
735 _ => None,
736 }
737}
738
739fn lenient_u64(value: &serde_json::Value) -> Option<u64> {
741 value
742 .as_u64()
743 .or_else(|| value.as_str().and_then(|s| s.trim().parse().ok()))
744}
745
746fn lenient_detail(error: &serde_json::Value) -> Option<CloudErrorDetailV1> {
751 let object = error.as_object()?;
752 let code = object.get("code").filter(|c| c.is_string())?.clone();
753 let message = object
754 .get("message")
755 .filter(|m| m.is_string())
756 .cloned()
757 .unwrap_or_else(|| serde_json::Value::String(String::new()));
758 let base = || {
759 let mut kept = serde_json::Map::new();
760 kept.insert("code".into(), code.clone());
761 kept.insert("message".into(), message.clone());
762 kept
763 };
764 let decodes = |kept: &serde_json::Map<String, serde_json::Value>| {
765 serde_json::from_value::<CloudErrorDetailV1>(serde_json::Value::Object(kept.clone()))
766 .is_ok()
767 };
768 let mut kept = base();
769 for (name, value) in object {
770 if matches!(name.as_str(), "code" | "message") {
771 continue;
772 }
773 let candidates = [
774 Some(value.clone()),
775 lenient_u64(value).map(serde_json::Value::from),
776 ];
777 for candidate in candidates.into_iter().flatten() {
778 let mut probe = base();
779 probe.insert(name.clone(), candidate.clone());
780 if decodes(&probe) {
781 kept.insert(name.clone(), candidate);
782 break;
783 }
784 }
785 }
786 serde_json::from_value(serde_json::Value::Object(kept)).ok()
787}
788
789fn task_key_refusal(status: u16, body: &serde_json::Value) -> Option<String> {
793 let error = &body["error"];
794 let code = error["code"].as_str()?;
795 let reason = error["reason"].as_str();
796 match (status, code) {
797 (400, "invalid_field") if error["field"].as_str() == Some("task_propose_key") => {
798 Some(TASK_KEY_INVALID.into())
799 }
800 (409, "invalid_state") => reason
801 .filter(|r| matches!(*r, TASK_KEY_BOUND | TASK_KEY_CLEARED))
802 .map(str::to_owned),
803 _ => None,
804 }
805}
806
807fn optin_key_refusal(status: u16, body: &serde_json::Value) -> Option<String> {
811 let error = &body["error"];
812 let code = error["code"].as_str()?;
813 match (status, code) {
814 (400, "invalid_field")
815 if matches!(
816 error["field"].as_str(),
817 Some("optin_key" | "optin_key.bind_signature")
818 ) =>
819 {
820 Some(OPTIN_KEY_INVALID.into())
821 }
822 (409, _) => [code, error["reason"].as_str().unwrap_or_default()]
823 .into_iter()
824 .find(|name| matches!(*name, OPTIN_KEY_BOUND | OPTIN_KEY_CLEARED))
825 .map(str::to_owned),
826 _ => None,
827 }
828}
829
830pub const OPTIN_KEY_INVALID: &str = "optin_key_invalid";
832pub const OPTIN_KEY_BOUND: &str = "optin_key_bound";
834pub const OPTIN_KEY_CLEARED: &str = "optin_key_cleared";
836
837pub const APP_KEY_NOT_ANNOUNCED: &str = "app_key_not_announced";
840pub const APP_KEY_BIND_INVALID: &str = "app_key_bind_invalid";
843pub const APP_KEYS_INVALID: &str = "app_keys_invalid";
846pub const TASK_KEY_INVALID: &str = "task_propose_key_invalid";
848pub const TASK_KEY_BOUND: &str = "task_propose_key_bound";
850pub const TASK_KEY_CLEARED: &str = "task_propose_key_cleared";
852
853pub const RETRY_AFTER_CAP_S: u64 = 32 * 86_400;
856
857impl CloudError {
858 pub(crate) fn from_response(status: u16, body: &serde_json::Value) -> Self {
860 let value_reason = body["error"]["reason"].clone();
861 let revocation = body["error"]["revocation"].clone();
862 let trial_used = body["error"]["code"].as_str() == Some(TRIAL_USED);
863 let plans_url = web_url(body["error"]["plans_url"].as_str());
864 let decoded = serde_json::from_value::<CloudErrorBody>(body.clone())
865 .map(|body| body.error)
866 .ok()
867 .or_else(|| lenient_detail(&body["error"]));
868 if status == 400
872 && body["error"]["code"].as_str() == Some("invalid_field")
873 && let Some(reason @ (APP_KEY_NOT_ANNOUNCED | APP_KEY_BIND_INVALID)) =
874 body["error"]["reason"].as_str()
875 {
876 return Self::Server {
877 status,
878 code: reason.into(),
879 };
880 }
881 if status == 400
884 && body["error"]["code"].as_str() == Some("invalid_field")
885 && body["error"]["field"].as_str() == Some("app_keys")
886 {
887 return Self::Server {
888 status,
889 code: APP_KEYS_INVALID.into(),
890 };
891 }
892 if let Some(code) = task_key_refusal(status, body) {
897 return Self::Server { status, code };
898 }
899 if let Some(code) = optin_key_refusal(status, body) {
901 return Self::Server { status, code };
902 }
903 if matches!(status, 400 | 409)
906 && let Some(name) = [&body["error"]["reason"], &body["error"]["code"]]
907 .iter()
908 .filter_map(|v| v.as_str())
909 .find(|name| crate::auth::CHAT_KEY_REPAIR_REASONS.contains(name))
910 {
911 return Self::Server {
912 status,
913 code: name.to_owned(),
914 };
915 }
916 if status == 409 && body["error"]["code"].as_str() == Some(NOT_READY) {
919 return Self::Server {
920 status,
921 code: NOT_READY.into(),
922 };
923 }
924 if status == 403 && body["error"]["code"].as_str() == Some(VAULT_CREATE_FORBIDDEN) {
927 return Self::Forbidden;
928 }
929 let Some(mut detail) = decoded else {
930 return Self::of_status(status, lenient_u64(&body["error"]["retry_after_s"]));
931 };
932 detail.retry_after_s = detail.retry_after_s.map(|s| s.min(RETRY_AFTER_CAP_S));
935 if let Some(refusal) = TaskRefusal::from_reason(
936 detail.code,
937 detail.reason.as_deref(),
938 detail.retry_after_s,
939 detail.check.as_deref(),
940 ) {
941 return Self::Task {
942 refusal,
943 number: detail.number,
944 detail: permit_line(refusal, &detail),
945 };
946 }
947 let next_step = NextStep::of_wire(detail.next_step.as_deref());
948 if trial_used {
951 return Self::PlanRequired(Box::new(PlanNeed {
952 plan_needed: wire_token(detail.plan_needed.as_deref(), 32),
953 message: safe_message(&detail.message),
954 reason: Some(TRIAL_USED.into()),
955 next_step,
956 plans_url,
957 trial_reason: wire_token(detail.reason.as_deref(), 32),
958 ..PlanNeed::default()
959 }));
960 }
961 match detail.code {
962 CloudErrorCode::Unauthorized => Self::Unauthorized,
963 CloudErrorCode::LeaseExpired => Self::LeaseLapsed,
964 CloudErrorCode::InstanceRevoked => Self::Revoked(Revocation::of_statement(&revocation)),
965 CloudErrorCode::PlanRequired => Self::PlanRequired(Box::new(PlanNeed {
966 feature: wire_token(detail.feature.as_deref(), 64),
967 plan_needed: wire_token(detail.plan_needed.as_deref(), 32),
968 limit: detail.limit,
969 used: detail.used,
970 message: safe_message(&detail.message),
971 plan: None,
972 reason: wire_token(detail.reason.as_deref(), 32),
973 next_step,
974 plans_url: None,
975 trial_reason: None,
976 })),
977 CloudErrorCode::InstanceLimit => Self::InstanceLimit(Box::new(InstanceCap {
978 resource: wire_token(detail.resource.as_deref(), 64),
979 limit: detail.limit,
980 used: detail.used,
981 seats: detail.seats,
982 per_seat: detail.per_seat,
983 next_step,
984 })),
985 CloudErrorCode::QuotaExceeded => Self::QuotaExceeded(Box::new(Quota {
986 status,
987 resource: wire_token(detail.resource.as_deref(), 64)
988 .unwrap_or_else(|| "unknown".into()),
989 limit: detail.limit,
990 used: detail.used,
991 reset_at: wire_time(detail.reset_at.as_deref()),
992 retry_after: detail.retry_after_s,
993 cooldown_days: detail.cooldown_days,
994 next_step,
995 })),
996 CloudErrorCode::StorageQuotaExceeded => Self::StorageFull(Box::new(StorageFull {
997 limit: detail.limit_bytes.or(detail.limit),
998 used: detail.used_bytes.or(detail.used),
999 next_step,
1000 })),
1001 CloudErrorCode::UploadRateLimited => Self::UploadRateLimited {
1002 retry_after: detail.retry_after_s,
1003 per_hour: detail.limit_bytes_per_hour,
1004 },
1005 CloudErrorCode::PolicyDenied => Self::PolicyDenied(PolicyDenial {
1008 member: wire_token(detail.member.as_deref().or(detail.field.as_deref()), 80),
1009 level: wire_token(
1010 detail.level.as_deref().or(detail
1011 .reason
1012 .as_deref()
1013 .filter(|r| matches!(*r, "org" | "workspace" | "vault" | "instance"))),
1014 16,
1015 ),
1016 action: wire_token(detail.action.as_deref(), 64),
1017 }),
1018 CloudErrorCode::ForbiddenRight if value_reason.as_str() == Some("vetoed") => {
1019 Self::Vetoed
1020 }
1021 CloudErrorCode::ForbiddenRight => Self::Forbidden,
1022 CloudErrorCode::UploadDisabled => {
1023 Self::UploadDisabled(detail.kind.unwrap_or(CloudUploadKind::Unknown))
1024 }
1025 CloudErrorCode::NotFound => Self::NotFound,
1026 CloudErrorCode::FeatureDisabled => Self::FeatureDisabled {
1027 feature: wire_token(detail.feature.as_deref(), 64),
1028 },
1029 CloudErrorCode::RevisionConflict => Self::Conflict {
1030 expected: detail.expected,
1031 actual: detail.actual,
1032 },
1033 CloudErrorCode::ScreeningRequired => Self::ScreeningBlocked,
1034 CloudErrorCode::UpgradeRequired => Self::UpgradeRequired {
1035 min: detail.min_instance,
1036 },
1037 CloudErrorCode::RateLimited => Self::RateLimited {
1038 retry_after: detail.retry_after_s,
1039 },
1040 CloudErrorCode::ExpiredToken => Self::DeviceFlow(CODE_EXPIRED.into()),
1041 CloudErrorCode::AccessDenied => Self::DeviceFlow(CODE_DENIED.into()),
1042 _ if status == 429 => Self::RateLimited {
1045 retry_after: detail.retry_after_s,
1046 },
1047 CloudErrorCode::Unknown => Self::of_status(status, detail.retry_after_s),
1048 other => Self::Server {
1049 status,
1050 code: serde_json::to_value(other)
1051 .ok()
1052 .and_then(|v| v.as_str().map(str::to_string))
1053 .unwrap_or_else(|| "unknown".into()),
1054 },
1055 }
1056 }
1057
1058 #[must_use]
1064 pub fn with_origin(mut self, origin: &str) -> Self {
1065 if let Self::PlanRequired(need) = &mut self
1066 && let Some(url) = need.plans_url.take()
1067 {
1068 let base = origin.trim_end_matches('/');
1069 need.plans_url = if !(base.starts_with("https://") || base.starts_with("http://")) {
1070 None
1071 } else if url.starts_with('/') {
1072 Some(format!("{base}{url}"))
1073 } else if same_origin(&url, base) {
1074 Some(url)
1075 } else {
1076 None
1077 };
1078 }
1079 self
1080 }
1081
1082 #[must_use]
1086 pub fn for_trial(self) -> Self {
1087 match self {
1088 Self::DeviceFlow(why) if why == CODE_EXPIRED => {
1089 Self::DeviceFlow(TRIAL_CODE_EXPIRED.into())
1090 }
1091 other => other,
1092 }
1093 }
1094
1095 fn of_status(status: u16, retry_after: Option<u64>) -> Self {
1098 match status {
1099 429 => Self::RateLimited {
1100 retry_after: retry_after.map(|s| s.min(RETRY_AFTER_CAP_S)),
1101 },
1102 413 => Self::Server {
1103 status,
1104 code: "payload_too_large".into(),
1105 },
1106 _ => Self::Server {
1107 status,
1108 code: "unknown".into(),
1109 },
1110 }
1111 }
1112
1113 #[must_use]
1116 pub fn with_plan(mut self, plan: CloudPlan) -> Self {
1117 if let Self::PlanRequired(need) = &mut self
1118 && (need.feature.is_some() || need.locked().is_some())
1119 && plan != CloudPlan::Unknown
1120 {
1121 need.plan.get_or_insert(plan);
1122 }
1123 self
1124 }
1125
1126 pub fn is_transient(&self) -> bool {
1129 match self {
1130 Self::QuotaExceeded(q) => q.waits(),
1131 other => matches!(
1132 other,
1133 Self::Offline(_)
1134 | Self::RateLimited { .. }
1135 | Self::UploadRateLimited { .. }
1136 | Self::Server {
1137 status: 408 | 500..,
1138 ..
1139 }
1140 ),
1141 }
1142 }
1143
1144 pub fn retry_after_at(&self, now: lean_ctx_time::UtcDateTime) -> Option<u64> {
1148 match self {
1149 Self::RateLimited { retry_after } | Self::UploadRateLimited { retry_after, .. } => {
1150 *retry_after
1151 }
1152 Self::QuotaExceeded(q) if q.waits() => q.retry_after.or_else(|| {
1153 let reset =
1154 lean_ctx_time::OffsetDateTime::parse_from_rfc3339(q.reset_at.as_deref()?)
1155 .ok()?;
1156 u64::try_from((reset.to_utc() - now).num_seconds().max(1)).ok()
1157 }),
1158 _ => None,
1159 }
1160 }
1161}
1162
1163impl fmt::Display for CloudError {
1164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1165 match self {
1166 Self::Offline(why) => write!(f, "The Cloud is not reachable ({why})"),
1167 Self::NotConnected => f.write_str("not connected to the Cloud (run `lean-ctx cloud connect`)"),
1168 Self::Unauthorized => f.write_str(
1169 "The Cloud does not accept this instance any more (run `lean-ctx cloud connect` again)",
1170 ),
1171 Self::PlanRequired(need) => {
1172 write_plan_need(f, need)?;
1173 if need.locked().is_none() && !need.trial_used() {
1175 write_hint(f, need.next_step)?;
1176 }
1177 Ok(())
1178 }
1179 Self::InstanceLimit(cap) => write_instance_cap(f, cap),
1180 Self::QuotaExceeded(q) => write_quota(f, q),
1181 Self::StorageFull(s) => {
1182 f.write_str("this workspace's Cloud storage is full")?;
1183 if let (Some(used), Some(limit)) = (s.used, s.limit) {
1184 write!(f, " ({} of {})", bytes_text(used), bytes_text(limit))?;
1185 }
1186 f.write_str(
1187 "; nothing is charged for more; uploads stop until storage frees (remove vaults or files in the Cloud)",
1188 )?;
1189 write_hint(f, s.next_step)
1190 }
1191 Self::UploadRateLimited {
1192 retry_after,
1193 per_hour,
1194 } => {
1195 f.write_str("The Cloud's upload allowance for this hour is used up")?;
1196 if let Some(per_hour) = per_hour {
1197 write!(f, " ({} per hour)", bytes_text(*per_hour))?;
1198 }
1199 match retry_after {
1200 Some(s) => write!(f, "; the rest goes out in {s} s")?,
1201 None => f.write_str("; the rest goes out later")?,
1202 }
1203 f.write_str(" (a large first sync can take a few hours)")
1204 }
1205 Self::PolicyDenied(d) => {
1206 f.write_str("Cloud policy refuses this")?;
1207 if let Some(member) = &d.member {
1208 write!(f, " ({member}")?;
1209 if let Some(level) = &d.level {
1210 write!(f, ", set at the {level} level")?;
1211 }
1212 f.write_str(")")?;
1213 }
1214 match &d.action {
1215 Some(action) => write!(
1216 f,
1217 "; a person does this on the Cloud website ({})",
1218 action.replace('_', " ")
1219 ),
1220 None => f.write_str(
1221 "; it is not retried until an admin changes the policy in the Cloud",
1222 ),
1223 }
1224 }
1225 Self::LeaseLapsed => {
1226 f.write_str("the Cloud lease has lapsed (run `lean-ctx cloud connect` again)")
1227 }
1228 Self::Revoked(r) => {
1229 f.write_str("this instance was revoked by ")?;
1230 match &r.workspace {
1231 Some(workspace) => f.write_str(workspace)?,
1232 None => f.write_str("its workspace")?,
1233 }
1234 if let Some(reason) = &r.reason {
1235 write!(f, " ({})", reason.replace('_', " "))?;
1236 }
1237 f.write_str("; reconnect with `lean-ctx cloud connect` after an admin allows it")
1238 }
1239 Self::Forbidden => f.write_str("The Cloud does not allow this for your account"),
1240 Self::Vetoed => f.write_str("a workspace veto bars it until the veto is lifted"),
1241 Self::UploadDisabled(kind) => match kind {
1242 CloudUploadKind::Metrics => {
1243 f.write_str("the workspace has switched metrics upload off")
1244 }
1245 CloudUploadKind::Receipts => {
1246 f.write_str("the workspace has switched receipts upload off")
1247 }
1248 CloudUploadKind::Unknown => {
1249 f.write_str("the workspace has switched this upload off")
1250 }
1251 },
1252 Self::NotFound => f.write_str("The Cloud does not know that item"),
1253 Self::FeatureDisabled { feature } => match feature.as_deref() {
1254 Some("instance_metrics") | None => f.write_str(
1255 "this Cloud server has switched off instance metrics; nothing was sent",
1256 ),
1257 Some(other) => write!(
1258 f,
1259 "this Cloud server has switched off {}; nothing was sent",
1260 other.replace('_', " ")
1261 ),
1262 },
1263 Self::Conflict { expected, actual } => match (expected, actual) {
1264 (Some(e), Some(a)) => {
1265 write!(f, "knowledge moved on (expected revision {e}, now {a})")
1266 }
1267 _ => f.write_str("knowledge moved on"),
1268 },
1269 Self::ScreeningBlocked => f.write_str("Cloud screening refused the content"),
1270 Self::UpgradeRequired { min } => match min {
1271 Some(min) => write!(f, "The Cloud needs lean-ctx {min} or newer (run `lean-ctx update`)"),
1272 None => f.write_str("The Cloud needs a newer lean-ctx (run `lean-ctx update`)"),
1273 },
1274 Self::RateLimited { retry_after } => match retry_after {
1275 Some(s) => write!(f, "The Cloud asks to try again in {s} s"),
1276 None => f.write_str("The Cloud asks to try again later"),
1277 },
1278 Self::DeviceFlow(why) => write!(f, "connection not approved: {why}"),
1279 Self::TrialUnsupported { origin } => write!(
1280 f,
1281 "LeanCTX does not offer the one-step trial here yet. Start the trial on {origin}, or sign in with `lean-ctx cloud connect`"
1282 ),
1283 Self::Protocol(why) => write!(f, "unexpected answer from Cloud: {why}"),
1284 Self::Config(why) => write!(f, "Cloud configuration: {why}"),
1285 Self::Local(why) => write!(f, "local Cloud state: {why}"),
1286 Self::Refused(why) => f.write_str(why),
1287 Self::Task {
1288 refusal,
1289 number,
1290 detail,
1291 } => {
1292 if let Some(number) = number {
1293 write!(f, "task #{number}: ")?;
1294 }
1295 match detail {
1296 Some(detail) if matches!(refusal, TaskRefusal::NotPermitted(_)) => {
1298 f.write_str(detail)
1299 }
1300 Some(detail) => write!(f, "{refusal} ({detail})"),
1301 None => write!(f, "{refusal}"),
1302 }
1303 }
1304 Self::Server { status, code } => write!(f, "The Cloud answered {status} ({code})"),
1305 }
1306 }
1307}
1308
1309impl std::error::Error for CloudError {}
1310
1311pub const CODE_EXPIRED: &str =
1313 "the code expired before it was approved; run `lean-ctx cloud connect` again for a new one";
1314
1315pub const TRIAL_CODE_EXPIRED: &str = "the code expired before it was approved. If the browser said this address already had its trial, choose a plan in the Cloud, then run `lean-ctx cloud connect`; otherwise run `lean-ctx cloud connect --trial` again for a new code";
1317
1318pub const CODE_DENIED: &str =
1320 "you chose \"Not mine\" in the browser; nothing changed on this machine";
1321
1322impl CloudError {
1323 #[must_use]
1329 pub fn event_code(&self) -> String {
1330 match self {
1331 Self::PlanRequired(need) if need.trial_used() => TRIAL_USED.into(),
1332 Self::PlanRequired(_) => "plan_required".into(),
1333 Self::TrialUnsupported { .. } => "trial_unsupported".into(),
1334 Self::DeviceFlow(why) if why == CODE_EXPIRED || why == TRIAL_CODE_EXPIRED => {
1335 "expired".into()
1336 }
1337 Self::DeviceFlow(why) if why == CODE_DENIED => "denied".into(),
1338 Self::DeviceFlow(why) if why == crate::auth::TASK_KEY_REFUSED => {
1340 TASK_KEY_INVALID.into()
1341 }
1342 Self::DeviceFlow(why) if why == crate::auth::TASK_KEY_ALREADY_BOUND => {
1343 TASK_KEY_BOUND.into()
1344 }
1345 Self::DeviceFlow(why) if why == crate::auth::TASK_KEY_WAS_REMOVED => {
1346 TASK_KEY_CLEARED.into()
1347 }
1348 Self::DeviceFlow(why) if why == crate::auth::OPTIN_KEY_REFUSED => {
1350 OPTIN_KEY_INVALID.into()
1351 }
1352 Self::DeviceFlow(why) if why == crate::auth::OPTIN_KEY_ALREADY_BOUND => {
1353 OPTIN_KEY_BOUND.into()
1354 }
1355 Self::DeviceFlow(why) if why == crate::auth::OPTIN_KEY_WAS_REMOVED => {
1356 OPTIN_KEY_CLEARED.into()
1357 }
1358 Self::DeviceFlow(why) if why == crate::auth::OPTIN_KEY_TOKEN_ENROLLMENT => {
1359 "token_enrollment".into()
1360 }
1361 Self::DeviceFlow(why) if why == crate::auth::APP_KEY_PAIRING_FAILED => {
1364 APP_KEY_NOT_ANNOUNCED.into()
1365 }
1366 Self::DeviceFlow(_) => "not_approved".into(),
1367 Self::InstanceLimit(_) => "instance_limit".into(),
1368 Self::QuotaExceeded(_) => "quota_exceeded".into(),
1369 Self::Offline(_) => "offline".into(),
1370 Self::Unauthorized => "unauthorized".into(),
1371 Self::Revoked(_) => "instance_revoked".into(),
1372 Self::RateLimited { .. } => "rate_limited".into(),
1373 Self::UpgradeRequired { .. } => "upgrade_required".into(),
1374 Self::Config(_) => "config".into(),
1375 Self::Protocol(_) => "protocol".into(),
1376 Self::Local(_) => "local".into(),
1377 Self::Server { code, .. } if wire_token(Some(code), 64).is_some() => code.clone(),
1378 _ => "error".into(),
1379 }
1380 }
1381}
1382
1383pub const RECOVER_HINT: &str = "for a lost or broken device, recover its slot now on the Cloud website (Hosts › Recover the slot now, with your second factor; once per 30 days)";
1387
1388fn host_cap_head(resource: &str) -> Option<&'static str> {
1390 match resource {
1391 "registered_instances" => Some("all hosts the plan includes are registered"),
1392 "connected_instances" => Some("all hosts that may be connected at once are connected"),
1393 _ => None,
1394 }
1395}
1396
1397fn write_instance_cap(f: &mut fmt::Formatter<'_>, cap: &InstanceCap) -> fmt::Result {
1400 let connected = cap.resource.as_deref() == Some("connected_instances");
1401 let resource = if connected {
1402 "connected_instances"
1403 } else {
1404 "registered_instances"
1405 };
1406 f.write_str(host_cap_head(resource).unwrap_or_default())?;
1407 if let (Some(used), Some(limit)) = (cap.used, cap.limit) {
1408 write!(f, " ({used} of {limit}")?;
1409 if let (Some(seats), Some(per_seat)) = (cap.seats, cap.per_seat) {
1410 write!(f, ": {seats} seats, {per_seat} per seat")?;
1411 }
1412 f.write_str(")")?;
1413 }
1414 if connected {
1415 write!(f, "; {FREE_CONNECTED}, or upgrade the plan")?;
1416 } else {
1417 write!(f, "; {FREE_REGISTERED}, or upgrade the plan")?;
1418 }
1419 write_hint(f, cap.next_step)
1420}
1421
1422#[must_use]
1424pub fn quota_label(resource: &str) -> &str {
1425 match resource {
1426 "transfer_bytes" => "monthly transfer",
1427 "bus_messages" => "monthly bus messages",
1428 "registered_instances" => HOSTS_REGISTERED,
1429 "private_vaults" => "private vaults",
1430 "connected_instances" => HOSTS_CONNECTED,
1431 "storage_bytes" => "storage",
1432 "model_credit_usd_micros" => "model credit",
1433 other => other,
1434 }
1435}
1436
1437fn write_quota(f: &mut fmt::Formatter<'_>, q: &Quota) -> fmt::Result {
1438 let what = quota_label(&q.resource);
1439 if let Some(head) = host_cap_head(&q.resource) {
1440 f.write_str(head)?;
1441 if let (Some(used), Some(limit)) = (q.used, q.limit) {
1442 write!(f, " ({used} of {limit})")?;
1443 }
1444 } else {
1445 write!(f, "this workspace has used all its {what}")?;
1446 if let (Some(used), Some(limit)) = (q.used, q.limit) {
1447 write!(
1448 f,
1449 " ({} of {})",
1450 amount_text(&q.resource, used),
1451 amount_text(&q.resource, limit)
1452 )?;
1453 }
1454 }
1455 f.write_str("; nothing is charged for more")?;
1456 match q.resource.as_str() {
1457 "registered_instances" if q.cooling_slot() => write!(
1458 f,
1459 "; a revoked host stays registered until {} ({}-day cool-down), or {RECOVER_HINT}",
1460 q.reset_at.as_deref().unwrap_or("?"),
1461 q.cooldown_days.unwrap_or(0)
1462 )?,
1463 "registered_instances" => write!(f, "; {FREE_REGISTERED}, or upgrade the plan")?,
1464 "connected_instances" => write!(f, "; {FREE_CONNECTED}")?,
1465 "private_vaults" => {
1466 f.write_str("; remove or publish a vault in the Cloud, or upgrade the plan")?;
1467 }
1468 "model_credit_usd_micros" => {}
1470 _ if q.waits() => match &q.reset_at {
1471 Some(at) => write!(f, "; uploads wait in the local outbox until {at}")?,
1472 None => f.write_str("; uploads wait in the local outbox until it frees")?,
1473 },
1474 _ => {}
1475 }
1476 write_hint(f, q.next_step)
1477}
1478
1479#[cfg(test)]
1480mod tests {
1481 use super::*;
1482 use serde_json::json;
1483
1484 #[test]
1487 fn trial_used_refusal_names_the_used_trial_and_the_plans_page() {
1488 let body = json!({"error": {
1489 "code": "trial_used",
1490 "message": "This address already had a trial.",
1491 "plan_needed": "team",
1492 "next_step": "subscribe",
1493 "plans_url": "https://cloud.leanctx.com/app/plans"
1494 }});
1495 let error = CloudError::from_response(402, &body);
1496 let CloudError::PlanRequired(need) = &error else {
1497 panic!("{error:?}");
1498 };
1499 assert!(need.trial_used());
1500 assert_eq!(need.plan_needed.as_deref(), Some("team"));
1501 assert_eq!(
1502 need.plans_url.as_deref(),
1503 Some("https://cloud.leanctx.com/app/plans")
1504 );
1505 assert_eq!(error.event_code(), "trial_used");
1506 assert!(!error.is_transient());
1507 assert_eq!(
1508 error.to_string(),
1509 "this address already had its Team trial; no second trial starts. Choose a plan at https://cloud.leanctx.com/app/plans, then run `lean-ctx cloud connect`"
1510 );
1511 let ended = CloudError::from_response(
1513 402,
1514 &json!({"error": {"code": "trial_used", "reason": "trial_ended", "message": "",
1515 "plan_needed": "personal", "plans_url": "https://cloud.leanctx.com/app/plans"}}),
1516 );
1517 assert_eq!(ended.event_code(), "trial_used");
1518 assert_eq!(
1519 ended.to_string(),
1520 "the Personal trial of this address has ended; no second trial starts. Choose a plan at https://cloud.leanctx.com/app/plans, then run `lean-ctx cloud connect`"
1521 );
1522 let no_plan = CloudError::from_response(
1523 402,
1524 &json!({"error": {"code": "trial_used", "reason": "no_plan", "message": "",
1525 "plan_needed": "team"}}),
1526 );
1527 assert_eq!(no_plan.event_code(), "trial_used");
1528 assert!(no_plan.to_string().starts_with(
1529 "this address has no Team trial left and no plan; no second trial starts."
1530 ));
1531 let path = format!(
1534 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud/error.trial_used.json",
1535 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
1536 );
1537 let fixture: serde_json::Value =
1538 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
1539 let refused = CloudError::from_response(402, &fixture);
1540 assert_eq!(refused.event_code(), "trial_used");
1541 assert_eq!(
1542 refused.to_string(),
1543 "this address already had its Personal trial; no second trial starts. Choose a plan in the Cloud, then run `lean-ctx cloud connect`"
1544 );
1545 assert_eq!(
1546 refused
1547 .with_origin("https://cloud.leanctx.com/")
1548 .to_string(),
1549 "this address already had its Personal trial; no second trial starts. Choose a plan at https://cloud.leanctx.com/o/bob/billing/?plan=personal, then run `lean-ctx cloud connect`"
1550 );
1551 let hostile = CloudError::from_response(
1553 402,
1554 &json!({"error": {"code": "trial_used", "message": "", "plan_needed": "personal",
1555 "plans_url": "javascript:alert(1)"}}),
1556 );
1557 assert_eq!(
1558 hostile.to_string(),
1559 "this address already had its Personal trial; no second trial starts. Choose a plan in the Cloud, then run `lean-ctx cloud connect`"
1560 );
1561 let plain = CloudError::from_response(
1563 402,
1564 &json!({"error": {"code": "plan_required", "message": "", "feature": "audit_export", "plan_needed": "team"}}),
1565 );
1566 assert_eq!(plain.event_code(), "plan_required");
1567 }
1568
1569 fn trial_used_with(plans_url: &str) -> CloudError {
1570 CloudError::from_response(
1571 402,
1572 &json!({"error": {"code": "trial_used", "message": "", "plan_needed": "personal",
1573 "plans_url": plans_url}}),
1574 )
1575 }
1576
1577 const NO_PAGE: &str = "this address already had its Personal trial; no second trial starts. Choose a plan in the Cloud, then run `lean-ctx cloud connect`";
1578
1579 #[test]
1582 fn trial_plans_url_on_another_origin_is_not_shown() {
1583 let origin = "https://cloud.leanctx.com";
1584 assert_eq!(
1585 trial_used_with("https://Cloud.LeanCTX.com/app/plans?plan=personal")
1586 .with_origin(origin)
1587 .to_string(),
1588 "this address already had its Personal trial; no second trial starts. Choose a plan at https://Cloud.LeanCTX.com/app/plans?plan=personal, then run `lean-ctx cloud connect`"
1589 );
1590 for foreign in [
1591 "http://cloud.leanctx.com/app/plans",
1592 "https://evil.example/app/plans",
1593 "https://cloud.leanctx.com.evil.example/app/plans",
1594 "https://cloud.leanctx.com@evil.example/app/plans",
1595 "https://cloud.leanctx.com:8443/app/plans",
1596 "https://cloud.leanctx.com",
1597 ] {
1598 let shown = trial_used_with(foreign).with_origin(origin).to_string();
1599 let expected = if foreign == "https://cloud.leanctx.com" {
1600 "this address already had its Personal trial; no second trial starts. Choose a plan at https://cloud.leanctx.com, then run `lean-ctx cloud connect`"
1601 } else {
1602 NO_PAGE
1603 };
1604 assert_eq!(shown, expected, "{foreign}");
1605 }
1606 assert_eq!(
1608 trial_used_with("https://cloud.leanctx.com/app/plans")
1609 .with_origin("file:///tmp")
1610 .to_string(),
1611 NO_PAGE
1612 );
1613 }
1614
1615 #[test]
1618 fn trial_plans_url_with_format_characters_is_not_shown() {
1619 for c in [
1620 '\u{202E}',
1621 '\u{202A}',
1622 '\u{2066}',
1623 '\u{2069}',
1624 '\u{200B}',
1625 '\u{200D}',
1626 '\u{200E}',
1627 '\u{061C}',
1628 '\u{00AD}',
1629 '\u{FEFF}',
1630 '\u{E0041}',
1631 '\u{3164}',
1632 ] {
1633 let url = format!("/o/bob/billing/{c}?plan=personal");
1634 assert_eq!(
1635 trial_used_with(&url)
1636 .with_origin("https://cloud.leanctx.com")
1637 .to_string(),
1638 NO_PAGE,
1639 "U+{:04X}",
1640 c as u32
1641 );
1642 }
1643 assert_eq!(
1644 trial_used_with("/o/bob/billing/?plan=personal")
1645 .with_origin("https://cloud.leanctx.com")
1646 .to_string(),
1647 "this address already had its Personal trial; no second trial starts. Choose a plan at https://cloud.leanctx.com/o/bob/billing/?plan=personal, then run `lean-ctx cloud connect`"
1648 );
1649 }
1650
1651 #[test]
1655 fn trial_code_expiry_points_to_the_plans_page() {
1656 let expired = CloudError::DeviceFlow(CODE_EXPIRED.into()).for_trial();
1657 assert_eq!(expired, CloudError::DeviceFlow(TRIAL_CODE_EXPIRED.into()));
1658 assert_eq!(expired.event_code(), "expired");
1659 assert!(expired.to_string().contains("choose a plan in the Cloud"));
1660 assert!(
1661 !expired
1662 .to_string()
1663 .contains("run `lean-ctx cloud connect` again")
1664 );
1665 let denied = CloudError::DeviceFlow(CODE_DENIED.into());
1666 assert_eq!(denied.clone().for_trial(), denied);
1667 assert_eq!(
1668 CloudError::Offline("reset".into()).for_trial(),
1669 CloudError::Offline("reset".into())
1670 );
1671 }
1672
1673 #[test]
1674 fn trial_event_codes_name_the_device_flow_outcomes() {
1675 assert_eq!(
1676 CloudError::DeviceFlow(CODE_EXPIRED.into()).event_code(),
1677 "expired"
1678 );
1679 assert_eq!(
1680 CloudError::from_response(
1681 400,
1682 &json!({"error": {"code": "access_denied", "message": ""}})
1683 )
1684 .event_code(),
1685 "denied"
1686 );
1687 assert_eq!(
1688 CloudError::Server {
1689 status: 400,
1690 code: "invalid_request".into()
1691 }
1692 .event_code(),
1693 "invalid_request"
1694 );
1695 assert_eq!(
1696 CloudError::Server {
1697 status: 500,
1698 code: "Bad Code\n".into()
1699 }
1700 .event_code(),
1701 "error"
1702 );
1703 assert_eq!(CloudError::Offline("reset".into()).event_code(), "offline");
1704 assert_eq!(
1706 CloudError::DeviceFlow(crate::auth::APP_KEY_PAIRING_FAILED.into()).event_code(),
1707 APP_KEY_NOT_ANNOUNCED
1708 );
1709 assert_eq!(APP_KEY_NOT_ANNOUNCED, "app_key_not_announced");
1710 for reason in [APP_KEY_NOT_ANNOUNCED, APP_KEY_BIND_INVALID] {
1712 let body = serde_json::json!({"error": {"code": "invalid_field",
1713 "field": "app_keys_bind_signature", "reason": reason, "message": "x"}});
1714 assert!(matches!(
1715 CloudError::from_response(400, &body),
1716 CloudError::Server { status: 400, code } if code == reason
1717 ));
1718 }
1719 }
1720
1721 #[test]
1724 fn invalid_field_keeps_its_code() {
1725 assert_eq!(
1726 CloudError::from_response(
1727 400,
1728 &json!({"error": {"code": "invalid_field", "message": "x",
1729 "field": "chat_key.bind_signature"}}),
1730 ),
1731 CloudError::Server {
1732 status: 400,
1733 code: "invalid_field".into()
1734 }
1735 );
1736 }
1737
1738 #[test]
1741 fn a_detail_with_a_mistyped_member_keeps_its_code_and_retry() {
1742 let limited = CloudError::from_response(
1743 429,
1744 &json!({"error": {"code": "rate_limited", "message": "slow down",
1745 "retry_after_s": 12, "number": "seventeen"}}),
1746 );
1747 assert_eq!(
1748 limited,
1749 CloudError::RateLimited {
1750 retry_after: Some(12)
1751 }
1752 );
1753 let claimed = CloudError::from_response(
1755 409,
1756 &json!({"error": {"code": "invalid_state", "message": "x",
1757 "reason": "task_claimed", "number": "17", "limit": {"odd": true}}}),
1758 );
1759 assert!(
1760 matches!(
1761 claimed,
1762 CloudError::Task {
1763 refusal: TaskRefusal::Claimed,
1764 number: Some(17),
1765 ..
1766 }
1767 ),
1768 "{claimed:?}"
1769 );
1770 let quota = CloudError::from_response(
1771 429,
1772 &json!({"error": {"code": "quota_exceeded", "message": "x",
1773 "resource": "bus_messages", "retry_after_s": "60", "used": -1}}),
1774 );
1775 let CloudError::QuotaExceeded(quota) = quota else {
1776 panic!("{quota:?}");
1777 };
1778 assert_eq!(
1779 (quota.resource.as_str(), quota.retry_after, quota.used),
1780 ("bus_messages", Some(60), None)
1781 );
1782 assert_eq!(
1784 CloudError::from_response(400, &json!({"error": {"code": 7}})),
1785 CloudError::Server {
1786 status: 400,
1787 code: "unknown".into()
1788 }
1789 );
1790 }
1791
1792 #[test]
1795 fn edge_answers_are_classified_by_status() {
1796 let busy = CloudError::from_response(
1797 429,
1798 &json!({"error": {"code": "server_busy", "message": "x", "retry_after_s": 5}}),
1799 );
1800 assert_eq!(
1801 busy,
1802 CloudError::RateLimited {
1803 retry_after: Some(5)
1804 }
1805 );
1806 let header_only = CloudError::from_response(429, &json!({"error": {"retry_after_s": 9}}));
1808 assert_eq!(
1809 header_only,
1810 CloudError::RateLimited {
1811 retry_after: Some(9)
1812 }
1813 );
1814 assert_eq!(
1815 CloudError::from_response(429, &serde_json::Value::Null),
1816 CloudError::RateLimited { retry_after: None }
1817 );
1818 for status in [408, 500, 502, 503, 504] {
1820 let down = CloudError::from_response(status, &serde_json::Value::Null);
1821 assert!(down.is_transient(), "{status}: {down:?}");
1822 }
1823 let too_large = CloudError::from_response(413, &serde_json::Value::Null);
1824 assert_eq!(
1825 too_large,
1826 CloudError::Server {
1827 status: 413,
1828 code: "payload_too_large".into()
1829 }
1830 );
1831 assert!(!too_large.is_transient());
1832 }
1833
1834 #[test]
1835 fn instance_limit_carries_the_seat_numbers() {
1836 let error = CloudError::from_response(
1837 409,
1838 &json!({"error": {"code": "instance_limit", "message": "x", "limit": 2, "used": 2}}),
1839 );
1840 assert_eq!(
1841 error,
1842 CloudError::InstanceLimit(Box::new(InstanceCap {
1843 limit: Some(2),
1844 used: Some(2),
1845 ..InstanceCap::default()
1846 }))
1847 );
1848 assert_eq!(
1849 error.to_string(),
1850 "all hosts the plan includes are registered (2 of 2); to free one, revoke a host you no longer use on the Hosts page, or upgrade the plan"
1851 );
1852 }
1853
1854 #[test]
1857 fn a_connected_limit_says_disconnect_and_names_the_seats() {
1858 let error = CloudError::from_response(
1859 409,
1860 &json!({"error": {"code": "instance_limit", "message": "x", "resource": "connected_instances",
1861 "limit": 4, "used": 4, "plan": "team", "next_step": "add_seats",
1862 "seats": 2, "per_seat": 2}}),
1863 );
1864 assert_eq!(
1865 error,
1866 CloudError::InstanceLimit(Box::new(InstanceCap {
1867 resource: Some("connected_instances".into()),
1868 limit: Some(4),
1869 used: Some(4),
1870 seats: Some(2),
1871 per_seat: Some(2),
1872 next_step: Some(NextStep::AddSeats),
1873 }))
1874 );
1875 assert_eq!(
1876 error.to_string(),
1877 "all hosts that may be connected at once are connected (4 of 4: 2 seats, 2 per seat); to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine), or upgrade the plan; every seat you add in the Cloud brings its own allowance"
1878 );
1879 assert!(!error.is_transient());
1880 let personal = CloudError::from_response(
1881 409,
1882 &json!({"error": {"code": "instance_limit", "message": "x", "resource": "connected_instances",
1883 "limit": 2, "used": 2, "plan": "personal", "next_step": "upgrade_team"}}),
1884 );
1885 assert!(
1886 personal
1887 .to_string()
1888 .ends_with("; Team gives every seat its own allowance"),
1889 "{personal}"
1890 );
1891 }
1892
1893 #[test]
1894 fn storage_full_decodes_with_bytes_and_is_not_retried() {
1895 let error = CloudError::from_response(
1896 403,
1897 &json!({"error": {"code": "storage_quota_exceeded", "message": "x", "resource": "storage_bytes",
1898 "limit": 1_073_741_824_u64, "used": 1_073_741_824_u64,
1899 "limit_bytes": 1_073_741_824_u64, "used_bytes": 1_073_741_824_u64,
1900 "plan": "personal", "next_step": "upgrade_team"}}),
1901 );
1902 assert_eq!(
1903 error,
1904 CloudError::StorageFull(Box::new(StorageFull {
1905 limit: Some(1 << 30),
1906 used: Some(1 << 30),
1907 next_step: Some(NextStep::UpgradeTeam),
1908 }))
1909 );
1910 assert!(!error.is_transient(), "waiting does not free storage");
1911 assert_eq!(
1912 error.retry_after_at(lean_ctx_time::UtcDateTime::now()),
1913 None
1914 );
1915 assert_eq!(
1916 error.to_string(),
1917 "this workspace's Cloud storage is full (1 GiB of 1 GiB); nothing is charged for more; uploads stop until storage frees (remove vaults or files in the Cloud); Team gives every seat its own allowance"
1918 );
1919 assert!(!error.to_string().contains("unknown"));
1920 let bare = CloudError::from_response(
1923 403,
1924 &json!({"error": {"code": "storage_quota_exceeded", "message": "x", "limit": 1536, "used": 2048,
1925 "next_step": "something_new"}}),
1926 );
1927 assert_eq!(
1928 bare,
1929 CloudError::StorageFull(Box::new(StorageFull {
1930 limit: Some(1536),
1931 used: Some(2048),
1932 next_step: None,
1933 }))
1934 );
1935 assert!(bare.to_string().contains("(2 KiB of 1.5 KiB)"), "{bare}");
1936 }
1937
1938 #[test]
1939 fn upload_rate_limited_is_transient_and_honours_retry_after() {
1940 let error = CloudError::from_response(
1941 429,
1942 &json!({"error": {"code": "upload_rate_limited", "message": "x",
1943 "limit_bytes_per_hour": 268_435_456_u64, "plan": "personal",
1944 "next_step": "wait", "retry_after_s": 1200}}),
1945 );
1946 assert_eq!(
1947 error,
1948 CloudError::UploadRateLimited {
1949 retry_after: Some(1200),
1950 per_hour: Some(256 << 20),
1951 }
1952 );
1953 assert!(error.is_transient());
1954 assert_eq!(
1955 error.retry_after_at(lean_ctx_time::UtcDateTime::now()),
1956 Some(1200)
1957 );
1958 assert_eq!(
1959 error.to_string(),
1960 "The Cloud's upload allowance for this hour is used up (256 MiB per hour); the rest goes out in 1200 s (a large first sync can take a few hours)"
1961 );
1962 let huge = CloudError::from_response(
1964 429,
1965 &json!({"error": {"code": "upload_rate_limited", "message": "x", "retry_after_s": u64::MAX}}),
1966 );
1967 assert_eq!(
1968 huge.retry_after_at(lean_ctx_time::UtcDateTime::now()),
1969 Some(RETRY_AFTER_CAP_S)
1970 );
1971 }
1972
1973 #[test]
1974 fn quota_hints_and_new_resource_labels() {
1975 let quota = |resource: &str, limit: u64, next: &str| {
1976 CloudError::from_response(
1977 409,
1978 &json!({"error": {"code": "quota_exceeded", "message": "x", "resource": resource,
1979 "limit": limit, "used": limit, "plan": "personal", "next_step": next}}),
1980 )
1981 .to_string()
1982 };
1983 assert_eq!(
1984 quota("storage_bytes", 1 << 30, "upgrade_team"),
1985 "this workspace has used all its storage (1 GiB of 1 GiB); nothing is charged for more; Team gives every seat its own allowance"
1986 );
1987 assert_eq!(
1988 quota("model_credit_usd_micros", 8_000_000, "top_up"),
1989 "this workspace has used all its model credit ($8.00 of $8.00); nothing is charged for more; a top-up in the Cloud adds more"
1990 );
1991 assert!(
1992 quota("registered_instances", 3, "contact")
1993 .ends_with("; contact us to extend your Enterprise contract")
1994 );
1995 assert_eq!(
1997 quota("registered_instances", 3, "upgrade_team"),
1998 "all hosts the plan includes are registered (3 of 3); nothing is charged for more; \
1999 to free one, revoke a host you no longer use on the Hosts page, or upgrade the plan; \
2000 Team gives every seat its own allowance"
2001 );
2002 assert_eq!(
2003 quota("connected_instances", 2, "wait"),
2004 "all hosts that may be connected at once are connected (2 of 2); \
2005 nothing is charged for more; to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine)"
2006 );
2007 for resource in ["registered_instances", "connected_instances"] {
2010 let line = quota(resource, 2, "upgrade_team");
2011 for word in ["instance", "slot", "workspace"] {
2012 assert!(!line.contains(word), "{word} in {line}");
2013 }
2014 }
2015 let monthly = CloudError::from_response(
2017 429,
2018 &json!({"error": {"code": "quota_exceeded", "message": "x", "resource": "bus_messages",
2019 "limit": 200_000, "used": 200_000, "next_step": "wait",
2020 "reset_at": "2026-12-01T00:00:00Z", "retry_after_s": 60}}),
2021 );
2022 assert_eq!(
2023 monthly.to_string(),
2024 "this workspace has used all its monthly bus messages (200000 of 200000); nothing is charged for more; uploads wait in the local outbox until 2026-12-01T00:00:00Z"
2025 );
2026 let feature = CloudError::from_response(
2028 402,
2029 &json!({"error": {"code": "plan_required", "message": "", "feature": "audit_export",
2030 "plan_needed": "team", "next_step": "upgrade_team"}}),
2031 );
2032 assert_eq!(
2033 feature.to_string(),
2034 "audit export is included in Team and Enterprise; Team gives every seat its own allowance"
2035 );
2036 let locked = CloudError::from_response(
2037 402,
2038 &json!({"error": {"code": "plan_required", "message": "x", "feature": "read_only",
2039 "reason": "trial_ended", "plan": "locked", "next_step": "subscribe",
2040 "plan_needed": "personal"}}),
2041 );
2042 assert_eq!(
2043 locked.to_string(),
2044 "Your Personal trial has ended: this workspace is locked (read and export only). Choose a plan in the Cloud to sync again."
2045 );
2046 }
2047
2048 #[test]
2049 fn bytes_are_worded_in_binary_units() {
2050 assert_eq!(bytes_text(0), "0 B");
2051 assert_eq!(bytes_text(1023), "1023 B");
2052 assert_eq!(bytes_text(256 << 20), "256 MiB");
2053 assert_eq!(bytes_text(40 << 30), "40 GiB");
2054 assert_eq!(bytes_text(3 << 29), "1.5 GiB");
2055 assert_eq!(bytes_text(u64::MAX), "16777215.9 TiB");
2056 }
2057
2058 #[test]
2059 fn a_huge_retry_after_is_capped_on_the_way_in() {
2060 for huge in [u64::MAX, i64::MAX.unsigned_abs(), RETRY_AFTER_CAP_S + 1] {
2061 let error = CloudError::from_response(
2062 429,
2063 &json!({"error": {"code": "rate_limited", "message": "x", "retry_after_s": huge}}),
2064 );
2065 assert_eq!(
2066 error,
2067 CloudError::RateLimited {
2068 retry_after: Some(RETRY_AFTER_CAP_S)
2069 }
2070 );
2071 }
2072 let small = CloudError::from_response(
2073 429,
2074 &json!({"error": {"code": "rate_limited", "message": "x", "retry_after_s": 90}}),
2075 );
2076 assert_eq!(
2077 small,
2078 CloudError::RateLimited {
2079 retry_after: Some(90)
2080 }
2081 );
2082 }
2083
2084 #[test]
2085 fn upload_disabled_names_the_kind_and_is_not_retried() {
2086 let error = CloudError::from_response(
2087 403,
2088 &json!({"error": {"code": "upload_disabled", "message": "x", "kind": "metrics"}}),
2089 );
2090 assert_eq!(error, CloudError::UploadDisabled(CloudUploadKind::Metrics));
2091 assert!(!error.is_transient());
2092 assert!(error.to_string().contains("metrics upload off"));
2093 }
2094
2095 #[test]
2096 fn task_reasons_become_task_refusals_and_others_stay() {
2097 let refusal = |status, code: &str, reason: &str| {
2098 CloudError::from_response(
2099 status,
2100 &json!({"error": {"code": code, "message": "x", "reason": reason, "number": 7, "retry_after_s": 60}}),
2101 )
2102 };
2103 assert_eq!(
2104 refusal(409, "invalid_state", "stale_claim"),
2105 CloudError::Task {
2106 refusal: TaskRefusal::StaleClaim,
2107 number: Some(7),
2108 detail: None
2109 }
2110 );
2111 assert_eq!(
2112 refusal(403, "forbidden_right", "optin_scope"),
2113 CloudError::Task {
2114 refusal: TaskRefusal::OptinScope,
2115 number: Some(7),
2116 detail: None
2117 }
2118 );
2119 let permit_said = |check: &str, agent_role: Option<&str>, message: &str| {
2121 let mut e = json!({"error": {"code": "forbidden_right", "message": message,
2122 "reason": "not_permitted", "number": 7, "check": check,
2123 "role": "backend"}});
2124 if let Some(r) = agent_role {
2125 e["error"]["agent_role"] = r.into();
2126 }
2127 CloudError::from_response(403, &e).to_string()
2128 };
2129 let permit = |check: &str, agent_role: Option<&str>| permit_said(check, agent_role, "");
2130 assert_eq!(
2131 permit("presence", None),
2132 "task #7: this agent is not on the bus: its session (or the relay) must be running and announce it with the task's role (the task needs role backend) [check: presence] Run `lean-ctx cloud bus relay --for 30`: it says who this machine announced, or why an agent is missing. The Cloud keeps an agent present only while a relay stays connected (the daemon's), so claim while it runs."
2133 );
2134 assert_eq!(
2135 permit("role", Some("web")),
2136 "task #7: this agent is on the bus in another role than the task needs (the agent works as web, the task needs backend) [check: role]"
2137 );
2138 assert!(
2139 permit("role", Some("web\u{1b}[31m"))
2140 .ends_with("(the task needs role backend) [check: role]"),
2141 "a role that is not a bus identifier is not printed"
2142 );
2143 assert_eq!(
2145 permit_said(
2146 "presence",
2147 None,
2148 "Agent coder-1 is not on the bus: this task needs it present with role backend. Start its session (or the relay) and claim again."
2149 ),
2150 "task #7: Agent coder-1 is not on the bus: this task needs it present with role backend. Start its session (or the relay) and claim again. [check: presence] Run `lean-ctx cloud bus relay --for 30`: it says who this machine announced, or why an agent is missing. The Cloud keeps an agent present only while a relay stays connected (the daemon's), so claim while it runs."
2151 );
2152 assert_eq!(
2153 permit_said(
2154 "role",
2155 Some("web"),
2156 "Agent coder-1 works as role web;\u{1b}[31m this task needs role backend."
2157 ),
2158 "task #7: Agent coder-1 works as role web; [31m this task needs role backend. [check: role]",
2159 "control characters of the service's message never reach the terminal"
2160 );
2161 assert_eq!(
2163 permit_said("", None, "Agent coder-1 may not take this task."),
2164 "task #7: Agent coder-1 may not take this task."
2165 );
2166 let inactive = refusal(409, "invalid_state", "optin_inactive");
2167 assert!(matches!(inactive, CloudError::Task { refusal, .. } if refusal.ends_claim()));
2168 assert!(matches!(
2169 refusal(409, "invalid_state", "optin_changed"),
2170 CloudError::Task {
2171 refusal: TaskRefusal::OptinChanged,
2172 ..
2173 }
2174 ));
2175 let budget = refusal(429, "rate_limited", "daily_budget");
2176 assert_eq!(
2177 budget,
2178 CloudError::Task {
2179 refusal: TaskRefusal::DailyBudget {
2180 retry_after: Some(60)
2181 },
2182 number: Some(7),
2183 detail: None
2184 }
2185 );
2186 assert!(!budget.is_transient(), "a used-up budget is not retried");
2187 assert!(
2188 budget
2189 .to_string()
2190 .starts_with("task #7: today's task budget")
2191 );
2192 for (fixture, expected) in [
2194 ("error.optin_scope.json", TaskRefusal::OptinScope),
2195 ("error.optin_changed.json", TaskRefusal::OptinChanged),
2196 ("error.optin_inactive.json", TaskRefusal::OptinInactive),
2197 (
2198 "error.daily_budget.json",
2199 TaskRefusal::DailyBudget {
2200 retry_after: Some(43200),
2201 },
2202 ),
2203 ("error.task_claimed.json", TaskRefusal::Claimed),
2204 (
2205 "error.task_not_permitted.json",
2206 TaskRefusal::NotPermitted(PermitCheck::Unknown),
2207 ),
2208 (
2209 "error.task_not_permitted_role.json",
2210 TaskRefusal::NotPermitted(PermitCheck::Role),
2211 ),
2212 ] {
2213 let path = format!(
2214 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud/{fixture}",
2215 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2216 );
2217 let body: serde_json::Value =
2218 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
2219 let code: CloudErrorCode =
2220 serde_json::from_value(body["error"]["code"].clone()).unwrap();
2221 assert!(
2222 matches!(
2223 CloudError::from_response(code.http_status(), &body),
2224 CloudError::Task { refusal, .. } if refusal == expected
2225 ),
2226 "{fixture}"
2227 );
2228 }
2229 for (fixture, expected) in [
2231 (
2232 "task_verify.error.self_verify.json",
2233 TaskRefusal::SelfVerify,
2234 ),
2235 (
2236 "task_verify.error.not_submitted.json",
2237 TaskRefusal::NotSubmitted,
2238 ),
2239 ] {
2240 let path = format!(
2241 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/routes/{fixture}",
2242 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2243 );
2244 let body: serde_json::Value =
2245 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
2246 let code: CloudErrorCode =
2247 serde_json::from_value(body["error"]["code"].clone()).unwrap();
2248 assert!(
2249 matches!(
2250 CloudError::from_response(code.http_status(), &body),
2251 CloudError::Task { refusal, .. } if refusal == expected
2252 ),
2253 "{fixture}"
2254 );
2255 }
2256 assert_eq!(
2257 refusal(403, "forbidden_right", "vetoed"),
2258 CloudError::Vetoed
2259 );
2260 assert_eq!(
2261 refusal(409, "invalid_state", "code_graph_disabled"),
2262 CloudError::Server {
2263 status: 409,
2264 code: "invalid_state".into()
2265 },
2266 "a reason of another section keeps its old meaning"
2267 );
2268 }
2269
2270 fn plan_required_example(file: &str, feature: &str) -> (u16, serde_json::Value) {
2272 let path = format!(
2273 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/web/{file}",
2274 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2275 );
2276 let fixture: serde_json::Value =
2277 serde_json::from_slice(&std::fs::read(&path).expect(&path)).expect(&path);
2278 let example = fixture["errors"]
2279 .as_array()
2280 .expect("errors")
2281 .iter()
2282 .find(|e| {
2283 e["body"]["error"]["code"] == "plan_required"
2284 && e["body"]["error"]["feature"] == feature
2285 })
2286 .unwrap_or_else(|| panic!("{file}: no plan_required {feature}"));
2287 (
2288 u16::try_from(example["status"].as_u64().unwrap()).unwrap(),
2289 example["body"].clone(),
2290 )
2291 }
2292
2293 #[test]
2294 fn plan_required_keeps_the_feature_and_words_it() {
2295 let (status, body) = plan_required_example("vault-transfer.json", "repos");
2297 assert_eq!(status, 402);
2298 let error = CloudError::from_response(status, &body);
2299 assert!(
2300 matches!(&error, CloudError::PlanRequired(need) if need.feature.as_deref() == Some("repos"))
2301 );
2302 assert_eq!(
2303 error.clone().with_plan(CloudPlan::Unknown),
2304 error,
2305 "an unknown plan is not named"
2306 );
2307 assert!(!error.is_transient());
2308 let repos = error.with_plan(CloudPlan::NoPlan);
2309 assert!(!repos.to_string().contains("engine"));
2310 assert_eq!(
2311 repos.to_string(),
2312 "this workspace has used all its vaults (3 of 3); more are included in Personal, Team and Enterprise; this workspace has no plan; remove or publish a vault in the Cloud, or upgrade the plan"
2313 );
2314
2315 let (status, body) = plan_required_example("organisation-create.json", "company");
2317 let org = CloudError::from_response(status, &body).with_plan(CloudPlan::Team);
2318 assert_eq!(
2319 org.to_string(),
2320 "A company comes with Enterprise, on request: send a request and we set it up with you; this workspace is on Team"
2321 );
2322 let unnamed = CloudError::from_response(
2323 402,
2324 &json!({"error": {"code": "plan_required", "message": "", "feature": "audit_export", "plan_needed": "team"}}),
2325 );
2326 assert_eq!(
2327 unnamed.to_string(),
2328 "audit export is included in Team and Enterprise"
2329 );
2330 let hostile = CloudError::from_response(
2331 402,
2332 &json!({"error": {"code": "plan_required", "message": "x\u{1b}[2J", "feature": "Comp\u{1b}"}}),
2333 );
2334 assert_eq!(
2335 hostile,
2336 CloudError::PlanRequired(Box::new(PlanNeed {
2337 message: Some("x [2J".into()),
2338 ..PlanNeed::default()
2339 })),
2340 "a feature that is not a wire token is dropped, the message is terminal-safe"
2341 );
2342 }
2343
2344 #[test]
2345 fn plan_required_without_a_feature_keeps_the_1x_seat_text() {
2346 let path = format!(
2347 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud/error.plan_required.json",
2348 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2349 );
2350 let body: serde_json::Value =
2351 serde_json::from_slice(&std::fs::read(&path).expect(&path)).expect(&path);
2352 let error = CloudError::from_response(402, &body).with_plan(CloudPlan::NoPlan);
2353 assert_eq!(
2354 error.to_string(),
2355 "your plan does not include the Cloud on this machine (Personal up to 3 hosts registered, up to 2 connected at once; Team and Enterprise up to 3 hosts registered, up to 2 connected at once per seat)"
2356 );
2357 assert!(
2358 matches!(&error, CloudError::PlanRequired(need) if need.plan.is_none()),
2359 "a 1.x refusal is about the Cloud itself, not a feature of the plan"
2360 );
2361 }
2362
2363 #[test]
2364 fn a_locked_workspace_is_one_line_whatever_the_feature() {
2365 let locked = |reason: &str, feature: Option<&str>, needed: &str| {
2366 let mut body = json!({"error": {"code": "plan_required", "message": "Your trial has ended: this workspace is locked.",
2367 "plan_needed": needed, "reason": reason}});
2368 if let Some(f) = feature {
2369 body["error"]["feature"] = f.into();
2370 }
2371 CloudError::from_response(402, &body)
2372 };
2373 let trial = "Your Personal trial has ended: this workspace is locked (read and export only). Choose a plan in the Cloud to sync again.";
2374 for feature in [None, Some("read_only")] {
2375 let e = locked("trial_ended", feature, "personal");
2376 assert_eq!(e.to_string(), trial);
2377 assert!(matches!(&e, CloudError::PlanRequired(n) if n.locked() == Some("trial_ended")));
2378 assert_eq!(
2379 e.with_plan(CloudPlan::Personal).to_string(),
2380 trial,
2381 "the lease's plan adds nothing to the line"
2382 );
2383 }
2384 assert_eq!(
2385 locked("plan_ended", Some("read_only"), "team").to_string(),
2386 "Your plan has ended: this workspace is locked (read and export only). Choose a plan in the Cloud to sync again."
2387 );
2388 assert_eq!(
2389 locked("trial_ended", None, "team").to_string(),
2390 "Your Team trial has ended: this workspace is locked (read and export only). Choose a plan in the Cloud to sync again."
2391 );
2392 let no_plan = locked("no_plan", None, "personal");
2394 assert!(
2395 no_plan.to_string().contains("2 connected at once"),
2396 "{no_plan}"
2397 );
2398 assert!(!no_plan.to_string().contains(LOCKED_MARK));
2399 }
2400
2401 #[test]
2402 fn non_contract_bodies_become_server_errors() {
2403 assert_eq!(
2404 CloudError::from_response(502, &json!("<html>")),
2405 CloudError::Server {
2406 status: 502,
2407 code: "unknown".into()
2408 }
2409 );
2410 assert!(
2411 CloudError::Server {
2412 status: 502,
2413 code: "unknown".into()
2414 }
2415 .is_transient()
2416 );
2417 }
2418
2419 #[test]
2420 fn a_role_that_may_not_add_a_vault_is_forbidden() {
2421 let body = json!({"error": {
2422 "code": "vault_create_forbidden",
2423 "message": "Only an owner, admin or maintainer of this team can add a new vault.",
2424 "role_needed": "maintainer",
2425 }});
2426 assert_eq!(CloudError::from_response(403, &body), CloudError::Forbidden);
2427 assert_ne!(CloudError::from_response(500, &body), CloudError::Forbidden);
2429 }
2430}