psrp-rs 1.0.0

Async PowerShell Remoting Protocol (MS-PSRP) client for Rust, built on winrm-rs.
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
//! `Get-Command` metadata pipeline — a special kind of PSRP pipeline
//! that asks the server which commands are available.
//!
//! The server uses this to implement implicit remoting (`Import-PSSession`).
//! Unlike a normal `CreatePipeline`, the body is a `GetCommandMetadata`
//! message (`0x0002_100A`) that carries a list of name patterns and the
//! command types to return.

use uuid::Uuid;

use crate::clixml::{PsObject, PsValue, parse_clixml, to_clixml};
use crate::error::{PsrpError, Result};
use crate::message::MessageType;
use crate::pipeline::PipelineState;
use crate::runspace::RunspacePool;
use crate::transport::PsrpTransport;

/// Bitmask of command types to query, mirroring
/// `System.Management.Automation.CommandTypes`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommandType(u32);

impl CommandType {
    pub const ALIAS: Self = Self(0x0001);
    pub const FUNCTION: Self = Self(0x0002);
    pub const FILTER: Self = Self(0x0004);
    pub const CMDLET: Self = Self(0x0008);
    pub const EXTERNAL_SCRIPT: Self = Self(0x0010);
    pub const APPLICATION: Self = Self(0x0020);
    pub const SCRIPT: Self = Self(0x0040);
    pub const WORKFLOW: Self = Self(0x0080);
    pub const CONFIGURATION: Self = Self(0x0100);
    pub const ALL: Self = Self(0x01FF);

    #[must_use]
    pub const fn empty() -> Self {
        Self(0)
    }
    #[must_use]
    pub const fn bits(self) -> u32 {
        self.0
    }
    #[must_use]
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }
}

impl std::ops::BitOr for CommandType {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self::Output {
        Self(self.0 | rhs.0)
    }
}

impl std::ops::BitAnd for CommandType {
    type Output = Self;
    fn bitand(self, rhs: Self) -> Self::Output {
        Self(self.0 & rhs.0)
    }
}

/// Describe one command returned by a metadata query.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct CommandMetadata {
    pub name: String,
    pub namespace: Option<String>,
    pub has_common_parameters: Option<bool>,
    pub command_type: Option<i32>,
    pub parameters: Vec<ParameterMetadata>,
}

/// One parameter of a [`CommandMetadata`] entry.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ParameterMetadata {
    pub name: String,
    pub parameter_type: Option<String>,
    pub is_mandatory: Option<bool>,
    pub position: Option<i32>,
}

impl CommandMetadata {
    fn from_ps_object(value: &PsValue) -> Option<Self> {
        let obj = value.properties()?;
        Some(Self {
            name: obj
                .get("Name")
                .and_then(PsValue::as_str)
                .unwrap_or_default()
                .to_string(),
            namespace: obj
                .get("Namespace")
                .and_then(PsValue::as_str)
                .map(str::to_string),
            has_common_parameters: obj.get("HasCommonParameters").and_then(PsValue::as_bool),
            command_type: obj.get("CommandType").and_then(PsValue::as_i32),
            parameters: match obj.get("Parameters") {
                Some(PsValue::List(list)) => list
                    .iter()
                    .filter_map(ParameterMetadata::from_ps_value)
                    .collect(),
                _ => Vec::new(),
            },
        })
    }
}

impl ParameterMetadata {
    fn from_ps_value(value: &PsValue) -> Option<Self> {
        let obj = value.properties()?;
        Some(Self {
            name: obj
                .get("Name")
                .and_then(PsValue::as_str)
                .unwrap_or_default()
                .to_string(),
            parameter_type: obj
                .get("ParameterType")
                .and_then(PsValue::as_str)
                .map(str::to_string),
            is_mandatory: obj.get("IsMandatory").and_then(PsValue::as_bool),
            position: obj.get("Position").and_then(PsValue::as_i32),
        })
    }
}

impl<T: PsrpTransport> RunspacePool<T> {
    /// Ask the server for metadata about every command matching `patterns`
    /// (wildcards accepted) whose type intersects `command_type`.
    ///
    /// Sends a `GetCommandMetadata` message, drains the resulting
    /// pipeline, and returns a decoded [`CommandMetadata`] list.
    pub async fn get_command_metadata(
        &mut self,
        patterns: &[&str],
        command_type: CommandType,
    ) -> Result<Vec<CommandMetadata>> {
        let pid = Uuid::new_v4();
        let body = build_get_command_metadata_body(patterns, command_type);
        self.send_pipeline_message(MessageType::GetCommandMetadata, pid, body)
            .await?;

        let mut out = Vec::new();
        loop {
            let msg = self.next_message().await?;
            match msg.message_type {
                MessageType::PipelineOutput => {
                    for v in parse_clixml(&msg.data)? {
                        if let Some(cm) = CommandMetadata::from_ps_object(&v) {
                            out.push(cm);
                        }
                    }
                }
                MessageType::PipelineState => {
                    if let Some(state) = state_from_xml(&msg.data) {
                        if state.is_terminal() {
                            if state == PipelineState::Failed {
                                return Err(PsrpError::PipelineFailed(
                                    "GetCommandMetadata pipeline failed".into(),
                                ));
                            }
                            return Ok(out);
                        }
                    }
                }
                _ => continue,
            }
        }
    }
}

