wstep-rs 0.1.3

Implementation of the [MS-WSTEP] WS-Trust X.509v3 Token Enrollment Extensions protocol
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
#![allow(clippy::module_name_repetitions)]

use std::{borrow::Cow, str::FromStr};

use serde::Serialize;

use crate::common::{ActionType, BinarySecurityToken, Header, RequestId, TokenType};

/// Represents a WS-Trust X.509v3 Token Enrollment Extensions (WSTEP) request.
///
/// This struct encapsulates the details of a WSTEP request, including the SOAP envelope
/// and its contents as defined in the MS-WSTEP specification.
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(clippy::module_name_repetitions)]
pub struct WstepRequest<'a> {
    /// Contains the SOAP envelope response elements for a WSTEP request.
    pub request_envelope: RequestEnvelope<'a>,
}

impl<'a> WstepRequest<'a> {
    /// The "anonymous" URI for the WS-Addressing `ReplyTo` field.
    pub const REPLY_TO_ANONYMOUS: &'static str = "http://www.w3.org/2005/08/addressing/anonymous";

    /// The content type for SOAP messages in WSTEP.
    pub const SOAP_CONTENT_TYPE: &'static str = "application/soap+xml; charset=utf-8";

    /// Creates a new [`WstepRequest`] for issuing an X.509v3 certificate.
    ///
    /// This method constructs a request for a new certificate using the PKCS#7 CMS format.
    ///
    /// # Arguments
    ///
    /// * `request_pkcs7_cms_base64` - The base64-encoded PKCS#7 CMS request.
    /// * `message_id` - A unique identifier for the message.
    /// * `to` - The recipient's address.
    ///
    /// # Returns
    ///
    /// A new [`WstepRequest`] instance configured for issuing an X.509v3 certificate.
    #[must_use]
    pub fn new_issue_x509v3(
        request_pkcs7_cms_base64: &'a str,
        message_id: &'a str,
        to: Option<&'a str>,
        reply_to: Option<&'a str>,
    ) -> Self {
        Self {
            request_envelope: RequestEnvelope::new_issue_x509v3(
                Header::new_request_header(
                    ActionType::RequestSecurityToken,
                    message_id,
                    to,
                    reply_to,
                ),
                BinarySecurityToken::new_pkcs7_base64(request_pkcs7_cms_base64),
            ),
        }
    }

    /// Creates a new [`WstepRequest`] for a Key Exchange Token (KET) request.
    ///
    /// This method constructs a request for a Key Exchange Token as defined in the MS-WSTEP specification.
    ///
    /// # Arguments
    ///
    /// * `message_id` - A unique identifier for the message.
    /// * `reply_to` - The address to which the response should be sent.
    ///
    /// # Returns
    ///
    /// A new [`WstepRequest`] instance configured for a Key Exchange Token request.
    #[must_use]
    pub fn new_key_exchange_token(message_id: &'a str, reply_to: &'a str) -> Self {
        Self {
            request_envelope: RequestEnvelope::new_key_exchange_token(message_id, reply_to),
        }
    }

    /// Creates a new [`WstepRequest`] for querying the status of a token.
    ///
    /// This method constructs a request to check the status of a previously submitted certificate request.
    ///
    /// # Arguments
    ///
    /// * `request_id` - The identifier of the original certificate request.
    /// * `message_id` - A unique identifier for this status query message.
    /// * `reply_to` - The address to which the response should be sent.
    ///
    /// # Returns
    ///
    /// A new [`WstepRequest`] instance configured for querying token status.
    #[must_use]
    pub fn new_query_token_status(
        request_id: &'a str,
        message_id: &'a str,
        reply_to: &'a str,
    ) -> Self {
        Self {
            request_envelope: RequestEnvelope::new_query_token_status(
                request_id, message_id, reply_to,
            ),
        }
    }

    /// Serializes the [`WstepRequest`] into a SOAP XML string.
    ///
    /// This method converts the request into a properly formatted SOAP envelope
    /// as required by the MS-WSTEP specification.
    ///
    /// # Returns
    /// A [`Result`] containing the serialized XML string.
    ///
    /// # Errors
    /// Returns a [`WstepRequestSerializationError`] if serialization fails.
    pub fn serialize_request(&self) -> Result<String, WstepRequestSerializationError> {
        quick_xml::se::to_string_with_root("s:Envelope", &self.request_envelope)
            .map_err(WstepRequestSerializationError)
    }
}

