async-opcua-nodes 0.19.0

OPC UA node representation and import framework
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
use std::collections::HashSet;

use hashbrown::HashMap;

use opcua_types::{
    AttributeId, ContentFilter, ContentFilterElementResult, ContentFilterResult, ElementOperand,
    EventFilter, EventFilterResult, FilterOperator, LiteralOperand, NodeClass, NodeId,
    NumericRange, ObjectTypeId, Operand, QualifiedName, RelativePath, SimpleAttributeOperand,
    StatusCode, UAString,
};

use crate::TypeTree;

#[derive(Debug, Clone)]
/// Parsed version of the raw [opcua_types::AttributeOperand]
pub struct ParsedAttributeOperand {
    /// Node ID of the node to get attribute from.
    pub node_id: NodeId,
    /// Attribute alias.
    pub alias: UAString,
    /// Browse path to the property to get from.
    pub browse_path: RelativePath,
    /// Attribute ID to get.
    pub attribute_id: AttributeId,
    /// Range of attribute to get.
    pub index_range: NumericRange,
}

#[derive(Debug, Clone)]
/// Parsed version of the raw [SimpleAttributeOperand].
pub struct ParsedSimpleAttributeOperand {
    /// Node ID of the type definition to get values from.
    pub type_definition_id: NodeId,
    /// Path to the property to get.
    pub browse_path: Vec<QualifiedName>,
    /// Attribute ID to get.
    pub attribute_id: AttributeId,
    /// Range of attribute to get.
    pub index_range: NumericRange,
}

#[derive(Debug, Clone)]
/// Parsed and validated [Operand].
pub enum ParsedOperand {
    /// Another element in the filter.
    ElementOperand(ElementOperand),
    /// A literal value.
    LiteralOperand(LiteralOperand),
    /// An attribute in a different node.
    AttributeOperand(ParsedAttributeOperand),
    /// An attribute of a type.
    SimpleAttributeOperand(ParsedSimpleAttributeOperand),
}

impl ParsedOperand {
    pub(crate) fn parse(
        operand: Operand,
        num_elements: usize,
        type_tree: &dyn TypeTree,
        allow_attribute_operands: bool,
    ) -> Result<Self, StatusCode> {
        match operand {
            Operand::ElementOperand(e) => {
                if e.index as usize >= num_elements {
                    Err(StatusCode::BadFilterOperandInvalid)
                } else {
                    Ok(Self::ElementOperand(e))
                }
            }
            Operand::LiteralOperand(o) => Ok(Self::LiteralOperand(o)),
            Operand::AttributeOperand(o) => {
                if !allow_attribute_operands {
                    return Err(StatusCode::BadFilterOperandInvalid);
                }
                let attribute_id = AttributeId::from_u32(o.attribute_id)
                    .map_err(|_| StatusCode::BadAttributeIdInvalid)?;
                Ok(Self::AttributeOperand(ParsedAttributeOperand {
                    node_id: o.node_id,
                    attribute_id,
                    alias: o.alias,
                    browse_path: o.browse_path,
                    index_range: o.index_range,
                }))
            }
            Operand::SimpleAttributeOperand(o) => Ok(Self::SimpleAttributeOperand(
                validate_select_clause(o, type_tree)?,
            )),
        }
    }
}

#[derive(Debug, Clone)]
/// Parsed version of the raw [EventFilter].
pub struct ParsedEventFilter {
    pub(super) content_filter: ParsedContentFilter,
    pub(super) select_clauses: Vec<ParsedSimpleAttributeOperand>,
}

impl ParsedEventFilter {
    /// Try to build a parsed filter from a raw [EventFilter].
    ///
    /// This may fail, but will always return an [EventFilterResult].
    pub fn new(
        raw: EventFilter,
        type_tree: &dyn TypeTree,
    ) -> (EventFilterResult, Result<Self, StatusCode>) {
        validate(raw, type_tree)
    }
}

#[derive(Debug, Clone)]
/// Parsed version of the raw [ContentFilter].
pub struct ParsedContentFilter {
    pub(super) elements: Vec<ParsedContentFilterElement>,
}

impl ParsedContentFilter {
    /// Create a new empty content filter.
    pub fn empty() -> Self {
        Self {
            elements: Vec::new(),
        }
    }

