guacamole-client 0.5.1

Rust client library for the Guacamole REST API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use std::collections::HashMap;
use std::fmt;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::client::GuacamoleClient;
use crate::error::Result;
use crate::history::HistoryEntry;
use crate::patch::PatchOperation;
use crate::validation::validate_username;

/// A Guacamole user account.
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct User {
    /// The username.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,

    /// The password (write-only, never returned by the server).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,

    /// Arbitrary user attributes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attributes: Option<HashMap<String, Option<String>>>,
}

impl fmt::Debug for User {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("User")
            .field("username", &self.username)
            .field("password", &"<redacted>")
            .field("attributes", &self.attributes)
            .finish()
    }
}

/// Payload for changing a user's password.
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PasswordChange {
    /// The current password.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub old_password: Option<String>,

    /// The desired new password.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_password: Option<String>,
}

impl fmt::Debug for PasswordChange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PasswordChange")
            .field("old_password", &"<redacted>")
            .field("new_password", &"<redacted>")
            .finish()
    }
}

/// Permissions assigned to a user.
///
/// Uses `serde_json::Value` for forward-compatibility with new permission types.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct UserPermissions {
    /// Per-connection permissions keyed by connection ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection_permissions: Option<HashMap<String, Vec<String>>>,

    /// Per-connection-group permissions keyed by group ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection_group_permissions: Option<HashMap<String, Vec<String>>>,

    /// Per-sharing-profile permissions keyed by sharing profile ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sharing_profile_permissions: Option<HashMap<String, Vec<String>>>,

    /// System-level permissions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_permissions: Option<Vec<String>>,

    /// Per-user permissions keyed by username.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_permissions: Option<HashMap<String, Vec<String>>>,

    /// Any additional permission fields not covered by the known fields.
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