fn state_from_xml(xml: &str) -> Option<PipelineState> {
    parse_clixml(xml).ok().and_then(|values| {
        values.into_iter().find_map(|v| match v {
            PsValue::Object(obj) => obj
                .get("PipelineState")
                .and_then(PsValue::as_i32)
                .map(pipeline_state_from_i32),
            _ => None,
        })
    })
}

fn pipeline_state_from_i32(v: i32) -> PipelineState {
    // Mirror pipeline::PipelineState::from_i32 without exposing it.
    match v {
        0 => PipelineState::NotStarted,
        1 => PipelineState::Running,
        2 => PipelineState::Stopping,
        3 => PipelineState::Stopped,
        4 => PipelineState::Completed,
        5 => PipelineState::Failed,
        6 => PipelineState::Disconnected,
        _ => PipelineState::Unknown,
    }
}

fn build_get_command_metadata_body(patterns: &[&str], command_type: CommandType) -> String {
    let names = PsValue::List(
        patterns
            .iter()
            .map(|p| PsValue::String((*p).to_string()))
            .collect(),
    );
    let obj = PsObject::new()
        .with("Name", names)
        .with("CommandType", PsValue::I32(command_type.bits() as i32))
        .with("Namespace", PsValue::List(Vec::new()))
        .with("ArgumentList", PsValue::List(Vec::new()));
    to_clixml(&PsValue::Object(obj))
}

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

    #[test]
    fn command_type_constants() {
        assert_eq!(CommandType::CMDLET.bits(), 0x0008);
        assert_eq!(CommandType::ALL.bits(), 0x01FF);
        let combo = CommandType::CMDLET | CommandType::FUNCTION;
        assert!(combo.contains(CommandType::CMDLET));
        assert!(combo.contains(CommandType::FUNCTION));
        assert!(!combo.contains(CommandType::ALIAS));
    }

    #[test]
    fn get_command_metadata_body_contains_name_and_type() {
        let body = build_get_command_metadata_body(&["Get-*", "Set-*"], CommandType::CMDLET);
        assert!(body.contains("<S>Get-*</S>"));
        assert!(body.contains("<S>Set-*</S>"));
        // CommandType::CMDLET = 0x0008 = 8
        assert!(body.contains("<I32 N=\"CommandType\">8</I32>"));
    }

    #[test]
    fn decode_command_metadata_object() {
        let obj = PsObject::new()
            .with("Name", PsValue::String("Get-Date".into()))
            .with("HasCommonParameters", PsValue::Bool(true))
            .with("CommandType", PsValue::I32(8))
            .with(
                "Parameters",
                PsValue::List(vec![PsValue::Object(
                    PsObject::new()
                        .with("Name", PsValue::String("Format".into()))
                        .with("ParameterType", PsValue::String("System.String".into()))
                        .with("IsMandatory", PsValue::Bool(false))
                        .with("Position", PsValue::I32(0)),
                )]),
            );
        let cm = CommandMetadata::from_ps_object(&PsValue::Object(obj)).unwrap();
        assert_eq!(cm.name, "Get-Date");
        assert_eq!(cm.has_common_parameters, Some(true));
        assert_eq!(cm.command_type, Some(8));
        assert_eq!(cm.parameters.len(), 1);
        assert_eq!(cm.parameters[0].name, "Format");
        assert_eq!(
            cm.parameters[0].parameter_type.as_deref(),
            Some("System.String")
        );
    }

    #[test]
    fn decode_rejects_non_object() {
        assert!(CommandMetadata::from_ps_object(&PsValue::I32(1)).is_none());
    }

    #[test]
    fn pipeline_state_shim_matches() {
        assert_eq!(pipeline_state_from_i32(0), PipelineState::NotStarted);
        assert_eq!(pipeline_state_from_i32(1), PipelineState::Running);
        assert_eq!(pipeline_state_from_i32(2), PipelineState::Stopping);
        assert_eq!(pipeline_state_from_i32(3), PipelineState::Stopped);
        assert_eq!(pipeline_state_from_i32(4), PipelineState::Completed);
        assert_eq!(pipeline_state_from_i32(5), PipelineState::Failed);
        assert_eq!(pipeline_state_from_i32(6), PipelineState::Disconnected);
        assert_eq!(pipeline_state_from_i32(99), PipelineState::Unknown);
    }

    #[test]
    fn state_from_xml_missing_is_none() {
        assert!(state_from_xml("<Obj RefId=\"0\"><MS/></Obj>").is_none());
    }

    #[test]
    fn state_from_xml_ok() {
        let xml = to_clixml(&PsValue::Object(
            PsObject::new().with("PipelineState", PsValue::I32(4)),
        ));
        assert_eq!(state_from_xml(&xml), Some(PipelineState::Completed));
    }

    // ---------- Phase D: end-to-end tests ----------

    use crate::fragment::encode_message;
    use crate::message::{Destination, PsrpMessage};
    use crate::runspace::RunspacePoolState;
    use crate::transport::mock::MockTransport;
    use uuid::Uuid;

    fn wire_msg(mt: MessageType, data: String) -> Vec<u8> {
        PsrpMessage {
            destination: Destination::Client,
            message_type: mt,
            rpid: Uuid::nil(),
            pid: Uuid::nil(),
            data,
        }
        .encode()
    }

    fn opened_state() -> Vec<u8> {
        wire_msg(
            MessageType::RunspacePoolState,
            to_clixml(&PsValue::Object(PsObject::new().with(
                "RunspaceState",
                PsValue::I32(RunspacePoolState::Opened as i32),
            ))),
        )
    }

    fn pipeline_state(state: PipelineState) -> Vec<u8> {
        wire_msg(
            MessageType::PipelineState,
            to_clixml(&PsValue::Object(
                PsObject::new().with("PipelineState", PsValue::I32(state as i32)),
            )),
        )
    }

    #[tokio::test]
    async fn get_command_metadata_returns_items() {
        let t = MockTransport::new();
        t.push_incoming(encode_message(1, &opened_state()));

        // Two cmdlets emitted as PipelineOutput.
        let cmd = |name: &str| {
            to_clixml(&PsValue::Object(
                PsObject::new()
                    .with("Name", PsValue::String(name.into()))
                    .with("CommandType", PsValue::I32(8)),
            ))
        };
        t.push_incoming(encode_message(
            10,
            &wire_msg(MessageType::PipelineOutput, cmd("Get-Date")),
        ));
        t.push_incoming(encode_message(
            11,
            &wire_msg(MessageType::PipelineOutput, cmd("Get-Process")),
        ));
        t.push_incoming(encode_message(
            12,
            &pipeline_state(PipelineState::Completed),
        ));

        let mut pool = crate::runspace::RunspacePool::open_with_transport(t.clone())
            .await
            .unwrap();
        let cmds = pool
            .get_command_metadata(&["Get-*"], CommandType::CMDLET)
            .await
            .unwrap();
        assert_eq!(cmds.len(), 2);
        assert_eq!(cmds[0].name, "Get-Date");
        assert_eq!(cmds[1].name, "Get-Process");
        let _ = pool.close().await;
    }

    #[tokio::test]
    async fn get_command_metadata_failed_pipeline_errors() {
        let t = MockTransport::new();
        t.push_incoming(encode_message(1, &opened_state()));
        t.push_incoming(encode_message(10, &pipeline_state(PipelineState::Failed)));
        let mut pool = crate::runspace::RunspacePool::open_with_transport(t)
            .await
            .unwrap();
        let err = pool
            .get_command_metadata(&["Nothing"], CommandType::ALL)
            .await
            .unwrap_err();
        assert!(matches!(err, crate::error::PsrpError::PipelineFailed(_)));
        let _ = pool.close().await;
    }

    #[tokio::test]
    async fn get_command_metadata_empty_result() {
        let t = MockTransport::new();
        t.push_incoming(encode_message(1, &opened_state()));
        t.push_incoming(encode_message(
            10,
            &pipeline_state(PipelineState::Completed),
        ));
        let mut pool = crate::runspace::RunspacePool::open_with_transport(t)
            .await
            .unwrap();
        let cmds = pool
            .get_command_metadata(&["None-*"], CommandType::CMDLET)
            .await
            .unwrap();
        assert!(cmds.is_empty());
        let _ = pool.close().await;
    }

    #[test]
    fn command_type_bit_and() {
        let mask = CommandType::ALL & CommandType::CMDLET;
        assert_eq!(mask.bits(), CommandType::CMDLET.bits());
        let empty = CommandType::empty();
        assert_eq!(empty.bits(), 0);
    }

    #[test]
    fn command_type_bit_or() {
        let combined = CommandType::CMDLET | CommandType::FUNCTION;
        assert!(combined.contains(CommandType::CMDLET));
        assert!(combined.contains(CommandType::FUNCTION));
        assert!(!combined.contains(CommandType::ALIAS));
        // Verify OR produces the correct bits (not XOR)
        assert_eq!(
            combined.bits(),
            CommandType::CMDLET.bits() | CommandType::FUNCTION.bits()
        );
        // OR with self should be idempotent (XOR would zero it out)
        let double = CommandType::CMDLET | CommandType::CMDLET;
        assert!(double.contains(CommandType::CMDLET));
        assert_eq!(double.bits(), CommandType::CMDLET.bits());
    }
}