    /// Create a new content filter from the raw [ContentFilter].
    ///
    /// If `allow_attribute_operands` is false, parsing will fail
    /// if it encounters an attribute operand.
    ///
    /// `banned_operators` is a list of operators that are not allowed in the filter.
    /// If any of these operators are present, the parsing will fail with
    /// `StatusCode::BadFilterOperatorUnsupported`.
    pub fn parse(
        filter: ContentFilter,
        type_tree: &dyn TypeTree,
        allow_attribute_operands: bool,
        banned_operators: &[FilterOperator],
    ) -> (ContentFilterResult, Result<ParsedContentFilter, StatusCode>) {
        validate_where_clause(
            filter,
            type_tree,
            allow_attribute_operands,
            banned_operators,
        )
    }
}

#[derive(Debug, Clone)]
/// Element of a parsed content filter.
pub struct ParsedContentFilterElement {
    pub(super) operator: FilterOperator,
    pub(super) operands: Vec<ParsedOperand>,
}

/// This validates the event filter as best it can to make sure it doesn't contain nonsense.
fn validate(
    event_filter: EventFilter,
    type_tree: &dyn TypeTree,
) -> (EventFilterResult, Result<ParsedEventFilter, StatusCode>) {
    let num_select_clauses = event_filter
        .select_clauses
        .as_ref()
        .map(|r| r.len())
        .unwrap_or_default();
    let mut select_clause_results = Vec::with_capacity(num_select_clauses);
    let mut final_select_clauses = Vec::with_capacity(num_select_clauses);
    for clause in event_filter.select_clauses.into_iter().flatten() {
        match validate_select_clause(clause, type_tree) {
            Ok(result) => {
                select_clause_results.push(StatusCode::Good);
                final_select_clauses.push(result);
            }
            Err(e) => select_clause_results.push(e),
        }
    }
    let (where_clause_result, parsed_where_clause) = validate_where_clause(
        event_filter.where_clause,
        type_tree,
        false,
        &[FilterOperator::InView, FilterOperator::RelatedTo],
    );

    (
        EventFilterResult {
            select_clause_results: if select_clause_results.is_empty() {
                None
            } else {
                Some(select_clause_results)
            },
            select_clause_diagnostic_infos: None,
            where_clause_result,
        },
        parsed_where_clause.map(|f| ParsedEventFilter {
            content_filter: f,
            select_clauses: final_select_clauses,
        }),
    )
}

fn validate_select_clause(
    clause: SimpleAttributeOperand,
    type_tree: &dyn TypeTree,
) -> Result<ParsedSimpleAttributeOperand, StatusCode> {
    let Some(path) = clause.browse_path else {
        return Err(StatusCode::BadNodeIdUnknown);
    };

    let Ok(attribute_id) = AttributeId::from_u32(clause.attribute_id) else {
        return Err(StatusCode::BadAttributeIdInvalid);
    };

    // From the standard:  If the SimpleAttributeOperand is used in an EventFilter
    // and the typeDefinitionId is BaseEventType the Server shall evaluate the
    // browsePath without considering the typeDefinitionId.
    if clause.type_definition_id == (0, ObjectTypeId::BaseEventType as u32) {
        // Do a simpler form of the attribute ID check in this case.
        if attribute_id != AttributeId::NodeId && attribute_id != AttributeId::Value {
            return Err(StatusCode::BadAttributeIdInvalid);
        }
        // We could in theory evaluate _every_ event type here, but that would be painful
        // and potentially expensive on servers with lots of types. It also wouldn't
        // be all that helpful.
        return Ok(ParsedSimpleAttributeOperand {
            type_definition_id: clause.type_definition_id,
            browse_path: path,
            attribute_id,
            index_range: clause.index_range,
        });
    }

    let Some(node) = type_tree.find_type_prop_by_browse_path(&clause.type_definition_id, &path)
    else {
        return Err(StatusCode::BadNodeIdUnknown);
    };

    // Validate the attribute id. Per spec:
    //
    //   The SimpleAttributeOperand allows the client to specify any attribute; however the server
    //   is only required to support the value attribute for variable nodes and the NodeId attribute
    //   for object nodes. That said, profiles defined in Part 7 may make support for
    //   additional attributes mandatory.
    //
    // So code will implement the bare minimum for now.
    let is_valid = match node.node_class {
        NodeClass::Object => attribute_id == AttributeId::NodeId,
        NodeClass::Variable => attribute_id == AttributeId::Value,
        _ => false,
    };

    if !is_valid {
        Err(StatusCode::BadAttributeIdInvalid)
    } else {
        Ok(ParsedSimpleAttributeOperand {
            type_definition_id: clause.type_definition_id,
            browse_path: path,
            attribute_id,
            index_range: clause.index_range,
        })
    }
}