/// Error that occurs when serializing a WSTEP request fails.
#[derive(Debug, Clone)]
pub struct WstepRequestSerializationError(quick_xml::SeError);

impl std::fmt::Display for WstepRequestSerializationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "failed to serialize MS-WSTEP request: {0}", self.0)
    }
}

impl std::error::Error for WstepRequestSerializationError {}

/// The SOAP envelope for a WSTEP request.
///
/// This structure represents the complete SOAP envelope for a WSTEP request,
/// including the header and body sections as defined in the MS-WSTEP protocol.
#[derive(Debug, Serialize, PartialEq, Eq, Clone)]
#[serde(rename = "s:Envelope")]
pub struct RequestEnvelope<'a> {
    /// The XML namespace for WS-Addressing.
    #[serde(rename = "@xmlns:a")]
    pub xmlns_a: Cow<'a, str>,

    /// The XML namespace for SOAP.
    #[serde(rename = "@xmlns:s")]
    pub xmlns_s: Cow<'a, str>,

    /// The SOAP header containing addressing and message metadata.
    #[serde(rename = "s:Header")]
    #[serde(alias = "Header")]
    pub header: Header<'a>,

    /// The SOAP body containing the actual request payload.
    #[serde(rename = "s:Body")]
    #[serde(alias = "Body")]
    pub body: RequestBody<'a>,
}

impl<'a> RequestEnvelope<'a> {
    /// The XML namespace for WS-Addressing.
    const XMLNS_A: &'static str = "http://www.w3.org/2005/08/addressing";

    /// The XML namespace for SOAP.
    const XMLNS_S: &'static str = "http://www.w3.org/2003/05/soap-envelope";

    /// Creates a new request envelope for issuing an X.509v3 certificate.
    ///
    /// # Arguments
    ///
    /// * `header` - The SOAP header containing addressing information.
    /// * `binary_security_token` - Token containing the certificate request.
    ///
    /// # Returns
    ///
    /// A new [`RequestEnvelope`] configured for a certificate issuance
    /// request.
    #[must_use]
    pub fn new_issue_x509v3(
        header: Header<'a>,
        binary_security_token: BinarySecurityToken<'a>,
    ) -> Self {
        Self {
            xmlns_a: Self::XMLNS_A.into(),
            xmlns_s: Self::XMLNS_S.into(),
            header,
            body: RequestBody::new_issue_x509v3(binary_security_token),
        }
    }

    /// Creates a new request envelope for a Key Exchange Token request.
    ///
    /// # Arguments
    ///
    /// * `message_id` - A unique identifier for this message.
    /// * `reply_to` - The address to which the response should be sent.
    ///
    /// # Returns
    ///
    /// A new [`RequestEnvelope`] configured for a Key Exchange Token request.
    #[must_use]
    pub fn new_key_exchange_token(message_id: &'a str, reply_to: &'a str) -> Self {
        Self {
            xmlns_a: Self::XMLNS_A.into(),
            xmlns_s: Self::XMLNS_S.into(),
            header: Header::new_request_header(
                ActionType::KeyExchangeToken,
                message_id,
                None,
                Some(reply_to),
            ),
            body: RequestBody::new_key_exchange_token(),
        }
    }

    /// Creates a new request envelope for querying token status.
    ///
    /// # Arguments
    ///
    /// * `request_id` - The identifier of the original certificate request.
    /// * `message_id` - A unique identifier for this message.
    /// * `reply_to` - The address to which the response should be sent.
    ///
    /// # Returns
    ///
    /// A new `RequestEnvelope` configured for querying token status.
    #[must_use]
    pub fn new_query_token_status(
        request_id: &'a str,
        message_id: &'a str,
        reply_to: &'a str,
    ) -> Self {
        Self {
            xmlns_a: Self::XMLNS_A.into(),
            xmlns_s: Self::XMLNS_S.into(),
            header: Header::new_request_header(
                ActionType::RequestSecurityToken,
                message_id,
                None,
                Some(reply_to),
            ),
            body: RequestBody::new_query_token_status(request_id),
        }
    }
}

/// The body section of a WSTEP SOAP request.
///
/// This structure contains the payload of the WSTEP request, primarily
/// the [`RequestSecurityToken`] element that specifies the certificate
/// operation.
#[derive(Debug, Serialize, PartialEq, Eq, Clone)]
pub struct RequestBody<'a> {
    /// The XML namespace for XML Schema Instance.
    #[serde(rename = "@xmlns:xsi")]
    pub xmlns_xsi: Cow<'a, str>,

    /// The XML namespace for XML Schema.
    #[serde(rename = "@xmlns:xsd")]
    pub xmlns_xsd: Cow<'a, str>,

    /// The main request element containing the certificate operation details.
    #[serde(rename = "RequestSecurityToken")]
    pub request_security_token: RequestSecurityToken<'a>,
}

