xrust 2.2.0

Support for XPath and XSLT
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! Support for security policies.
//!
//! A security policy allows a module to limit, or constrain, access to a resource.
//!
//! # Security Features
//! The resource is named, using a [QName], and the module will call into the in-force policy to determine the limitation set on the resource.
//! The limitation is returned as a [SecurityResult].
//! The module may provide [ActualParameters] to the feature, refer to the module's documentation for details.
//!
//! ```rust
//! # use std::rc::Rc;
//! use xrust::security::{SecurityResult, Policy, Feature};
//! use xrust::{Error, ErrorKind};
//! use xrust::item::{Item, Node};
//! use xrust::value::Value;
//! use xrust::transform::Transform;
//! use xrust::transform::callable::ActualParameters;
//! use qualname::{QName, NcName};
//!
//! fn get_feature<N: Node>(policy: &Policy<N>) -> Result<Option<String>, Error> {
//!    match policy.get(
//!       &QName::from_local_name(NcName::try_from("my_security_feature").unwrap()),
//!       ActualParameters::Named(vec![
//!          (QName::from_local_name(NcName::try_from("input").unwrap()),
//!           Transform::Literal(Item::Value(Rc::new(Value::from("value")))))
//!       ]),
//!    )? {
//!        SecurityResult::NotPermitted => Err(Error::new(ErrorKind::NotPermitted, "access denied")),
//!        SecurityResult::Permitted(None) => Ok(None),
//!        SecurityResult::Permitted(Some(v)) => Ok(Some(v)),
//!    }
//! }
//! ```
//!
//! If a policy does not define a limit or constraint for a resource,
//! then the module will define a default value. The module should set a default that has minimal security implications for the application.
//! Most likely this will be to deny access to the resource.
//!
//! # Security Policies
//! Security policies are named. Many named policies can be loaded into the system.
//! The application can nominate which policy it wants to be in force ("activated").
//!
//! Resource constraints are specified with a template.
//! Templates use the same syntax as XSLT templates.
//! The template is evaluated when a module wants to grant access to a resource.
//! The parameters provided by the module, see above, are passed to the template.
//! The template must return a single element, one of:
//! ```xslt
//! Q{http://gitlab.gnome.org/World/Rust/markup-rs/Security}not-permitted
//! Q{http://gitlab.gnome.org/World/Rust/markup-rs/Security}permitted
//! ```
//!
//! These elements map, respectively, to:
//! * SecurityResult::NotPermitted
//! * SecurityResult::Permitted(Option<String>)
//!
//! If the 'permitted' element does not contain content, then None is set in the SecurityResult::Permitted value.
//! Otherwise a Some is inserted with the string value of the content.
//!
//! In this example, a security policy is created with the feature set to "permitted with no limits".
//!
//! ```rust
//! use xrust::security::{Feature, Policy};
//! use xrust::transform::Transform;
//! use xrust::transform::callable::FormalParameters;
//! use xrust::trees::smite::RNode;
//! use qualname::{QName, NcName, NamespaceUri};
//!
//! let mut policy: Policy<RNode> = Policy::new(QName::from_local_name(
//!    NcName::try_from("test_policy").unwrap(),
//! ));
//! policy.add(
//!    QName::from_local_name(
//!        NcName::try_from("my_security_feature").unwrap(),
//!    ),
//!    Feature::new(Transform::LiteralElement(
//!      QName::new_from_parts(
//!        NcName::try_from("permitted").unwrap(),
//!        Some(NamespaceUri::try_from("http://gitlab.gnome.org/World/Rust/markup-rs/Security").unwrap()),
//!      ),
//!      Box::new(Transform::Empty),
//!    ),
//!    FormalParameters::Named(vec![])),
//! );
//! ```
//!
//! # Serialisation
//! Security policies may be represented as an XML document.
//! See the From trait implementation for [Policy].

#![allow(rustdoc::bare_urls)]

use std::collections::HashMap;

use crate::item::{Node, NodeType};
use crate::parser::xpath::parse;
use crate::transform::Transform;
use crate::transform::callable::{ActualParameters, FormalParameters};
use crate::transform::context::{ContextBuilder, StaticContextBuilder};
use crate::xdmerror::{Error, ErrorKind};
use crate::xslt::{ATTRNAME, ATTRSELECT, XSLPARAM, to_transform};
use qualname::{NamespaceUri, NcName, QName};