fn validate_where_clause(
    where_clause: ContentFilter,
    type_tree: &dyn TypeTree,
    allow_attribute_operand: bool,
    banned_operators: &[FilterOperator],
) -> (ContentFilterResult, Result<ParsedContentFilter, StatusCode>) {
    // The ContentFilter structure defines a collection of elements that define filtering criteria.
    // Each element in the collection describes an operator and an array of operands to be used by
    // the operator. The operators that can be used in a ContentFilter are described in Table 119.
    // The filter is evaluated by evaluating the first entry in the element array starting with the
    // first operand in the operand array. The operands of an element may contain References to
    // sub-elements resulting in the evaluation continuing to the referenced elements in the element
    // array. The evaluation shall not introduce loops. For example evaluation starting from element
    // “A” shall never be able to return to element “A”. However there may be more than one path
    // leading to another element “B”. If an element cannot be traced back to the starting element
    // it is ignored. Extra operands for any operator shall result in an error. Annex B provides
    // examples using the ContentFilter structure.

    let Some(elements) = where_clause.elements else {
        return (
            ContentFilterResult {
                element_results: None,
                element_diagnostic_infos: None,
            },
            Ok(ParsedContentFilter::empty()),
        );
    };

    let mut operand_refs: HashMap<usize, Vec<usize>> = HashMap::new();
    let num_elements = elements.len();
    let element_result_pairs: Vec<(
        ContentFilterElementResult,
        Option<ParsedContentFilterElement>,
    )> = elements
        .into_iter()
        .enumerate()
        .map(|(element_idx, e)| {
            let Some(filter_operands) = e.filter_operands else {
                return (
                    ContentFilterElementResult {
                        status_code: StatusCode::BadFilterOperandCountMismatch,
                        operand_status_codes: None,
                        operand_diagnostic_infos: None,
                    },
                    None,
                );
            };
            let num_filter_operands = filter_operands.len();

            let operand_count_mismatch = match e.filter_operator {
                FilterOperator::Equals => filter_operands.len() != 2,
                FilterOperator::IsNull => filter_operands.len() != 1,
                FilterOperator::GreaterThan => filter_operands.len() != 2,
                FilterOperator::LessThan => filter_operands.len() != 2,
                FilterOperator::GreaterThanOrEqual => filter_operands.len() != 2,
                FilterOperator::LessThanOrEqual => filter_operands.len() != 2,
                FilterOperator::Like => filter_operands.len() != 2,
                FilterOperator::Not => filter_operands.len() != 1,
                FilterOperator::Between => filter_operands.len() != 3,
                FilterOperator::InList => filter_operands.len() < 2, // 2..n
                FilterOperator::And => filter_operands.len() != 2,
                FilterOperator::Or => filter_operands.len() != 2,
                FilterOperator::Cast => filter_operands.len() != 2,
                FilterOperator::BitwiseAnd => filter_operands.len() != 2,
                FilterOperator::BitwiseOr => filter_operands.len() != 2,
                FilterOperator::InView => filter_operands.len() != 1,
                FilterOperator::OfType => filter_operands.len() != 1,
                FilterOperator::RelatedTo => filter_operands.len() != 6,
            };

            if banned_operators.contains(&e.filter_operator) {
                return (
                    ContentFilterElementResult {
                        status_code: StatusCode::BadFilterOperatorUnsupported,
                        operand_status_codes: None,
                        operand_diagnostic_infos: None,
                    },
                    None,
                );
            }

            let mut valid_operands = Vec::with_capacity(filter_operands.len());
            let mut operand_status_codes = Vec::with_capacity(filter_operands.len());

            let operand_results: Vec<_> = filter_operands
                .into_iter()
                .map(|e| {
                    let operand = <Operand>::try_from(e.clone())?;
                    ParsedOperand::parse(operand, num_elements, type_tree, allow_attribute_operand)
                })
                .collect();

            for res in operand_results {
                match res {
                    Ok(op) => {
                        operand_status_codes.push(StatusCode::Good);
                        if let ParsedOperand::ElementOperand(e) = &op {
                            operand_refs
                                .entry(element_idx)
                                .or_default()
                                .push(e.index as usize);
                        }
                        valid_operands.push(op);
                    }
                    Err(e) => operand_status_codes.push(e),
                }
            }
            let operator_invalid = valid_operands.len() != num_filter_operands;

            // Check what error status to return
            let status_code = if operand_count_mismatch {
                StatusCode::BadFilterOperandCountMismatch
            } else if operator_invalid {
                StatusCode::BadFilterOperandInvalid
            } else {
                StatusCode::Good
            };

            let res = if status_code.is_good() {
                Some(ParsedContentFilterElement {
                    operator: e.filter_operator,
                    operands: valid_operands,
                })
            } else {
                None
            };

            (
                ContentFilterElementResult {
                    status_code,
                    operand_status_codes: Some(operand_status_codes),
                    operand_diagnostic_infos: None,
                },
                res,
            )
        })
        .collect();

    let mut is_valid = true;
    let mut valid_elements = Vec::with_capacity(num_elements);
    let mut element_results = Vec::with_capacity(num_elements);
    for (result, element) in element_result_pairs {
        if let Some(element) = element {
            valid_elements.push(element);
        } else {
            is_valid = false;
        }
        element_results.push(result);
    }

    // Discover cycles. The operators must form a tree starting from the first
    let mut path = HashSet::new();
    match has_cycles(&operand_refs, 0, &mut path) {
        Ok(()) => (),
        Err(()) => is_valid = false,
    }

    (
        ContentFilterResult {
            element_results: Some(element_results),
            element_diagnostic_infos: None,
        },
        if is_valid {
            Ok(ParsedContentFilter {
                elements: valid_elements,
            })
        } else {
            Err(StatusCode::BadEventFilterInvalid)
        },
    )
}