impl GuacamoleClient {
    /// Lists all users in the given data source.
    pub async fn list_users(
        &self,
        data_source: Option<&str>,
    ) -> Result<HashMap<String, User>> {
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!("/api/session/data/{ds}/users"))?;
        let response = self.http.get(&url).send().await?;
        Self::parse_response(response, "users").await
    }

    /// Retrieves a single user by username.
    pub async fn get_user(
        &self,
        data_source: Option<&str>,
        username: &str,
    ) -> Result<User> {
        validate_username(username)?;
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!("/api/session/data/{ds}/users/{username}"))?;
        let response = self.http.get(&url).send().await?;
        Self::parse_response(response, &format!("user {username}")).await
    }

    /// Retrieves the currently authenticated user.
    pub async fn get_self(
        &self,
        data_source: Option<&str>,
    ) -> Result<User> {
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!("/api/session/data/{ds}/self"))?;
        let response = self.http.get(&url).send().await?;
        Self::parse_response(response, "self").await
    }

    /// Creates a new user. Returns `()` on success (204 No Content).
    pub async fn create_user(
        &self,
        data_source: Option<&str>,
        user: &User,
    ) -> Result<()> {
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!("/api/session/data/{ds}/users"))?;
        let response = self.http.post(&url).json(user).send().await?;
        Self::handle_error(response, "create user").await?;
        Ok(())
    }

    /// Updates an existing user. Returns `()` on success (204 No Content).
    pub async fn update_user(
        &self,
        data_source: Option<&str>,
        username: &str,
        user: &User,
    ) -> Result<()> {
        validate_username(username)?;
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!("/api/session/data/{ds}/users/{username}"))?;
        let response = self.http.put(&url).json(user).send().await?;
        Self::handle_error(response, &format!("user {username}")).await?;
        Ok(())
    }

    /// Deletes a user by username. Returns `()` on success (204 No Content).
    pub async fn delete_user(
        &self,
        data_source: Option<&str>,
        username: &str,
    ) -> Result<()> {
        validate_username(username)?;
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!("/api/session/data/{ds}/users/{username}"))?;
        let response = self.http.delete(&url).send().await?;
        Self::handle_error(response, &format!("user {username}")).await?;
        Ok(())
    }

    /// Changes a user's password.
    pub async fn update_user_password(
        &self,
        data_source: Option<&str>,
        username: &str,
        password_change: &PasswordChange,
    ) -> Result<()> {
        validate_username(username)?;
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!(
            "/api/session/data/{ds}/users/{username}/password"
        ))?;
        let response = self.http.put(&url).json(password_change).send().await?;
        Self::handle_error(response, &format!("user {username} password")).await?;
        Ok(())
    }

    /// Retrieves the permissions assigned to a user.
    pub async fn get_user_permissions(
        &self,
        data_source: Option<&str>,
        username: &str,
    ) -> Result<UserPermissions> {
        validate_username(username)?;
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!(
            "/api/session/data/{ds}/users/{username}/permissions"
        ))?;
        let response = self.http.get(&url).send().await?;
        Self::parse_response(response, &format!("user {username} permissions")).await
    }

    /// Retrieves the effective (inherited + direct) permissions for a user.
    pub async fn get_user_effective_permissions(
        &self,
        data_source: Option<&str>,
        username: &str,
    ) -> Result<UserPermissions> {
        validate_username(username)?;
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!(
            "/api/session/data/{ds}/users/{username}/effectivePermissions"
        ))?;
        let response = self.http.get(&url).send().await?;
        Self::parse_response(response, &format!("user {username} effective permissions"))
            .await
    }

    /// Retrieves the groups a user belongs to.
    pub async fn get_user_groups(
        &self,
        data_source: Option<&str>,
        username: &str,
    ) -> Result<Vec<String>> {
        validate_username(username)?;
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!(
            "/api/session/data/{ds}/users/{username}/userGroups"
        ))?;
        let response = self.http.get(&url).send().await?;
        Self::parse_response(response, &format!("user {username} groups")).await
    }

    /// Retrieves the history for a specific user.
    pub async fn get_user_history(
        &self,
        data_source: Option<&str>,
        username: &str,
    ) -> Result<Vec<HistoryEntry>> {
        validate_username(username)?;
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!(
            "/api/session/data/{ds}/users/{username}/history"
        ))?;
        let response = self.http.get(&url).send().await?;
        Self::parse_response(response, &format!("user {username} history")).await
    }

    /// Updates the groups a user belongs to using JSON Patch operations.
    pub async fn update_user_groups(
        &self,
        data_source: Option<&str>,
        username: &str,
        patches: &[PatchOperation],
    ) -> Result<()> {
        validate_username(username)?;
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!(
            "/api/session/data/{ds}/users/{username}/userGroups"
        ))?;
        let response = self.http.patch(&url).json(patches).send().await?;
        Self::handle_error(response, &format!("user {username} groups")).await?;
        Ok(())
    }

    /// Updates the permissions for a user using JSON Patch operations.
    pub async fn update_user_permissions(
        &self,
        data_source: Option<&str>,
        username: &str,
        patches: &[PatchOperation],
    ) -> Result<()> {
        validate_username(username)?;
        let ds = self.resolve_data_source(data_source)?;
        let url = self.url(&format!(
            "/api/session/data/{ds}/users/{username}/permissions"
        ))?;
        let response = self.http.patch(&url).json(patches).send().await?;
        Self::handle_error(response, &format!("user {username} permissions")).await?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn user_serde_roundtrip() {
        let user = User {
            username: Some("guacadmin".to_string()),
            password: Some("secret".to_string()),
            attributes: Some(HashMap::from([(
                "disabled".to_string(),
                Some("false".to_string()),
            )])),
        };
        let json = serde_json::to_string(&user).unwrap();
        let deserialized: User = serde_json::from_str(&json).unwrap();
        assert_eq!(user, deserialized);
    }

    #[test]
    fn user_debug_redacts_password() {
        let user = User {
            username: Some("admin".to_string()),
            password: Some("hunter2".to_string()),
            ..Default::default()
        };
        let debug = format!("{user:?}");
        assert!(!debug.contains("hunter2"), "Debug must not leak password");
        assert!(debug.contains("<redacted>"));
        assert!(debug.contains("admin"));
    }

    #[test]
    fn user_skip_none_fields() {
        let user = User::default();
        let json = serde_json::to_value(&user).unwrap();
        let obj = json.as_object().unwrap();
        assert!(obj.is_empty());
    }

    #[test]
    fn password_change_debug_redacts_both() {
        let pc = PasswordChange {
            old_password: Some("old-secret".to_string()),
            new_password: Some("new-secret".to_string()),
        };
        let debug = format!("{pc:?}");
        assert!(!debug.contains("old-secret"));
        assert!(!debug.contains("new-secret"));
        assert!(debug.contains("<redacted>"));
    }

    #[test]
    fn password_change_serde_roundtrip() {
        let pc = PasswordChange {
            old_password: Some("old".to_string()),
            new_password: Some("new".to_string()),
        };
        let json = serde_json::to_string(&pc).unwrap();
        let deserialized: PasswordChange = serde_json::from_str(&json).unwrap();
        assert_eq!(pc, deserialized);
    }

    #[test]
    fn password_change_camel_case() {
        let pc = PasswordChange {
            old_password: Some("old".to_string()),
            new_password: Some("new".to_string()),
        };
        let json = serde_json::to_value(&pc).unwrap();
        assert!(json.get("oldPassword").is_some());
        assert!(json.get("newPassword").is_some());
    }

    #[test]
    fn user_permissions_serde_roundtrip() {
        let json_str = r#"{
            "connectionPermissions": {"1": ["READ"], "2": ["READ", "UPDATE"]},
            "connectionGroupPermissions": {},
            "sharingProfilePermissions": {"3": ["READ"]},
            "systemPermissions": ["ADMINISTER"],
            "userPermissions": {}
        }"#;
        let perms: UserPermissions = serde_json::from_str(json_str).unwrap();
        assert_eq!(
            perms.system_permissions,
            Some(vec!["ADMINISTER".to_string()])
        );
        assert!(perms.connection_permissions.is_some());

        let conn_perms = perms.connection_permissions.as_ref().unwrap();
        assert_eq!(conn_perms.get("1"), Some(&vec!["READ".to_string()]));
        assert_eq!(
            conn_perms.get("2"),
            Some(&vec!["READ".to_string(), "UPDATE".to_string()])
        );

        let json_roundtrip = serde_json::to_string(&perms).unwrap();
        let deserialized: UserPermissions = serde_json::from_str(&json_roundtrip).unwrap();
        assert_eq!(perms, deserialized);
    }

    #[test]
    fn user_permissions_skip_none_fields() {
        let perms = UserPermissions::default();
        let json = serde_json::to_value(&perms).unwrap();
        let obj = json.as_object().unwrap();
        assert!(obj.is_empty());
    }

    #[test]
    fn deserialize_user_from_api_json() {
        let json = r#"{
            "username": "student",
            "attributes": {
                "disabled": "",
                "expired": "",
                "access-window-start": "",
                "access-window-end": ""
            }
        }"#;
        let user: User = serde_json::from_str(json).unwrap();
        assert_eq!(user.username.as_deref(), Some("student"));
        assert!(user.password.is_none());
        assert!(user.attributes.is_some());
    }

    #[test]
    fn deserialize_user_unknown_fields_ignored() {
        let json = r#"{"username": "test", "unknownField": 42}"#;
        let user: User = serde_json::from_str(json).unwrap();
        assert_eq!(user.username.as_deref(), Some("test"));
    }

    #[test]
    fn user_permissions_extra_captures_unknown_fields() {
        let json = r#"{
            "connectionPermissions": {"1": ["READ"]},
            "customPermissionType": {"x": ["ADMIN"]}
        }"#;
        let perms: UserPermissions = serde_json::from_str(json).unwrap();
        assert!(perms.extra.contains_key("customPermissionType"));
        let custom = perms.extra["customPermissionType"].as_object().unwrap();
        assert_eq!(custom["x"], serde_json::json!(["ADMIN"]));
    }

    #[test]
    fn user_permissions_extra_survives_roundtrip() {
        let json = r#"{
            "connectionPermissions": {"1": ["READ"]},
            "futurePermissions": {"a": ["WRITE"]}
        }"#;
        let perms: UserPermissions = serde_json::from_str(json).unwrap();
        let serialized = serde_json::to_string(&perms).unwrap();
        let deserialized: UserPermissions = serde_json::from_str(&serialized).unwrap();
        assert_eq!(perms, deserialized);
        assert!(deserialized.extra.contains_key("futurePermissions"));
    }

    #[test]
    fn user_null_attribute_values() {
        let json = r#"{
            "username": "admin",
            "attributes": {
                "disabled": "false",
                "expired": null
            }
        }"#;
        let user: User = serde_json::from_str(json).unwrap();
        let attrs = user.attributes.as_ref().unwrap();
        assert_eq!(attrs.get("disabled"), Some(&Some("false".to_string())));
        assert_eq!(attrs.get("expired"), Some(&None));
    }

    #[test]
    fn password_change_skip_none_fields() {
        let pc = PasswordChange::default();
        let json = serde_json::to_value(&pc).unwrap();
        let obj = json.as_object().unwrap();
        assert!(obj.is_empty());
    }

    #[test]
    fn password_change_unknown_fields_ignored() {
        let json = r#"{"oldPassword": "old", "unknownField": true}"#;
        let pc: PasswordChange = serde_json::from_str(json).unwrap();
        assert_eq!(pc.old_password.as_deref(), Some("old"));
    }
}