impl<'a> RequestBody<'a> {
    /// The XML namespace for XML Schema Instance.
    const XMLNS_XSI: &'static str = "http://www.w3.org/2001/XMLSchema-instance";

    /// The XML namespace for XML Schema.
    const XMLNS_XSD: &'static str = "http://www.w3.org/2001/XMLSchema";

    /// Creates a new request body for issuing an X.509v3 certificate.
    ///
    /// # Arguments
    ///
    /// * `binary_security_token` - Token containing the certificate request.
    ///
    /// # Returns
    ///
    /// A new `RequestBody` configured for a certificate issuance request.
    #[must_use]
    pub fn new_issue_x509v3(binary_security_token: BinarySecurityToken<'a>) -> Self {
        Self {
            xmlns_xsi: Self::XMLNS_XSI.into(),
            xmlns_xsd: Self::XMLNS_XSD.into(),
            request_security_token: RequestSecurityToken::new_issue_x509v3(binary_security_token),
        }
    }

    /// Creates a new request body for a Key Exchange Token request.
    ///
    /// # Returns
    ///
    /// A new `RequestBody` configured for a Key Exchange Token request.
    #[must_use]
    pub fn new_key_exchange_token() -> Self {
        Self {
            xmlns_xsi: Self::XMLNS_XSI.into(),
            xmlns_xsd: Self::XMLNS_XSD.into(),
            request_security_token: RequestSecurityToken::new_key_exchange_token(),
        }
    }

    /// Creates a new request body for querying token status.
    ///
    /// # Arguments
    ///
    /// * `request_id` - The identifier of the original certificate request.
    ///
    /// # Returns
    ///
    /// A new `RequestBody` configured for querying token status.
    #[must_use]
    pub fn new_query_token_status(request_id: &'a str) -> Self {
        Self {
            xmlns_xsi: Self::XMLNS_XSI.into(),
            xmlns_xsd: Self::XMLNS_XSD.into(),
            request_security_token: RequestSecurityToken::new_query_token_status(request_id),
        }
    }
}

/// A `RequestSecurityToken` as defined by MS-WSTEP.
///
/// MS-WSTEP defines the content model for this element as non-deterministic.
/// Thus, this enumeration represents the intended content model as documented
/// in section 3.1.4.1.3.3 of MS-WSTEP.
#[derive(Debug, Serialize, PartialEq, Eq, Clone)]
pub struct RequestSecurityToken<'a> {
    /// The XML namespace for WS-Trust.
    #[serde(rename = "@xmlns")]
    pub xmlns: Cow<'a, str>,

    /// The type of token being requested, always X.509v3 in WSTEP.
    #[serde(rename = "TokenType")]
    pub token_type: TokenType<'a>,

    /// The type of request being made, e.g. `Issue`, `QueryTokenStatus`, or
    /// `KeyExchangeToken`.
    #[serde(rename = "RequestType")]
    pub request_type: RequestType,

    /// The binary security token containing the certificate request,
    /// if applicable.
    #[serde(
        rename = "BinarySecurityToken",
        skip_serializing_if = "Option::is_none"
    )]
    pub binary_security_token: Option<BinarySecurityToken<'a>>,

    /// Flag indicating this is a Key Exchange Token request, if applicable.
    #[serde(rename = "RequestKET", skip_serializing_if = "Option::is_none")]
    pub request_ket: Option<()>,

    /// The request identifier, used in status queries or left empty for new
    /// requests.
    #[serde(rename = "RequestID")]
    pub request_id: RequestId<'a>,
}

impl<'a> RequestSecurityToken<'a> {
    /// The XML namespace for WS-Trust.
    const XMLNS: &'static str = "http://docs.oasis-open.org/ws-sx/ws-trust/200512";

    /// Create a new request security token for issuing an X.509v3 certificate.
    ///
    /// # Arguments
    ///
    /// * `binary_security_token` - Token containing the certificate request.
    ///
    /// # Returns
    ///
    /// A new [`RequestSecurityToken`] configured for a certificate issuance
    /// request.
    #[must_use]
    pub fn new_issue_x509v3(binary_security_token: BinarySecurityToken<'a>) -> Self {
        Self {
            xmlns: Self::XMLNS.into(),
            token_type: TokenType::x509v3(),
            request_type: RequestType::Issue,
            binary_security_token: Some(binary_security_token),
            request_ket: None,
            request_id: RequestId::nil(),
        }
    }