fn has_cycles(
    children: &HashMap<usize, Vec<usize>>,
    id: usize,
    path: &mut HashSet<usize>,
) -> Result<(), ()> {
    let Some(child_refs) = children.get(&id) else {
        return Ok(());
    };
    if !path.insert(id) {
        return Err(());
    }

    for child in child_refs {
        has_cycles(children, *child, path)?;
    }

    path.remove(&id);

    Ok(())
}

#[cfg(test)]
mod tests {
    use crate::{events::validation::validate_where_clause, DefaultTypeTree};
    use opcua_types::{
        AttributeId, ContentFilter, ContentFilterElement, ContentFilterResult, FilterOperator,
        NodeClass, NodeId, ObjectTypeId, Operand, SimpleAttributeOperand, StatusCode,
    };

    #[test]
    fn test_validate_empty_where_clause() {
        let type_tree = DefaultTypeTree::new();
        // check for at least one filter operand
        let where_clause = ContentFilter { elements: None };
        let (result, filter) = validate_where_clause(where_clause, &type_tree, false, &[]);
        assert_eq!(
            result,
            ContentFilterResult {
                element_results: None,
                element_diagnostic_infos: None,
            }
        );
        assert!(filter.is_ok());
    }

    #[test]
    fn test_validate_operator_len() {
        let type_tree = DefaultTypeTree::new();

        // Make a where clause where every single operator is included but each has the wrong number of operands.
        // We should expect them all to be in error
        let where_clause = ContentFilter {
            elements: Some(vec![
                ContentFilterElement::from((FilterOperator::Equals, vec![Operand::literal(10)])),
                ContentFilterElement::from((FilterOperator::IsNull, vec![])),
                ContentFilterElement::from((
                    FilterOperator::GreaterThan,
                    vec![Operand::literal(10)],
                )),
                ContentFilterElement::from((FilterOperator::LessThan, vec![Operand::literal(10)])),
                ContentFilterElement::from((
                    FilterOperator::GreaterThanOrEqual,
                    vec![Operand::literal(10)],
                )),
                ContentFilterElement::from((
                    FilterOperator::LessThanOrEqual,
                    vec![Operand::literal(10)],
                )),
                ContentFilterElement::from((FilterOperator::Like, vec![Operand::literal(10)])),
                ContentFilterElement::from((FilterOperator::Not, vec![])),
                ContentFilterElement::from((
                    FilterOperator::Between,
                    vec![Operand::literal(10), Operand::literal(20)],
                )),
                ContentFilterElement::from((FilterOperator::InList, vec![Operand::literal(10)])),
                ContentFilterElement::from((FilterOperator::And, vec![Operand::literal(10)])),
                ContentFilterElement::from((FilterOperator::Or, vec![Operand::literal(10)])),
                ContentFilterElement::from((FilterOperator::Cast, vec![Operand::literal(10)])),
                ContentFilterElement::from((
                    FilterOperator::BitwiseAnd,
                    vec![Operand::literal(10)],
                )),
                ContentFilterElement::from((FilterOperator::BitwiseOr, vec![Operand::literal(10)])),
                ContentFilterElement::from((FilterOperator::Like, vec![Operand::literal(10)])),
            ]),
        };
        // Check for less than required number of operands
        let (result, filter) = validate_where_clause(where_clause, &type_tree, false, &[]);
        result
            .element_results
            .unwrap()
            .iter()
            .for_each(|e| assert_eq!(e.status_code, StatusCode::BadFilterOperandCountMismatch));
        assert_eq!(filter.unwrap_err(), StatusCode::BadEventFilterInvalid);
    }