/// The result of determining the limitation or constraint for a security feature.
/// Permitted means that the application is allowed to access the resource.
/// The contained value is a limit on the usage of the resource.
/// If it is None then there is no limit on resource usage, or the module may impose a default limit.
/// NotPermitted means that the application is not allowed to access the resource at all, or the module may impose a default limit.
#[derive(Clone, Debug, PartialEq)]
pub enum SecurityResult {
    Permitted(Option<String>),
    NotPermitted,
}

/// All of the security policies available for use, indexed by name.
/// One of these policies may be in force (or "active").
#[derive(Clone, Debug)]
pub struct SecurityPolicies<N: Node> {
    policies: HashMap<QName, Policy<N>>,
    in_force: Option<QName>,
}

impl<N: Node> SecurityPolicies<N> {
    /// Create a new set of security policies.
    pub fn new() -> Self {
        Self {
            policies: HashMap::new(),
            in_force: None,
        }
    }
    /// Add a new security policy
    pub fn push(&mut self, policy: Policy<N>) {
        self.policies.insert(policy.name.clone(), policy);
    }
    /// Look up a security policy by name
    pub fn find(&self, name: QName) -> Option<&Policy<N>> {
        self.policies.get(&name)
    }
    /// Make the named security policy the "in force" (or "active") policy.
    pub fn activate(&mut self, name: &QName) -> Option<&Policy<N>> {
        self.policies.get_key_value(name).map(|(_k, v)| {
            self.in_force = Some(name.clone());
            v
        })
    }
    /// Determine whether a feature, in the in-force policy, is permitted.
    /// All parameters must be named, i.e. positional parameters are ignored.
    pub fn get(&self, f: &QName, a: ActualParameters<N>) -> Result<SecurityResult, Error> {
        // If there is no in-force security policy then all features are not permitted
        if self.in_force.is_none() {
            return Ok(SecurityResult::NotPermitted);
        }

        // Does the in-force security policy have the requested feature?
        // If not then it is not permitted
        if let Some(p) = self.policies.get(&self.in_force.as_ref().unwrap()) {
            p.get(f, a)
        } else {
            Ok(SecurityResult::NotPermitted)
        }
    }
}

/// A security policy. Security policies contain a number of security [Feature]s.
#[derive(Clone, Debug)]
pub struct Policy<N: Node> {
    name: QName,
    features: HashMap<QName, Feature<N>>,
}

impl<N: Node> Policy<N> {
    /// Create a new security policy
    pub fn new(name: QName) -> Self {
        Self {
            name,
            features: HashMap::new(),
        }
    }
    /// Get the name of the security policy
    pub fn name(&self) -> QName {
        self.name.clone()
    }
    /// Add a [Feature] to the security policy
    pub fn add(&mut self, name: QName, f: Feature<N>) {
        self.features.insert(name, f);
    }
    /// Get a [Feature] of the security policy
    pub fn feature(&self, name: &QName) -> Option<&Feature<N>> {
        self.features.get(name)
    }
    /*
    /// Get all of the [Feature]s of the security policy
    /// TODO: make this an iterator
    pub fn all_features(&self) -> Vec<&Feature<N>> {
        self.features.iter().map(|(_, f)| f).collect()
    }
    */
    /// Resolve the setting of a security [Feature].
    pub fn get(&self, name: &QName, a: ActualParameters<N>) -> Result<SecurityResult, Error> {
        self.features
            .get(name)
            .map_or_else(|| Ok(SecurityResult::NotPermitted), |f| f.get(a))
    }
}

