1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use std::convert::TryFrom;
4
5use sysknife_proto::sysknife::v1 as proto;
6
7pub const MAX_MESSAGE_BYTES: usize = 4 * 1024 * 1024;
20
21#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct DistroHint {
41 pub id: String,
45 pub family: &'static str,
50 pub version: Option<String>,
53}
54
55pub const DISTRO_FAMILY_FEDORA: &str = "fedora";
57
58pub const DISTRO_FAMILY_DEBIAN: &str = "debian";
60
61pub const DISTRO_FAMILY_OTHER: &str = "other";
63
64pub const KNOWN_ACTION_NAMES: &[&str] = &[
89 "GetSystemState",
90 "CollectDiagnostics",
91 "GetDeploymentHistory",
92 "ListDeployments",
93 "UpdateSystem",
94 "CleanupDeployments",
95 "RebootSystem",
96 "RollbackDeployment",
97 "GetKernelArguments",
98 "PinDeployment",
99 "UnpinDeployment",
100 "RebaseSystem",
101 "SetKernelArguments",
102 "InstallFlatpak",
103 "RemoveFlatpak",
104 "UpdateFlatpak",
105 "SearchFlatpakApps",
106 "ListFlatpakRemotes",
107 "ListInstalledFlatpaks",
108 "AddFlatpakRemote",
109 "RemoveFlatpakRemote",
110 "GetFlatpakAppInfo",
111 "ListToolboxes",
112 "CreateToolbox",
113 "RemoveToolbox",
114 "GetLayeredPackages",
115 "ResetLayeredPackageOverride",
116 "GetPendingUpdates",
117 "InstallPackages",
118 "RemovePackages",
119 "AddLayeredPackage",
120 "RemoveLayeredPackage",
121 "ReplaceLayeredPackage",
122 "RemoveBasePackage",
123 "ListServices",
124 "ListTimers",
125 "ReloadDaemon",
126 "CreateScheduledJob",
127 "StartService",
128 "StopService",
129 "RestartService",
130 "ReloadService",
131 "SetServiceEnabled",
132 "MaskService",
133 "UnmaskService",
134 "GetServiceLogs",
135 "GetServiceStatus",
136 "GetServiceResourceLimits",
137 "SetServiceResourceLimits",
138 "GetFirewallState",
139 "GetNetworkStatus",
140 "GetListeningPorts",
141 "GetNftablesRuleset",
142 "GetFirewallBackendState",
143 "ConfigureWifi",
144 "SetDnsServers",
145 "ConfigureFirewall",
146 "GetDiskUsage",
147 "ListProcesses",
148 "SignalProcess",
149 "GetMemoryInfo",
150 "GetHostState",
151 "GetJournalLog",
153 "VacuumJournal",
154 "GetLvmReport",
156 "ExtendLogicalVolume",
157 "CreateLogicalVolume",
158 "CreateLvSnapshot",
159 "GetSysctl",
161 "SetSysctl",
162 "GetMounts",
164 "AddMount",
165 "RemoveMount",
166 "AddSwap",
167 "RemoveSwap",
168 "GetSudoGrants",
170 "GrantSudoAccess",
171 "RevokeSudoAccess",
172 "GetLogrotateStatus",
174 "ConfigureLogRotation",
175 "RemoveLogRotation",
176 "ConfigureRemoteSyslog",
177 "RemoveRemoteSyslog",
178 "GetPasswordAging",
180 "SetPasswordAging",
181 "SetPasswordPolicy",
182 "SetAccountLockout",
183 "GetAuditRules",
185 "AddAuditRule",
186 "RemoveAuditRule",
187 "GetCertificates",
189 "ObtainCertificate",
190 "RenewCertificates",
191 "GetDateTime",
192 "SetHostname",
193 "SetTimezone",
194 "SetLocale",
195 "SetNtp",
196 "ListPackageRepositories",
197 "AddPackageRepository",
198 "RemovePackageRepository",
199 "EnablePackageRepository",
200 "DisablePackageRepository",
201 "ListContainers",
202 "CreateContainer",
203 "StartContainer",
204 "StopContainer",
205 "RemoveContainer",
206 "GetContainerInfo",
207 "ListUsers",
208 "ListGroups",
209 "CreateUser",
210 "DeleteUser",
211 "AddUserToGroup",
212 "RemoveUserFromGroup",
213 "CreateGroup",
214 "DeleteGroup",
215 "LockUserAccount",
216 "UnlockUserAccount",
217 "GetAuthorizedKeys",
218 "AddAuthorizedKey",
219 "RemoveAuthorizedKey",
220 "SetSshdOption",
221 "ListJobHistory",
222 "AptUpdate",
224 "AptUpgrade",
225 "AptInstall",
226 "AptRemove",
227 "AptPurge",
228 "AptAutoremove",
229 "AptHold",
230 "AptUnhold",
231 "AptSearch",
232 "AptListInstalled",
233 "AptShow",
234 "AptListUpgradable",
235 "AptHistoryList",
236 "UnattendedUpgradesStatus",
237 "ConfigureUnattendedUpgrades",
238 "GetAptPins",
239 "SetAptPin",
240 "RemoveAptPin",
241 "AddPpa",
243 "RemovePpa",
244 "SnapInstall",
246 "SnapRemove",
247 "SnapRefresh",
248 "SnapHold",
249 "SnapUnhold",
250 "SnapList",
251 "SnapInfo",
252 "SnapRevert",
253 "SnapClassicInstall",
254 "UfwEnable",
256 "UfwDisable",
257 "UfwAllow",
258 "UfwDeny",
259 "UfwReset",
260 "UfwStatus",
261 "DistroboxList",
263 "DistroboxCreate",
264 "DistroboxRemove",
265 "NetplanGetConfig",
267 "NetplanApply",
268 "NetplanSet",
269 "NetplanGenerate",
270 "GrubGetKargs",
272 "GrubSetKargs",
273 "CheckPendingReboot",
275 "ResolvectlStatus",
277 "ResolvectlSetDns",
278 "AppArmorStatus",
280 "AppArmorEnforce",
281 "AppArmorComplain",
282 "CloudInitStatus",
284 "UbuntuInstallFlatpak",
286 "UbuntuRemoveFlatpak",
287 "UbuntuUpdateFlatpak",
288 "UbuntuListFlatpaks",
289 "Fail2banStatus",
291 "Fail2banBanIp",
292 "Fail2banUnbanIp",
293 "ConfigureFail2banJail",
294 "UbuntuReleaseUpgrade",
296 "ProStatus",
298 "ProAttach",
299 "ProDetach",
300 "EnableProService",
301 "DisableProService",
302 "LivepatchStatus",
304 "MultipassList",
306 "UfwDeleteRule",
308 "UfwLimit",
309];
310
311#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
318#[serde(transparent)]
319pub struct ActionName(String);
320
321impl ActionName {
322 pub fn parse(name: impl Into<String>) -> Result<Self, UnknownActionName> {
324 let name = name.into();
325 if KNOWN_ACTION_NAMES.contains(&name.as_str()) {
326 Ok(Self(name))
327 } else {
328 Err(UnknownActionName(name))
329 }
330 }
331
332 pub fn as_str(&self) -> &str {
334 &self.0
335 }
336}
337
338impl std::fmt::Display for ActionName {
339 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
340 f.write_str(&self.0)
341 }
342}
343
344impl AsRef<str> for ActionName {
345 fn as_ref(&self) -> &str {
346 &self.0
347 }
348}
349
350#[derive(Clone, Debug, PartialEq, Eq)]
352pub struct UnknownActionName(pub String);
353
354impl std::fmt::Display for UnknownActionName {
355 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
356 write!(f, "unknown action name: '{}'", self.0)
357 }
358}
359
360impl std::error::Error for UnknownActionName {}
361
362#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
371#[serde(transparent)]
372pub struct RequestHash(String);
373
374impl RequestHash {
375 pub fn new(s: impl Into<String>) -> Self {
376 Self(s.into())
377 }
378 pub fn as_str(&self) -> &str {
379 &self.0
380 }
381 pub fn into_inner(self) -> String {
382 self.0
383 }
384}
385
386impl std::fmt::Display for RequestHash {
387 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
388 f.write_str(&self.0)
389 }
390}
391
392impl AsRef<str> for RequestHash {
393 fn as_ref(&self) -> &str {
394 &self.0
395 }
396}
397
398impl From<String> for RequestHash {
399 fn from(s: String) -> Self {
400 Self(s)
401 }
402}
403
404#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
417#[serde(transparent)]
418pub struct TransactionId(String);
419
420#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
427#[serde(transparent)]
428pub struct ApprovalReceipt(String);
429
430impl std::fmt::Debug for ApprovalReceipt {
431 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
432 f.write_str("ApprovalReceipt(<redacted>)")
433 }
434}
435
436macro_rules! opaque_string_newtype {
437 ($name:ident) => {
438 impl $name {
439 pub fn new(s: impl Into<String>) -> Self {
440 Self(s.into())
441 }
442 pub fn as_str(&self) -> &str {
443 &self.0
444 }
445 pub fn into_inner(self) -> String {
446 self.0
447 }
448 }
449
450 impl AsRef<str> for $name {
451 fn as_ref(&self) -> &str {
452 &self.0
453 }
454 }
455
456 impl From<String> for $name {
457 fn from(s: String) -> Self {
458 Self(s)
459 }
460 }
461 };
462}
463
464opaque_string_newtype!(TransactionId);
465opaque_string_newtype!(ApprovalReceipt);
466
467impl std::fmt::Display for TransactionId {
472 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
473 f.write_str(&self.0)
474 }
475}
476
477#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
488#[serde(rename_all = "snake_case")]
489pub enum CallerRole {
490 Observer,
491 Dev,
492 Admin,
493 Boot,
494}
495
496impl CallerRole {
497 pub fn as_str(&self) -> &'static str {
505 match self {
506 Self::Observer => "observer",
507 Self::Dev => "dev",
508 Self::Admin => "admin",
509 Self::Boot => "boot",
510 }
511 }
512}
513
514#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
515#[serde(rename_all = "snake_case")]
516pub enum RiskLevel {
517 Low,
518 Medium,
519 High,
520}
521
522#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
523#[serde(rename_all = "snake_case")]
524pub enum JobState {
525 Queued,
526 Running,
527 Succeeded,
528 Failed,
529 Canceled,
530 RolledBack,
531 NeedsReboot,
532}
533
534#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
541#[serde(rename_all = "snake_case")]
542pub enum FailureCategory {
543 ValidationFailure,
544 AuthorizationFailure,
545 PolicyDenied,
546 StaleApproval,
547 ExecutionFailure,
548 TransientInfrastructureFailure,
549 Cancellation,
550 StuckExecution,
551 RebootRequired,
552 RollbackFailure,
553}
554
555#[derive(Debug, thiserror::Error)]
556pub enum BridgeError {
557 #[error("invalid json payload for {0}")]
558 InvalidJson(&'static str, #[source] serde_json::Error),
559
560 #[error("invalid enum value {value} for {field}")]
561 InvalidEnum { field: &'static str, value: i32 },
562}
563
564#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
565pub struct RequestEnvelope {
566 pub action_name: String,
567 pub request_id: String,
568 pub params: Value,
569 pub caller_role: CallerRole,
570 pub request_hash: RequestHash,
571}
572
573#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
574pub struct PreviewEnvelope {
575 pub summary: String,
576 pub risk_level: RiskLevel,
577 pub current_state: Value,
578 pub proposed_change: Value,
579 pub expected_side_effects: Vec<String>,
580 pub reboot_required: bool,
581 pub rollback_available: bool,
582 pub warnings: Vec<String>,
583 pub request_hash: RequestHash,
584}
585
586#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
587pub struct ResultEnvelope {
588 pub status: JobState,
589 pub summary: String,
590 pub warnings: Vec<String>,
591 pub job_id: Option<String>,
592 pub needs_reboot: bool,
593 pub rollback_ref: Option<String>,
594 pub transaction_id: String,
595}
596
597#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
598pub struct TransactionRecord {
599 pub transaction_id: String,
600 pub request_id: String,
601 pub request_hash: String,
602 pub action_name: String,
603 pub risk_level: RiskLevel,
604 pub status: JobState,
605 pub approval_id: Option<String>,
606 pub summary: String,
607 pub warnings: Vec<String>,
608}
609
610impl From<CallerRole> for proto::CallerRole {
611 fn from(value: CallerRole) -> Self {
616 match value {
617 CallerRole::Observer => proto::CallerRole::Observer,
618 CallerRole::Dev => proto::CallerRole::Dev,
619 CallerRole::Admin => proto::CallerRole::Admin,
620 CallerRole::Boot => proto::CallerRole::Boot,
621 }
622 }
623}
624
625impl TryFrom<proto::CallerRole> for CallerRole {
626 type Error = BridgeError;
627
628 fn try_from(value: proto::CallerRole) -> Result<Self, Self::Error> {
629 match i32::from(value) {
630 1 => Ok(CallerRole::Observer),
631 2 => Ok(CallerRole::Dev),
632 3 => Ok(CallerRole::Admin),
633 4 => Ok(CallerRole::Boot),
634 code => Err(BridgeError::InvalidEnum {
635 field: "caller_role",
636 value: code,
637 }),
638 }
639 }
640}
641
642impl From<RiskLevel> for proto::RiskLevel {
643 fn from(value: RiskLevel) -> Self {
644 match value {
645 RiskLevel::Low => proto::RiskLevel::Low,
646 RiskLevel::Medium => proto::RiskLevel::Medium,
647 RiskLevel::High => proto::RiskLevel::High,
648 }
649 }
650}
651
652impl TryFrom<proto::RiskLevel> for RiskLevel {
653 type Error = BridgeError;
654
655 fn try_from(value: proto::RiskLevel) -> Result<Self, Self::Error> {
656 match i32::from(value) {
657 1 => Ok(RiskLevel::Low),
658 2 => Ok(RiskLevel::Medium),
659 3 => Ok(RiskLevel::High),
660 code => Err(BridgeError::InvalidEnum {
661 field: "risk_level",
662 value: code,
663 }),
664 }
665 }
666}
667
668impl From<JobState> for proto::JobState {
669 fn from(value: JobState) -> Self {
670 match value {
671 JobState::Queued => proto::JobState::Queued,
672 JobState::Running => proto::JobState::Running,
673 JobState::Succeeded => proto::JobState::Succeeded,
674 JobState::Failed => proto::JobState::Failed,
675 JobState::Canceled => proto::JobState::Canceled,
676 JobState::RolledBack => proto::JobState::RolledBack,
677 JobState::NeedsReboot => proto::JobState::NeedsReboot,
678 }
679 }
680}
681
682impl TryFrom<proto::JobState> for JobState {
683 type Error = BridgeError;
684
685 fn try_from(value: proto::JobState) -> Result<Self, Self::Error> {
686 match i32::from(value) {
687 1 => Ok(JobState::Queued),
688 2 => Ok(JobState::Running),
689 3 => Ok(JobState::Succeeded),
690 4 => Ok(JobState::Failed),
691 5 => Ok(JobState::Canceled),
692 6 => Ok(JobState::RolledBack),
693 7 => Ok(JobState::NeedsReboot),
694 code => Err(BridgeError::InvalidEnum {
695 field: "job_state",
696 value: code,
697 }),
698 }
699 }
700}
701
702impl From<FailureCategory> for proto::FailureCategory {
703 fn from(value: FailureCategory) -> Self {
704 match value {
705 FailureCategory::ValidationFailure => proto::FailureCategory::ValidationFailure,
706 FailureCategory::AuthorizationFailure => proto::FailureCategory::AuthorizationFailure,
707 FailureCategory::PolicyDenied => proto::FailureCategory::PolicyDenied,
708 FailureCategory::StaleApproval => proto::FailureCategory::StaleApproval,
709 FailureCategory::ExecutionFailure => proto::FailureCategory::ExecutionFailure,
710 FailureCategory::TransientInfrastructureFailure => {
711 proto::FailureCategory::TransientInfrastructureFailure
712 }
713 FailureCategory::Cancellation => proto::FailureCategory::Cancellation,
714 FailureCategory::StuckExecution => proto::FailureCategory::StuckExecution,
715 FailureCategory::RebootRequired => proto::FailureCategory::RebootRequired,
716 FailureCategory::RollbackFailure => proto::FailureCategory::RollbackFailure,
717 }
718 }
719}
720
721impl TryFrom<proto::FailureCategory> for FailureCategory {
722 type Error = BridgeError;
723
724 fn try_from(value: proto::FailureCategory) -> Result<Self, Self::Error> {
725 match i32::from(value) {
726 1 => Ok(FailureCategory::ValidationFailure),
727 2 => Ok(FailureCategory::AuthorizationFailure),
728 3 => Ok(FailureCategory::PolicyDenied),
729 4 => Ok(FailureCategory::StaleApproval),
730 5 => Ok(FailureCategory::ExecutionFailure),
731 6 => Ok(FailureCategory::TransientInfrastructureFailure),
732 7 => Ok(FailureCategory::Cancellation),
733 8 => Ok(FailureCategory::StuckExecution),
734 9 => Ok(FailureCategory::RebootRequired),
735 10 => Ok(FailureCategory::RollbackFailure),
736 code => Err(BridgeError::InvalidEnum {
737 field: "failure_category",
738 value: code,
739 }),
740 }
741 }
742}
743
744impl From<RequestEnvelope> for proto::RequestEnvelope {
745 fn from(value: RequestEnvelope) -> Self {
746 Self {
747 action_name: value.action_name,
748 request_id: value.request_id,
749 params_json: serde_json::to_string(&value.params).expect("json serialization"),
750 caller_role: i32::from(proto::CallerRole::from(value.caller_role)),
751 request_hash: value.request_hash.into_inner(),
752 }
753 }
754}
755
756impl TryFrom<proto::RequestEnvelope> for RequestEnvelope {
757 type Error = BridgeError;
758
759 fn try_from(value: proto::RequestEnvelope) -> Result<Self, Self::Error> {
760 let params = serde_json::from_str(&value.params_json)
761 .map_err(|error| BridgeError::InvalidJson("params_json", error))?;
762
763 Ok(Self {
764 action_name: value.action_name,
765 request_id: value.request_id,
766 params,
767 caller_role: CallerRole::try_from(
768 proto::CallerRole::try_from(value.caller_role).map_err(|_| {
769 BridgeError::InvalidEnum {
770 field: "caller_role",
771 value: value.caller_role,
772 }
773 })?,
774 )?,
775 request_hash: RequestHash::from(value.request_hash),
776 })
777 }
778}
779
780impl From<PreviewEnvelope> for proto::PreviewEnvelope {
781 fn from(value: PreviewEnvelope) -> Self {
782 Self {
783 summary: value.summary,
784 risk_level: i32::from(proto::RiskLevel::from(value.risk_level)),
785 current_state_json: serde_json::to_string(&value.current_state)
786 .expect("json serialization"),
787 proposed_change_json: serde_json::to_string(&value.proposed_change)
788 .expect("json serialization"),
789 expected_side_effects: value.expected_side_effects,
790 reboot_required: value.reboot_required,
791 rollback_available: value.rollback_available,
792 warnings: value.warnings,
793 request_hash: value.request_hash.into_inner(),
794 }
795 }
796}
797
798impl TryFrom<proto::PreviewEnvelope> for PreviewEnvelope {
799 type Error = BridgeError;
800
801 fn try_from(value: proto::PreviewEnvelope) -> Result<Self, Self::Error> {
802 let current_state = serde_json::from_str(&value.current_state_json)
803 .map_err(|error| BridgeError::InvalidJson("current_state_json", error))?;
804 let proposed_change = serde_json::from_str(&value.proposed_change_json)
805 .map_err(|error| BridgeError::InvalidJson("proposed_change_json", error))?;
806
807 Ok(Self {
808 summary: value.summary,
809 risk_level: RiskLevel::try_from(
810 proto::RiskLevel::try_from(value.risk_level).map_err(|_| {
811 BridgeError::InvalidEnum {
812 field: "risk_level",
813 value: value.risk_level,
814 }
815 })?,
816 )?,
817 current_state,
818 proposed_change,
819 expected_side_effects: value.expected_side_effects,
820 reboot_required: value.reboot_required,
821 rollback_available: value.rollback_available,
822 warnings: value.warnings,
823 request_hash: RequestHash::from(value.request_hash),
824 })
825 }
826}
827
828impl From<ResultEnvelope> for proto::ResultEnvelope {
829 fn from(value: ResultEnvelope) -> Self {
830 Self {
831 status: i32::from(proto::JobState::from(value.status)),
832 summary: value.summary,
833 warnings: value.warnings,
834 job_id: value.job_id.unwrap_or_default(),
835 needs_reboot: value.needs_reboot,
836 rollback_ref: value.rollback_ref.unwrap_or_default(),
837 transaction_id: value.transaction_id,
838 }
839 }
840}
841
842impl TryFrom<proto::ResultEnvelope> for ResultEnvelope {
843 type Error = BridgeError;
844
845 fn try_from(value: proto::ResultEnvelope) -> Result<Self, Self::Error> {
846 Ok(Self {
847 status: JobState::try_from(proto::JobState::try_from(value.status).map_err(|_| {
848 BridgeError::InvalidEnum {
849 field: "job_state",
850 value: value.status,
851 }
852 })?)?,
853 summary: value.summary,
854 warnings: value.warnings,
855 job_id: if value.job_id.is_empty() {
856 None
857 } else {
858 Some(value.job_id)
859 },
860 needs_reboot: value.needs_reboot,
861 rollback_ref: if value.rollback_ref.is_empty() {
862 None
863 } else {
864 Some(value.rollback_ref)
865 },
866 transaction_id: value.transaction_id,
867 })
868 }
869}
870
871impl From<TransactionRecord> for proto::TransactionRecord {
872 fn from(value: TransactionRecord) -> Self {
873 Self {
874 transaction_id: value.transaction_id,
875 request_id: value.request_id,
876 request_hash: value.request_hash,
877 action_name: value.action_name,
878 risk_level: i32::from(proto::RiskLevel::from(value.risk_level)),
879 status: i32::from(proto::JobState::from(value.status)),
880 approval_id: value.approval_id.unwrap_or_default(),
881 summary: value.summary,
882 warnings: value.warnings,
883 }
884 }
885}
886
887impl TryFrom<proto::TransactionRecord> for TransactionRecord {
888 type Error = BridgeError;
889
890 fn try_from(value: proto::TransactionRecord) -> Result<Self, Self::Error> {
891 Ok(Self {
892 transaction_id: value.transaction_id,
893 request_id: value.request_id,
894 request_hash: value.request_hash,
895 action_name: value.action_name,
896 risk_level: RiskLevel::try_from(
897 proto::RiskLevel::try_from(value.risk_level).map_err(|_| {
898 BridgeError::InvalidEnum {
899 field: "risk_level",
900 value: value.risk_level,
901 }
902 })?,
903 )?,
904 status: JobState::try_from(proto::JobState::try_from(value.status).map_err(|_| {
905 BridgeError::InvalidEnum {
906 field: "job_state",
907 value: value.status,
908 }
909 })?)?,
910 approval_id: if value.approval_id.is_empty() {
911 None
912 } else {
913 Some(value.approval_id)
914 },
915 summary: value.summary,
916 warnings: value.warnings,
917 })
918 }
919}
920
921#[cfg(test)]
922mod request_hash_tests {
923 use super::*;
924
925 #[test]
926 fn serde_round_trips_via_transparent_string() {
927 let r = RequestHash::new("abc123".to_string());
930 let json = serde_json::to_string(&r).unwrap();
931 assert_eq!(json, "\"abc123\"");
932 let back: RequestHash = serde_json::from_str("\"abc123\"").unwrap();
933 assert_eq!(back, r);
934 }
935}
936
937#[cfg(test)]
938mod caller_role_ordering_tests {
939 use super::CallerRole;
940
941 #[test]
942 fn caller_role_orders_least_to_most_privileged() {
943 assert!(CallerRole::Observer < CallerRole::Dev);
946 assert!(CallerRole::Dev < CallerRole::Admin);
947 assert!(CallerRole::Admin < CallerRole::Boot);
948
949 assert!(CallerRole::Admin >= CallerRole::Dev);
951 assert!(!(CallerRole::Observer >= CallerRole::Dev));
952 }
953
954 #[test]
955 fn max_selects_the_higher_privilege() {
956 assert_eq!(
959 CallerRole::Observer.max(CallerRole::Admin),
960 CallerRole::Admin
961 );
962 assert_eq!(CallerRole::Boot.max(CallerRole::Dev), CallerRole::Boot);
963 }
964}
965
966#[cfg(test)]
967mod frame_limit_declaration_tests {
968 use std::fs;
969 use std::path::{Path, PathBuf};
970
971 fn workspace_root() -> PathBuf {
974 let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
975 loop {
976 let manifest = dir.join("Cargo.toml");
977 if manifest.is_file() {
978 if let Ok(text) = fs::read_to_string(&manifest) {
979 if text.contains("[workspace]") {
980 return dir;
981 }
982 }
983 }
984 if !dir.pop() {
985 panic!("could not locate the workspace root");
986 }
987 }
988 }
989
990 fn walk_rs(dir: &Path, out: &mut Vec<PathBuf>) {
992 if let Ok(entries) = fs::read_dir(dir) {
993 for entry in entries.flatten() {
994 let path = entry.path();
995 if path.file_name().is_some_and(|n| n == "target") {
996 continue;
997 }
998 if path.is_dir() {
999 walk_rs(&path, out);
1000 } else if path.extension().is_some_and(|e| e == "rs") {
1001 out.push(path);
1002 }
1003 }
1004 }
1005 }
1006
1007 #[test]
1028 fn frame_limit_is_declared_once() {
1029 let root = workspace_root();
1030 let mut files: Vec<PathBuf> = Vec::new();
1031 for crate_dir in [
1032 "crates/sysknife-types",
1033 "crates/sysknife-daemon",
1034 "apps/sysknife-cli",
1035 ] {
1036 walk_rs(&root.join(crate_dir), &mut files);
1037 }
1038
1039 let mut declarations: Vec<String> = Vec::new();
1040 for path in &files {
1041 let text = fs::read_to_string(path).unwrap();
1042 for (idx, raw) in text.lines().enumerate() {
1043 let line = raw.trim();
1044 let is_const_decl = [
1045 "const ",
1046 "pub const ",
1047 "pub(crate) const ",
1048 "pub(super) const ",
1049 ]
1050 .iter()
1051 .any(|p| line.starts_with(p));
1052 if is_const_decl && line.contains("4 * 1024 * 1024") {
1055 declarations.push(format!("{}:{}", path.display(), idx + 1));
1056 }
1057 }
1058 }
1059
1060 assert_eq!(
1061 declarations.len(),
1062 1,
1063 "expected exactly one declaration of the 4 MiB frame limit, \
1064 found {}:\n{:#?}",
1065 declarations.len(),
1066 declarations
1067 );
1068 let (decl_path, _line) = declarations[0].rsplit_once(':').unwrap();
1069 let relativized = PathBuf::from(decl_path.replace(&format!("{}/", root.display()), ""));
1070 assert_eq!(
1071 relativized,
1072 Path::new("crates/sysknife-types/src/lib.rs"),
1073 "the single frame-limit declaration must live in sysknife-types"
1074 );
1075 }
1076}