    #[test]
    fn test_validate_bad_filter_operand() {
        let type_tree = DefaultTypeTree::new();

        // check for filter operator invalid, by giving it a bogus extension object for an element
        use opcua_types::{ContentFilterElement, ExtensionObject};
        let bad_operator = ExtensionObject::null();
        let where_clause = ContentFilter {
            elements: Some(vec![ContentFilterElement {
                filter_operator: FilterOperator::IsNull,
                filter_operands: Some(vec![bad_operator]),
            }]),
        };
        let (result, filter) = validate_where_clause(where_clause, &type_tree, false, &[]);
        let element_results = result.element_results.unwrap();
        assert_eq!(element_results.len(), 1);
        assert_eq!(
            element_results[0].status_code,
            StatusCode::BadFilterOperandInvalid
        );
        let err = filter.unwrap_err();
        assert_eq!(err, StatusCode::BadEventFilterInvalid);
    }

    #[test]
    fn test_validate_select_operands() {
        let mut type_tree = DefaultTypeTree::new();

        type_tree.add_type_node(
            &NodeId::new(1, "event"),
            &ObjectTypeId::BaseEventType.into(),
            NodeClass::ObjectType,
        );
        type_tree.add_type_property(
            &NodeId::new(1, "prop"),
            &NodeId::new(1, "event"),
            &[&"Prop".into()],
            NodeClass::Variable,
        );

        // One attribute that exists, one that doesn't.
        let where_clause = ContentFilter {
            elements: Some(vec![
                ContentFilterElement::from((
                    FilterOperator::IsNull,
                    vec![Operand::SimpleAttributeOperand(SimpleAttributeOperand {
                        type_definition_id: NodeId::new(1, "event"),
                        browse_path: Some(vec!["Prop".into()]),
                        attribute_id: AttributeId::Value as u32,
                        index_range: Default::default(),
                    })],
                )),
                ContentFilterElement::from((
                    FilterOperator::IsNull,
                    vec![Operand::SimpleAttributeOperand(SimpleAttributeOperand {
                        type_definition_id: NodeId::new(1, "event"),
                        browse_path: Some(vec!["Prop2".into()]),
                        attribute_id: AttributeId::Value as u32,
                        index_range: Default::default(),
                    })],
                )),
            ]),
        };

        let (result, filter) = validate_where_clause(where_clause, &type_tree, false, &[]);
        let element_results = result.element_results.unwrap();
        assert_eq!(element_results.len(), 2);
        assert_eq!(element_results[0].status_code, StatusCode::Good);
        assert_eq!(
            element_results[1].status_code,
            StatusCode::BadFilterOperandInvalid
        );
        let status_codes = element_results[1].operand_status_codes.as_ref().unwrap();
        assert_eq!(status_codes.len(), 1);
        assert_eq!(status_codes[0], StatusCode::BadNodeIdUnknown);
        assert_eq!(filter.unwrap_err(), StatusCode::BadEventFilterInvalid);
    }

    #[test]
    fn test_validate_circular_filter() {
        let type_tree = DefaultTypeTree::new();

        let where_clause = ContentFilter {
            elements: Some(vec![
                ContentFilterElement::from((
                    FilterOperator::And,
                    vec![Operand::element(1), Operand::element(2)],
                )),
                ContentFilterElement::from((FilterOperator::IsNull, vec![Operand::literal(10)])),
                ContentFilterElement::from((
                    FilterOperator::Or,
                    vec![Operand::element(1), Operand::element(3)],
                )),
                ContentFilterElement::from((FilterOperator::Not, vec![Operand::element(0)])),
            ]),
        };

        let (_result, filter) = validate_where_clause(where_clause, &type_tree, false, &[]);
        assert_eq!(filter.unwrap_err(), StatusCode::BadEventFilterInvalid);
    }
}