/// Build a [Policy] from an XML document.
///
/// A security policy document has Q{http://gitlab.gnome.org/World/Rust/markup-rs/Security}policy as its toplevel element.
/// The policy element must have a name attribute.
///
/// The policy element may have one or more Q{http://gitlab.gnome.org/World/Rust/markup-rs/Security}feature child elements.
/// Each feature element must have a name attribute which has the qualified name of a security feature.
/// The feature element must contain either a Q{http://gitlab.gnome.org/World/Rust/markup-rs/Security}Permitted or {http://gitlab.gnome.org/World/Rust/markup-rs/Security}not-permitted element.
/// Which element is present determines whether the security feature is permitted or not.
///
/// The Q{http://gitlab.gnome.org/World/Rust/markup-rs/Security}permitted may contain child content.
/// If there is no content then the feature is permitted, but has no value.
/// If there is content then it is evaluated to determine the value for the feature.
/// The content is an XSLT template. It must result in a single element node, optionally with content. See above for the interpretation of the element.
///
/// Example security policy document:
///
/// ```xml
/// <sec:policy name="my-policy" xmlns:sec='http://gitlab.gnome.org/World/Rust/markup-rs/Security'
///    xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
///   <sec:feature name="feature1">
///     <sec:not-permitted/>
///   </sec:feature>
///   <sec:feature name="feature2">
///     <sec:permitted/>
///   </sec:feature>
///   <sec:feature name="feature3">
///     <sec:permitted>
///       <xsl:sequence select='42'/>
///     </sec:permitted>
///   </sec:feature>
///   <sec:feature name="feature4">
///     <sec:permitted>42</sec:permitted>
///   </sec:feature>
/// </sec:policy>
/// ```
//impl<N: Node> From<N> for Policy<N> {
pub trait SecurityPolicy {
    fn to_policy(&self) -> Result<Policy<Self>, Error>
    where
        Self: Node,
    {
        // TODO: make the QNames constants
        let secnsuri =
            NamespaceUri::try_from("http://gitlab.gnome.org/World/Rust/markup-rs/Security")
                .unwrap();
        if let Some(top) = self.first_child() {
            if !top.name().is_some_and(|qn| {
                qn == QName::new_from_parts(
                    NcName::try_from("policy").unwrap(),
                    Some(secnsuri.clone()),
                )
            }) {
                return Err(Error::new(
                    ErrorKind::TypeError,
                    "not a security policy document",
                ));
            }
            let name = top
                .get_attribute(&QName::from_local_name(NcName::try_from("name").unwrap()))
                .to_string();
            if name != "" {
                // Resolve qualified name to a QName using the doc's namespaces
                let mut policy = Policy::new(top.to_qname(name)?);

                // Content is feature elements, skipping over white space
                let fname = QName::new_from_parts(
                    NcName::try_from("feature").unwrap(),
                    Some(secnsuri.clone()),
                );
                top.child_iter()
                    .filter(|c| c.name().is_some_and(|n| n == fname))
                    .try_for_each(|f| {
                        let feat_name = f
                            .get_attribute(&QName::from_local_name(
                                NcName::try_from("name").unwrap(),
                            ))
                            .to_string();
                        if feat_name != "" {
                            // Content is the template to evaluate
                            let mut body: Vec<Transform<Self>> = vec![];
                            // attribute sets are not used in this context
                            let attr_sets: HashMap<QName, Vec<Transform<Self>>> = HashMap::new();

                            // Strip whitespace
                            f.descend_iter()
                                .filter(|ws| {
                                    ws.node_type() == NodeType::Text
                                        && ws.value().to_string().trim().is_empty()
                                })
                                .for_each(|mut ws| {
                                    ws.pop().expect("unable to remove whitespace node")
                                });

                            // Get any formal parameters
                            let mut params: Vec<(QName, Option<Transform<Self>>)> = Vec::new();
                            f.child_iter()
                                .filter(|d| d.name().is_some_and(|e| e == *XSLPARAM))
                                .try_for_each(|d| {
                                    let p_name = d.get_attribute(&ATTRNAME);
                                    if p_name.to_string().is_empty() {
                                        Err(Error::new(
                                            ErrorKind::StaticAbsent,
                                            "name attribute is missing",
                                        ))
                                    } else {
                                        let sel = d.get_attribute(&ATTRSELECT);
                                        if sel.to_string().is_empty() {
                                            // xsl:param content is the sequence constructor
                                            let mut body = vec![];
                                            d.child_iter().try_for_each(|e| {
                                                body.push(to_transform(e, &attr_sets)?);
                                                Ok(())
                                            })?;
                                            params.push((
                                                QName::from_local_name(
                                                    NcName::try_from(p_name.to_string().as_str())
                                                        .map_err(|_| {
                                                        Error::new(
                                                            ErrorKind::ParseError,
                                                            "not a QName",
                                                        )
                                                    })?,
                                                ),
                                                Some(Transform::SequenceItems(body)),
                                            ));
                                            Ok(())
                                        } else {
                                            // select attribute value is an expression
                                            params.push((
                                                QName::from_local_name(
                                                    NcName::try_from(p_name.to_string().as_str())
                                                        .map_err(|_| {
                                                        Error::new(
                                                            ErrorKind::ParseError,
                                                            "not a QName",
                                                        )
                                                    })?,
                                                ),
                                                Some(parse::<Self>(
                                                    &sel.to_string(),
                                                    Some(d.clone()),
                                                    None,
                                                )?),
                                            ));
                                            Ok(())
                                        }
                                    }
                                })?;
                            // Compile template
                            f.child_iter()
                                .filter(|d| d.name().is_some_and(|e| e != *XSLPARAM))
                                .try_for_each(|d| {
                                    body.push(to_transform(d, &attr_sets)?);
                                    Ok::<(), Error>(())
                                })?;
                            if body.len() == 0 {
                                return Err(Error::new(
                                    ErrorKind::TypeError,
                                    format!("template for feature {} must not be empty", feat_name),
                                ));
                            }
                            if body.len() == 1 {
                                policy.add(
                                    top.to_qname(feat_name)?,
                                    Feature::new(body.remove(0), FormalParameters::Named(params)),
                                )
                            } else {
                                policy.add(
                                    top.to_qname(feat_name)?,
                                    Feature::new(
                                        Transform::SequenceItems(body),
                                        FormalParameters::Named(params),
                                    ),
                                )
                            }
                        } else {
                            return Err(Error::new(
                                ErrorKind::DynamicAbsent,
                                "feature must have a name",
                            ));
                        }
                        Ok(())
                    })?;
                Ok(policy)
            } else {
                Err(Error::new(
                    ErrorKind::DynamicAbsent,
                    "name attribute is required",
                ))
            }
        } else {
            Err(Error::new(ErrorKind::DynamicAbsent, "empty document"))
        }
    }
}

