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 "ProSecurityStatus",
299 "ProAttach",
300 "ProDetach",
301 "EnableProService",
302 "DisableProService",
303 "LivepatchStatus",
305 "MultipassList",
307 "UfwDeleteRule",
309 "UfwLimit",
310];
311
312#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
319#[serde(transparent)]
320pub struct ActionName(String);
321
322impl ActionName {
323 pub fn parse(name: impl Into<String>) -> Result<Self, UnknownActionName> {
325 let name = name.into();
326 if KNOWN_ACTION_NAMES.contains(&name.as_str()) {
327 Ok(Self(name))
328 } else {
329 Err(UnknownActionName(name))
330 }
331 }
332
333 pub fn as_str(&self) -> &str {
335 &self.0
336 }
337}
338
339impl std::fmt::Display for ActionName {
340 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341 f.write_str(&self.0)
342 }
343}
344
345impl AsRef<str> for ActionName {
346 fn as_ref(&self) -> &str {
347 &self.0
348 }
349}
350
351#[derive(Clone, Debug, PartialEq, Eq)]
353pub struct UnknownActionName(pub String);
354
355impl std::fmt::Display for UnknownActionName {
356 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
357 write!(f, "unknown action name: '{}'", self.0)
358 }
359}
360
361impl std::error::Error for UnknownActionName {}
362
363#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
372#[serde(transparent)]
373pub struct RequestHash(String);
374
375impl RequestHash {
376 pub fn new(s: impl Into<String>) -> Self {
377 Self(s.into())
378 }
379 pub fn as_str(&self) -> &str {
380 &self.0
381 }
382 pub fn into_inner(self) -> String {
383 self.0
384 }
385}
386
387impl std::fmt::Display for RequestHash {
388 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
389 f.write_str(&self.0)
390 }
391}
392
393impl AsRef<str> for RequestHash {
394 fn as_ref(&self) -> &str {
395 &self.0
396 }
397}
398
399impl From<String> for RequestHash {
400 fn from(s: String) -> Self {
401 Self(s)
402 }
403}
404
405#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
418#[serde(transparent)]
419pub struct TransactionId(String);
420
421#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
428#[serde(transparent)]
429pub struct ApprovalReceipt(String);
430
431impl std::fmt::Debug for ApprovalReceipt {
432 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433 f.write_str("ApprovalReceipt(<redacted>)")
434 }
435}
436
437macro_rules! opaque_string_newtype {
438 ($name:ident) => {
439 impl $name {
440 pub fn new(s: impl Into<String>) -> Self {
441 Self(s.into())
442 }
443 pub fn as_str(&self) -> &str {
444 &self.0
445 }
446 pub fn into_inner(self) -> String {
447 self.0
448 }
449 }
450
451 impl AsRef<str> for $name {
452 fn as_ref(&self) -> &str {
453 &self.0
454 }
455 }
456
457 impl From<String> for $name {
458 fn from(s: String) -> Self {
459 Self(s)
460 }
461 }
462 };
463}
464
465opaque_string_newtype!(TransactionId);
466opaque_string_newtype!(ApprovalReceipt);
467
468impl std::fmt::Display for TransactionId {
473 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474 f.write_str(&self.0)
475 }
476}
477
478#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
489#[serde(rename_all = "snake_case")]
490pub enum CallerRole {
491 Observer,
492 Dev,
493 Admin,
494 Boot,
495}
496
497impl CallerRole {
498 pub fn as_str(&self) -> &'static str {
506 match self {
507 Self::Observer => "observer",
508 Self::Dev => "dev",
509 Self::Admin => "admin",
510 Self::Boot => "boot",
511 }
512 }
513}
514
515#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
516#[serde(rename_all = "snake_case")]
517pub enum RiskLevel {
518 Low,
519 Medium,
520 High,
521}
522
523#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
524#[serde(rename_all = "snake_case")]
525pub enum JobState {
526 Queued,
527 Running,
528 Succeeded,
529 Failed,
530 Canceled,
531 RolledBack,
532 NeedsReboot,
533}
534
535#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
542#[serde(rename_all = "snake_case")]
543pub enum FailureCategory {
544 ValidationFailure,
545 AuthorizationFailure,
546 PolicyDenied,
547 StaleApproval,
548 ExecutionFailure,
549 TransientInfrastructureFailure,
550 Cancellation,
551 StuckExecution,
552 RebootRequired,
553 RollbackFailure,
554}
555
556#[derive(Debug, thiserror::Error)]
557pub enum BridgeError {
558 #[error("invalid json payload for {0}")]
559 InvalidJson(&'static str, #[source] serde_json::Error),
560
561 #[error("invalid enum value {value} for {field}")]
562 InvalidEnum { field: &'static str, value: i32 },
563}
564
565#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
566pub struct RequestEnvelope {
567 pub action_name: String,
568 pub request_id: String,
569 pub params: Value,
570 pub caller_role: CallerRole,
571 pub request_hash: RequestHash,
572}
573
574#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
575pub struct PreviewEnvelope {
576 pub summary: String,
577 pub risk_level: RiskLevel,
578 pub current_state: Value,
579 pub proposed_change: Value,
580 pub expected_side_effects: Vec<String>,
581 pub reboot_required: bool,
582 pub rollback_available: bool,
583 pub warnings: Vec<String>,
584 pub request_hash: RequestHash,
585}
586
587#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
588pub struct ResultEnvelope {
589 pub status: JobState,
590 pub summary: String,
591 pub warnings: Vec<String>,
592 pub job_id: Option<String>,
593 pub needs_reboot: bool,
594 pub rollback_ref: Option<String>,
595 pub transaction_id: String,
596}
597
598#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
599pub struct TransactionRecord {
600 pub transaction_id: String,
601 pub request_id: String,
602 pub request_hash: String,
603 pub action_name: String,
604 pub risk_level: RiskLevel,
605 pub status: JobState,
606 pub approval_id: Option<String>,
607 pub summary: String,
608 pub warnings: Vec<String>,
609}
610
611impl From<CallerRole> for proto::CallerRole {
612 fn from(value: CallerRole) -> Self {
617 match value {
618 CallerRole::Observer => proto::CallerRole::Observer,
619 CallerRole::Dev => proto::CallerRole::Dev,
620 CallerRole::Admin => proto::CallerRole::Admin,
621 CallerRole::Boot => proto::CallerRole::Boot,
622 }
623 }
624}
625
626impl TryFrom<proto::CallerRole> for CallerRole {
627 type Error = BridgeError;
628
629 fn try_from(value: proto::CallerRole) -> Result<Self, Self::Error> {
630 match i32::from(value) {
631 1 => Ok(CallerRole::Observer),
632 2 => Ok(CallerRole::Dev),
633 3 => Ok(CallerRole::Admin),
634 4 => Ok(CallerRole::Boot),
635 code => Err(BridgeError::InvalidEnum {
636 field: "caller_role",
637 value: code,
638 }),
639 }
640 }
641}
642
643impl From<RiskLevel> for proto::RiskLevel {
644 fn from(value: RiskLevel) -> Self {
645 match value {
646 RiskLevel::Low => proto::RiskLevel::Low,
647 RiskLevel::Medium => proto::RiskLevel::Medium,
648 RiskLevel::High => proto::RiskLevel::High,
649 }
650 }
651}
652
653impl TryFrom<proto::RiskLevel> for RiskLevel {
654 type Error = BridgeError;
655
656 fn try_from(value: proto::RiskLevel) -> Result<Self, Self::Error> {
657 match i32::from(value) {
658 1 => Ok(RiskLevel::Low),
659 2 => Ok(RiskLevel::Medium),
660 3 => Ok(RiskLevel::High),
661 code => Err(BridgeError::InvalidEnum {
662 field: "risk_level",
663 value: code,
664 }),
665 }
666 }
667}
668
669impl From<JobState> for proto::JobState {
670 fn from(value: JobState) -> Self {
671 match value {
672 JobState::Queued => proto::JobState::Queued,
673 JobState::Running => proto::JobState::Running,
674 JobState::Succeeded => proto::JobState::Succeeded,
675 JobState::Failed => proto::JobState::Failed,
676 JobState::Canceled => proto::JobState::Canceled,
677 JobState::RolledBack => proto::JobState::RolledBack,
678 JobState::NeedsReboot => proto::JobState::NeedsReboot,
679 }
680 }
681}
682
683impl TryFrom<proto::JobState> for JobState {
684 type Error = BridgeError;
685
686 fn try_from(value: proto::JobState) -> Result<Self, Self::Error> {
687 match i32::from(value) {
688 1 => Ok(JobState::Queued),
689 2 => Ok(JobState::Running),
690 3 => Ok(JobState::Succeeded),
691 4 => Ok(JobState::Failed),
692 5 => Ok(JobState::Canceled),
693 6 => Ok(JobState::RolledBack),
694 7 => Ok(JobState::NeedsReboot),
695 code => Err(BridgeError::InvalidEnum {
696 field: "job_state",
697 value: code,
698 }),
699 }
700 }
701}
702
703impl From<FailureCategory> for proto::FailureCategory {
704 fn from(value: FailureCategory) -> Self {
705 match value {
706 FailureCategory::ValidationFailure => proto::FailureCategory::ValidationFailure,
707 FailureCategory::AuthorizationFailure => proto::FailureCategory::AuthorizationFailure,
708 FailureCategory::PolicyDenied => proto::FailureCategory::PolicyDenied,
709 FailureCategory::StaleApproval => proto::FailureCategory::StaleApproval,
710 FailureCategory::ExecutionFailure => proto::FailureCategory::ExecutionFailure,
711 FailureCategory::TransientInfrastructureFailure => {
712 proto::FailureCategory::TransientInfrastructureFailure
713 }
714 FailureCategory::Cancellation => proto::FailureCategory::Cancellation,
715 FailureCategory::StuckExecution => proto::FailureCategory::StuckExecution,
716 FailureCategory::RebootRequired => proto::FailureCategory::RebootRequired,
717 FailureCategory::RollbackFailure => proto::FailureCategory::RollbackFailure,
718 }
719 }
720}
721
722impl TryFrom<proto::FailureCategory> for FailureCategory {
723 type Error = BridgeError;
724
725 fn try_from(value: proto::FailureCategory) -> Result<Self, Self::Error> {
726 match i32::from(value) {
727 1 => Ok(FailureCategory::ValidationFailure),
728 2 => Ok(FailureCategory::AuthorizationFailure),
729 3 => Ok(FailureCategory::PolicyDenied),
730 4 => Ok(FailureCategory::StaleApproval),
731 5 => Ok(FailureCategory::ExecutionFailure),
732 6 => Ok(FailureCategory::TransientInfrastructureFailure),
733 7 => Ok(FailureCategory::Cancellation),
734 8 => Ok(FailureCategory::StuckExecution),
735 9 => Ok(FailureCategory::RebootRequired),
736 10 => Ok(FailureCategory::RollbackFailure),
737 code => Err(BridgeError::InvalidEnum {
738 field: "failure_category",
739 value: code,
740 }),
741 }
742 }
743}
744
745impl From<RequestEnvelope> for proto::RequestEnvelope {
746 fn from(value: RequestEnvelope) -> Self {
747 Self {
748 action_name: value.action_name,
749 request_id: value.request_id,
750 params_json: serde_json::to_string(&value.params).expect("json serialization"),
751 caller_role: i32::from(proto::CallerRole::from(value.caller_role)),
752 request_hash: value.request_hash.into_inner(),
753 }
754 }
755}
756
757impl TryFrom<proto::RequestEnvelope> for RequestEnvelope {
758 type Error = BridgeError;
759
760 fn try_from(value: proto::RequestEnvelope) -> Result<Self, Self::Error> {
761 let params = serde_json::from_str(&value.params_json)
762 .map_err(|error| BridgeError::InvalidJson("params_json", error))?;
763
764 Ok(Self {
765 action_name: value.action_name,
766 request_id: value.request_id,
767 params,
768 caller_role: CallerRole::try_from(
769 proto::CallerRole::try_from(value.caller_role).map_err(|_| {
770 BridgeError::InvalidEnum {
771 field: "caller_role",
772 value: value.caller_role,
773 }
774 })?,
775 )?,
776 request_hash: RequestHash::from(value.request_hash),
777 })
778 }
779}
780
781impl From<PreviewEnvelope> for proto::PreviewEnvelope {
782 fn from(value: PreviewEnvelope) -> Self {
783 Self {
784 summary: value.summary,
785 risk_level: i32::from(proto::RiskLevel::from(value.risk_level)),
786 current_state_json: serde_json::to_string(&value.current_state)
787 .expect("json serialization"),
788 proposed_change_json: serde_json::to_string(&value.proposed_change)
789 .expect("json serialization"),
790 expected_side_effects: value.expected_side_effects,
791 reboot_required: value.reboot_required,
792 rollback_available: value.rollback_available,
793 warnings: value.warnings,
794 request_hash: value.request_hash.into_inner(),
795 }
796 }
797}
798
799impl TryFrom<proto::PreviewEnvelope> for PreviewEnvelope {
800 type Error = BridgeError;
801
802 fn try_from(value: proto::PreviewEnvelope) -> Result<Self, Self::Error> {
803 let current_state = serde_json::from_str(&value.current_state_json)
804 .map_err(|error| BridgeError::InvalidJson("current_state_json", error))?;
805 let proposed_change = serde_json::from_str(&value.proposed_change_json)
806 .map_err(|error| BridgeError::InvalidJson("proposed_change_json", error))?;
807
808 Ok(Self {
809 summary: value.summary,
810 risk_level: RiskLevel::try_from(
811 proto::RiskLevel::try_from(value.risk_level).map_err(|_| {
812 BridgeError::InvalidEnum {
813 field: "risk_level",
814 value: value.risk_level,
815 }
816 })?,
817 )?,
818 current_state,
819 proposed_change,
820 expected_side_effects: value.expected_side_effects,
821 reboot_required: value.reboot_required,
822 rollback_available: value.rollback_available,
823 warnings: value.warnings,
824 request_hash: RequestHash::from(value.request_hash),
825 })
826 }
827}
828
829impl From<ResultEnvelope> for proto::ResultEnvelope {
830 fn from(value: ResultEnvelope) -> Self {
831 Self {
832 status: i32::from(proto::JobState::from(value.status)),
833 summary: value.summary,
834 warnings: value.warnings,
835 job_id: value.job_id.unwrap_or_default(),
836 needs_reboot: value.needs_reboot,
837 rollback_ref: value.rollback_ref.unwrap_or_default(),
838 transaction_id: value.transaction_id,
839 }
840 }
841}
842
843impl TryFrom<proto::ResultEnvelope> for ResultEnvelope {
844 type Error = BridgeError;
845
846 fn try_from(value: proto::ResultEnvelope) -> Result<Self, Self::Error> {
847 Ok(Self {
848 status: JobState::try_from(proto::JobState::try_from(value.status).map_err(|_| {
849 BridgeError::InvalidEnum {
850 field: "job_state",
851 value: value.status,
852 }
853 })?)?,
854 summary: value.summary,
855 warnings: value.warnings,
856 job_id: if value.job_id.is_empty() {
857 None
858 } else {
859 Some(value.job_id)
860 },
861 needs_reboot: value.needs_reboot,
862 rollback_ref: if value.rollback_ref.is_empty() {
863 None
864 } else {
865 Some(value.rollback_ref)
866 },
867 transaction_id: value.transaction_id,
868 })
869 }
870}
871
872impl From<TransactionRecord> for proto::TransactionRecord {
873 fn from(value: TransactionRecord) -> Self {
874 Self {
875 transaction_id: value.transaction_id,
876 request_id: value.request_id,
877 request_hash: value.request_hash,
878 action_name: value.action_name,
879 risk_level: i32::from(proto::RiskLevel::from(value.risk_level)),
880 status: i32::from(proto::JobState::from(value.status)),
881 approval_id: value.approval_id.unwrap_or_default(),
882 summary: value.summary,
883 warnings: value.warnings,
884 }
885 }
886}
887
888impl TryFrom<proto::TransactionRecord> for TransactionRecord {
889 type Error = BridgeError;
890
891 fn try_from(value: proto::TransactionRecord) -> Result<Self, Self::Error> {
892 Ok(Self {
893 transaction_id: value.transaction_id,
894 request_id: value.request_id,
895 request_hash: value.request_hash,
896 action_name: value.action_name,
897 risk_level: RiskLevel::try_from(
898 proto::RiskLevel::try_from(value.risk_level).map_err(|_| {
899 BridgeError::InvalidEnum {
900 field: "risk_level",
901 value: value.risk_level,
902 }
903 })?,
904 )?,
905 status: JobState::try_from(proto::JobState::try_from(value.status).map_err(|_| {
906 BridgeError::InvalidEnum {
907 field: "job_state",
908 value: value.status,
909 }
910 })?)?,
911 approval_id: if value.approval_id.is_empty() {
912 None
913 } else {
914 Some(value.approval_id)
915 },
916 summary: value.summary,
917 warnings: value.warnings,
918 })
919 }
920}
921
922#[cfg(test)]
923mod request_hash_tests {
924 use super::*;
925
926 #[test]
927 fn serde_round_trips_via_transparent_string() {
928 let r = RequestHash::new("abc123".to_string());
931 let json = serde_json::to_string(&r).unwrap();
932 assert_eq!(json, "\"abc123\"");
933 let back: RequestHash = serde_json::from_str("\"abc123\"").unwrap();
934 assert_eq!(back, r);
935 }
936}
937
938#[cfg(test)]
939mod caller_role_ordering_tests {
940 use super::CallerRole;
941
942 #[test]
943 fn caller_role_orders_least_to_most_privileged() {
944 assert!(CallerRole::Observer < CallerRole::Dev);
947 assert!(CallerRole::Dev < CallerRole::Admin);
948 assert!(CallerRole::Admin < CallerRole::Boot);
949
950 assert!(CallerRole::Admin >= CallerRole::Dev);
952 assert!(!(CallerRole::Observer >= CallerRole::Dev));
953 }
954
955 #[test]
956 fn max_selects_the_higher_privilege() {
957 assert_eq!(
960 CallerRole::Observer.max(CallerRole::Admin),
961 CallerRole::Admin
962 );
963 assert_eq!(CallerRole::Boot.max(CallerRole::Dev), CallerRole::Boot);
964 }
965}
966
967#[cfg(test)]
968mod frame_limit_declaration_tests {
969 use std::fs;
970 use std::path::{Path, PathBuf};
971
972 fn workspace_root() -> PathBuf {
975 let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
976 loop {
977 let manifest = dir.join("Cargo.toml");
978 if manifest.is_file() {
979 if let Ok(text) = fs::read_to_string(&manifest) {
980 if text.contains("[workspace]") {
981 return dir;
982 }
983 }
984 }
985 if !dir.pop() {
986 panic!("could not locate the workspace root");
987 }
988 }
989 }
990
991 fn walk_rs(dir: &Path, out: &mut Vec<PathBuf>) {
993 if let Ok(entries) = fs::read_dir(dir) {
994 for entry in entries.flatten() {
995 let path = entry.path();
996 if path.file_name().is_some_and(|n| n == "target") {
997 continue;
998 }
999 if path.is_dir() {
1000 walk_rs(&path, out);
1001 } else if path.extension().is_some_and(|e| e == "rs") {
1002 out.push(path);
1003 }
1004 }
1005 }
1006 }
1007
1008 #[test]
1029 fn frame_limit_is_declared_once() {
1030 let root = workspace_root();
1031 let mut files: Vec<PathBuf> = Vec::new();
1032 for crate_dir in [
1033 "crates/sysknife-types",
1034 "crates/sysknife-daemon",
1035 "apps/sysknife-cli",
1036 ] {
1037 walk_rs(&root.join(crate_dir), &mut files);
1038 }
1039
1040 let mut declarations: Vec<String> = Vec::new();
1041 for path in &files {
1042 let text = fs::read_to_string(path).unwrap();
1043 for (idx, raw) in text.lines().enumerate() {
1044 let line = raw.trim();
1045 let is_const_decl = [
1046 "const ",
1047 "pub const ",
1048 "pub(crate) const ",
1049 "pub(super) const ",
1050 ]
1051 .iter()
1052 .any(|p| line.starts_with(p));
1053 if is_const_decl && line.contains("4 * 1024 * 1024") {
1056 declarations.push(format!("{}:{}", path.display(), idx + 1));
1057 }
1058 }
1059 }
1060
1061 assert_eq!(
1062 declarations.len(),
1063 1,
1064 "expected exactly one declaration of the 4 MiB frame limit, \
1065 found {}:\n{:#?}",
1066 declarations.len(),
1067 declarations
1068 );
1069 let (decl_path, _line) = declarations[0].rsplit_once(':').unwrap();
1070 let relativized = PathBuf::from(decl_path.replace(&format!("{}/", root.display()), ""));
1071 assert_eq!(
1072 relativized,
1073 Path::new("crates/sysknife-types/src/lib.rs"),
1074 "the single frame-limit declaration must live in sysknife-types"
1075 );
1076 }
1077}