    /// Creates a new request security token for a Key Exchange Token request.
    ///
    /// # Returns
    ///
    /// A new [`RequestSecurityToken`] configured for a Key Exchange Token
    /// request.
    #[must_use]
    pub fn new_key_exchange_token() -> Self {
        Self {
            xmlns: Self::XMLNS.into(),
            token_type: TokenType::x509v3(),
            request_type: RequestType::KeyExchangeToken,
            binary_security_token: None,
            request_ket: Some(()),
            request_id: RequestId::nil(),
        }
    }

    /// Creates a new request security token for querying token status.
    ///
    /// # Arguments
    ///
    /// * `request_id` - The identifier of the original certificate request.
    ///
    /// # Returns
    ///
    /// A new [`RequestSecurityToken`] configured for querying token status.
    #[must_use]
    pub fn new_query_token_status(request_id: &'a str) -> Self {
        Self {
            xmlns: Self::XMLNS.into(),
            token_type: TokenType::x509v3(),
            request_type: RequestType::QueryTokenStatus,
            binary_security_token: None,
            request_ket: None,
            request_id: RequestId::new_with_id(request_id),
        }
    }
}

/// A `RequestType` as defined by section 3.1 of WSTrust1.3, subject to the
/// constraints defined by section 3.1.4.1.2.7 of MS-WSTEP.
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum RequestType {
    /// Request a new certificate to be issued.
    Issue,
    /// Query the status of a previously submitted certificate request.
    QueryTokenStatus,
    /// Request a Key Exchange Token from the server.
    KeyExchangeToken,
}

impl RequestType {
    /// The URI for the `Issue` request type.
    const RT_ISSUE: &str = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue";

    /// The URI for the `QueryTokenStatus` request type.
    const RT_QUERY_TOKEN_STATUS: &str =
        "http://schemas.microsoft.com/windows/pki/2009/01/enrollment/QueryTokenStatus";

    /// The URI for the `KeyExchangeToken` request type.
    const RT_KEY_EXCHANGE_TOKEN: &str = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/KET";
}

impl Serialize for RequestType {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str((*self).into())
    }
}

impl From<RequestType> for &'static str {
    fn from(value: RequestType) -> Self {
        match value {
            RequestType::Issue => RequestType::RT_ISSUE,
            RequestType::QueryTokenStatus => RequestType::RT_QUERY_TOKEN_STATUS,
            RequestType::KeyExchangeToken => RequestType::RT_KEY_EXCHANGE_TOKEN,
        }
    }
}

impl FromStr for RequestType {
    type Err = RequestTypeParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let request_type = match s {
            Self::RT_ISSUE => Self::Issue,
            Self::RT_QUERY_TOKEN_STATUS => Self::QueryTokenStatus,
            Self::RT_KEY_EXCHANGE_TOKEN => Self::KeyExchangeToken,
            other => return Err(RequestTypeParseError(other.to_string())),
        };

        Ok(request_type)
    }
}

/// Error that occurs when parsing a string into a [`RequestType`] fails.
///
/// This error is returned when the input string does not match any of the
/// valid URIs for MS-WSTEP request types.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestTypeParseError(String);

impl std::fmt::Display for RequestTypeParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} is not a valid MS-WSTEP request type", self.0)
    }
}

impl std::error::Error for RequestTypeParseError {}

#[cfg(test)]
mod request_security_token_tests {
    use crate::common::{serde_test_utils::se_test, BinarySecurityToken};

    use super::RequestSecurityToken;

    #[test]
    fn test_se_request_security_token() {
        let cms: &'static str =
            include_str!("../tests/data/standard_certificate_client_request.cms");
        let expected = format!(
            r#"<RequestSecurityToken xmlns="http://docs.oasis-open.org/ws-sx/ws-trust/200512"><TokenType>http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3</TokenType><RequestType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue</RequestType><BinarySecurityToken EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd#base64binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd#PKCS7" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">{cms}</BinarySecurityToken><RequestID xsi:nil="true" xmlns="http://schemas.microsoft.com/windows/pki/2009/01/enrollment"/></RequestSecurityToken>"#,
        );
        let actual =
            RequestSecurityToken::new_issue_x509v3(BinarySecurityToken::new_pkcs7_base64(cms));
        se_test(&expected, &actual);
    }
}