/// A security feature. These limit or constrain acccess to a resource.
/// Access to a resource may, or may not, be permitted.
/// If access is permitted, then it may also be constrained so some maximum value.
/// This value is computed dynamically using a [Transform].
/// The transformation is not allowed to access external resources.
#[derive(Clone, Debug)]
pub struct Feature<N: Node> {
    t: Transform<N>,
    parameters: FormalParameters<N>,
}

impl<N: Node> Feature<N> {
    /// Create a Feature
    pub fn new(t: Transform<N>, parameters: FormalParameters<N>) -> Self {
        Feature { t, parameters }
    }

    /// Evaluate the template to determine whether this security feature is permitted,
    /// and if so then to what limit, i.e. a maximum value.
    pub fn get(&self, a: ActualParameters<N>) -> Result<SecurityResult, Error> {
        // The template is a callable.
        // The template must return an element, so there needs to be a result document.
        // The use of a document is completely internal to this function,
        // but there needs to be a concrete type available to create a fresh document.
        let mut stctxt = StaticContextBuilder::new()
            .message(|_| Ok(()))
            .parser(|_| {
                Err(Error::new(
                    ErrorKind::StaticBadFunction,
                    "external resources are not allowed",
                ))
            })
            .fetcher(|_: &_| {
                Err(Error::new(
                    ErrorKind::StaticBadFunction,
                    "external resources are not allowed",
                ))
            })
            .build();
        let rd = N::new_document();
        let mut ctxt = ContextBuilder::new().result_document(rd).build();
        // TODO: match actual parameters to formal.
        // TODO: create default value for named formal parameters that are absent from the actuals
        if let ActualParameters::Named(ap) = a {
            ap.iter().try_for_each(|(an, av)| {
                ctxt.var_push(an.to_string(), ctxt.dispatch(&mut stctxt, av)?);
                Ok(())
            })?;
            if let FormalParameters::Named(fp) = &self.parameters {
                // If the parameter has not already been defined by an actual,
                // set it to its default value
                fp.iter().try_for_each(|frm| {
                    if ctxt.var_value(frm.0.to_string()).is_none() {
                        if let Some(vv) = &frm.1 {
                            ctxt.var_push(frm.0.to_string(), ctxt.dispatch(&mut stctxt, &vv)?);
                        } else {
                            ctxt.var_push(frm.0.to_string(), vec![]);
                        }
                    }
                    Ok(())
                })?;
            }
        }
        // TODO: make these constants
        let np = QName::new_from_parts(
            NcName::try_from("not-permitted").unwrap(),
            Some(
                NamespaceUri::try_from("http://gitlab.gnome.org/World/Rust/markup-rs/Security")
                    .unwrap(),
            ),
        );
        let p = QName::new_from_parts(
            NcName::try_from("permitted").unwrap(),
            Some(
                NamespaceUri::try_from("http://gitlab.gnome.org/World/Rust/markup-rs/Security")
                    .unwrap(),
            ),
        );

        // Now evaluate the template. It must result in a single element node.
        let r = ctxt.dispatch(&mut stctxt, &self.t)?;
        if r.len() == 1 {
            if r[0].is_element_node() {
                if r[0].name().unwrap() == np {
                    Ok(SecurityResult::NotPermitted)
                } else if r[0].name().unwrap() == p {
                    let content = r[0].to_string();
                    if content.is_empty() {
                        Ok(SecurityResult::Permitted(None))
                    } else {
                        Ok(SecurityResult::Permitted(Some(content)))
                    }
                } else {
                    Err(Error::new(
                        ErrorKind::TypeError,
                        "result must be a permitted or not-permitted element",
                    ))
                }
            } else {
                Err(Error::new(
                    ErrorKind::DynamicAbsent,
                    "result must be an element",
                ))
            }
        } else {
            Err(Error::new(
                ErrorKind::DynamicAbsent,
                "result must be a single element",
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::item::Item;
    use crate::trees::smite::RNode;
    use crate::value::Value;
    use std::rc::Rc;

    #[test]
    fn feature_get_np() {
        let f = Feature::new(
            Transform::LiteralElement(
                QName::new_from_parts(
                    NcName::try_from("not-permitted").unwrap(),
                    Some(
                        NamespaceUri::try_from(
                            "http://gitlab.gnome.org/World/Rust/markup-rs/Security",
                        )
                        .unwrap(),
                    ),
                ),
                Box::new(Transform::<RNode>::Empty),
            ),
            FormalParameters::Named(vec![]),
        );
        assert_eq!(
            f.get(ActualParameters::Named(vec![]))
                .expect("unable to determine status of security feature"),
            SecurityResult::NotPermitted
        )
    }

    #[test]
    fn feature_get_unlimited() {
        let f = Feature::new(
            Transform::LiteralElement(
                QName::new_from_parts(
                    NcName::try_from("permitted").unwrap(),
                    Some(
                        NamespaceUri::try_from(
                            "http://gitlab.gnome.org/World/Rust/markup-rs/Security",
                        )
                        .unwrap(),
                    ),
                ),
                Box::new(Transform::<RNode>::Empty),
            ),
            FormalParameters::Named(vec![]),
        );
        assert_eq!(
            f.get(ActualParameters::Named(vec![]))
                .expect("unable to determine status of security feature"),
            SecurityResult::Permitted(None)
        )
    }

    #[test]
    fn feature_get_limited() {
        let f = Feature::new(
            Transform::LiteralElement(
                QName::new_from_parts(
                    NcName::try_from("permitted").unwrap(),
                    Some(
                        NamespaceUri::try_from(
                            "http://gitlab.gnome.org/World/Rust/markup-rs/Security",
                        )
                        .unwrap(),
                    ),
                ),
                Box::new(Transform::Literal(Item::<RNode>::Value(Rc::new(
                    Value::from(1234),
                )))),
            ),
            FormalParameters::Named(vec![]),
        );
        assert_eq!(
            f.get(ActualParameters::Named(vec![]))
                .expect("unable to determine status of security feature"),
            SecurityResult::Permitted(Some(String::from("1234")))
        )
    }
}