Skip to main content

security/
authorization.rs

1use bitflags::bitflags;
2use serde_json::Value;
3
4use crate::bridge;
5use crate::error::{Result, SecurityError};
6
7bitflags! {
8    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9    /// Mirrors Authorization Services option bits used with `AuthorizationCreate`.
10    pub struct AuthorizationOptions: u32 {
11        /// Mirrors an Authorization Services option bit.
12        const DEFAULTS = 0;
13        /// Mirrors an Authorization Services option bit.
14        const INTERACTION_ALLOWED = 1 << 0;
15        /// Mirrors an Authorization Services option bit.
16        const EXTEND_RIGHTS = 1 << 1;
17        /// Mirrors an Authorization Services option bit.
18        const PARTIAL_RIGHTS = 1 << 2;
19        /// Mirrors an Authorization Services option bit.
20        const DESTROY_RIGHTS = 1 << 3;
21        /// Mirrors an Authorization Services option bit.
22        const PREAUTHORIZE = 1 << 4;
23        /// Mirrors an Authorization Services option bit.
24        const SKIP_INTERNAL_AUTH = 1 << 9;
25        /// Mirrors an Authorization Services option bit.
26        const NO_DATA = 1 << 20;
27    }
28}
29
30#[derive(Debug)]
31/// Wraps `AuthorizationRef`.
32pub struct Authorization {
33    handle: bridge::Handle,
34}
35
36impl Authorization {
37    #[cfg(feature = "async")]
38    pub(crate) fn as_ptr(&self) -> *mut std::ffi::c_void {
39        self.handle.as_ptr()
40    }
41
42    /// Wraps the corresponding Authorization Services operation for `AuthorizationRef`.
43    pub fn new() -> Result<Self> {
44        Self::with_options(AuthorizationOptions::DEFAULTS)
45    }
46
47    /// Wraps the corresponding Authorization Services operation for `AuthorizationRef`.
48    pub fn with_options(options: AuthorizationOptions) -> Result<Self> {
49        let mut status = 0;
50        let mut error = std::ptr::null_mut();
51        let raw = unsafe {
52            bridge::security_authorization_create(options.bits(), &raw mut status, &raw mut error)
53        };
54        bridge::required_handle("security_authorization_create", raw, status, error)
55            .map(|handle| Self { handle })
56    }
57
58    pub fn set_destroy_rights_on_drop(&mut self, destroy_rights: bool) {
59        unsafe {
60            bridge::security_authorization_set_destroy_rights(self.handle.as_ptr(), destroy_rights);
61        }
62    }
63
64    /// Wraps the corresponding Authorization Services operation for `AuthorizationRef`.
65    pub fn external_form(&self) -> Result<Vec<u8>> {
66        let mut status = 0;
67        let mut error = std::ptr::null_mut();
68        let raw = unsafe {
69            bridge::security_authorization_make_external_form(
70                self.handle.as_ptr(),
71                &raw mut status,
72                &raw mut error,
73            )
74        };
75        bridge::required_data(
76            "security_authorization_make_external_form",
77            raw,
78            status,
79            error,
80        )
81    }
82
83    /// Wraps the corresponding Authorization Services operation for `AuthorizationRef`.
84    pub fn from_external_form(external_form: &[u8]) -> Result<Self> {
85        let mut status = 0;
86        let mut error = std::ptr::null_mut();
87        let raw = unsafe {
88            bridge::security_authorization_create_from_external_form(
89                external_form.as_ptr().cast(),
90                bridge::len_to_isize(external_form.len())?,
91                &raw mut status,
92                &raw mut error,
93            )
94        };
95        bridge::required_handle(
96            "security_authorization_create_from_external_form",
97            raw,
98            status,
99            error,
100        )
101        .map(|handle| Self { handle })
102    }
103
104    /// Wraps the corresponding Authorization Services operation for `AuthorizationRef`.
105    pub fn copy_info(&self, tag: Option<&str>) -> Result<Value> {
106        let tag = tag.map(bridge::cstring).transpose()?;
107        let mut status = 0;
108        let mut error = std::ptr::null_mut();
109        let raw = unsafe {
110            bridge::security_authorization_copy_info(
111                self.handle.as_ptr(),
112                tag.as_ref()
113                    .map_or(std::ptr::null(), |value| value.as_ptr()),
114                &raw mut status,
115                &raw mut error,
116            )
117        };
118        bridge::required_json("security_authorization_copy_info", raw, status, error)
119    }
120
121    /// Wraps the corresponding Authorization Services operation for `AuthorizationRef`.
122    pub fn copy_rights(&self, rights: &[&str], options: AuthorizationOptions) -> Result<Value> {
123        let rights_json = rights_json(rights)?;
124        let mut status = 0;
125        let mut error = std::ptr::null_mut();
126        let raw = unsafe {
127            bridge::security_authorization_copy_rights(
128                self.handle.as_ptr(),
129                rights_json.as_ptr(),
130                options.bits(),
131                &raw mut status,
132                &raw mut error,
133            )
134        };
135        bridge::required_json("security_authorization_copy_rights", raw, status, error)
136    }
137
138    /// Wraps the corresponding Authorization Services operation for `AuthorizationRef`.
139    pub fn copy_rights_async(
140        &self,
141        rights: &[&str],
142        options: AuthorizationOptions,
143    ) -> Result<Value> {
144        let rights_json = rights_json(rights)?;
145        let mut status = 0;
146        let mut error = std::ptr::null_mut();
147        let raw = unsafe {
148            bridge::security_authorization_copy_rights_async(
149                self.handle.as_ptr(),
150                rights_json.as_ptr(),
151                options.bits(),
152                &raw mut status,
153                &raw mut error,
154            )
155        };
156        bridge::required_json(
157            "security_authorization_copy_rights_async",
158            raw,
159            status,
160            error,
161        )
162    }
163}
164
165pub(crate) fn rights_json(rights: &[&str]) -> Result<std::ffi::CString> {
166    if rights.is_empty() {
167        return Err(SecurityError::InvalidArgument(
168            "at least one authorization right is required".to_owned(),
169        ));
170    }
171    if rights
172        .iter()
173        .any(|right| right.is_empty() || right.contains('\0'))
174    {
175        return Err(SecurityError::InvalidArgument(
176            "authorization right names must be non-empty and free of NUL bytes".to_owned(),
177        ));
178    }
179    bridge::json_cstring(&rights)
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    #[test]
187    fn rights_json_rejects_empty_and_nul_names() {
188        assert!(rights_json(&[]).is_err());
189        assert!(rights_json(&[""]).is_err());
190        assert!(rights_json(&["system.privilege.admin\0other"]).is_err());
191        assert_eq!(
192            rights_json(&["system.preferences"])
193                .unwrap()
194                .to_str()
195                .unwrap(),
196            r#"["system.preferences"]"#
197        );
198    }
199
200    #[test]
201    fn defaults_are_empty() {
202        assert!(AuthorizationOptions::DEFAULTS.is_empty());
203        assert_eq!(AuthorizationOptions::DEFAULTS.bits(), 0);
204    }
205
206    #[test]
207    fn authorization_options_round_trip_through_bits() {
208        let options = AuthorizationOptions::INTERACTION_ALLOWED
209            | AuthorizationOptions::EXTEND_RIGHTS
210            | AuthorizationOptions::PREAUTHORIZE;
211
212        assert_eq!(
213            AuthorizationOptions::from_bits(options.bits()),
214            Some(options)
215        );
216    }
217
218    #[test]
219    fn authorization_options_keep_sparse_bits() {
220        let options = AuthorizationOptions::SKIP_INTERNAL_AUTH | AuthorizationOptions::NO_DATA;
221
222        assert!(options.contains(AuthorizationOptions::SKIP_INTERNAL_AUTH));
223        assert!(options.contains(AuthorizationOptions::NO_DATA));
224        assert_eq!(options.bits(), (1 << 9) | (1 << 20));
225    }
226}