Skip to main content

opcua_kit/
identity.rs

1use base64::{Engine, engine::general_purpose::STANDARD};
2use uuid::Uuid;
3
4/// An invalid namespace URI or OPC UA identifier.
5#[derive(Copy, Clone, Debug, Eq, PartialEq)]
6pub struct NodeIdError(&'static str);
7
8impl std::fmt::Display for NodeIdError {
9    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10        f.write_str(self.0)
11    }
12}
13impl std::error::Error for NodeIdError {}
14
15#[cfg(feature = "commissioning")]
16#[derive(serde::Deserialize)]
17#[serde(deny_unknown_fields)]
18pub(crate) struct WireNode {
19    namespace: String,
20    id: String,
21}
22
23#[cfg(feature = "commissioning")]
24impl TryFrom<WireNode> for NodeId {
25    type Error = NodeIdError;
26    fn try_from(raw: WireNode) -> Result<Self, Self::Error> {
27        Self::new(raw.namespace, raw.id)
28    }
29}
30
31/// A namespace URI and a typed OPC UA identifier. Namespace indexes are session-local.
32///
33/// Numeric identifiers use decimal, GUIDs use hyphenated hex, and opaque identifiers
34/// use RFC 4648 standard Base64. String identifier contents are case-sensitive.
35#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
36#[cfg_attr(
37    feature = "commissioning",
38    derive(serde::Serialize, serde::Deserialize),
39    serde(try_from = "WireNode")
40)]
41pub struct NodeId {
42    /// Case-sensitive namespace URI.
43    namespace: String,
44    /// Identifier prefixed with `i=`, `s=`, `g=`, or `b=`.
45    id: String,
46}
47
48impl NodeId {
49    /// Create a canonical node identity from a namespace URI and a typed OPC UA identifier.
50    ///
51    /// For example, `NodeId::new("urn:plant:line-1", "i=00042")` stores `i=42`.
52    pub fn new(namespace: impl Into<String>, id: impl Into<String>) -> Result<Self, NodeIdError> {
53        let mut node = Self {
54            namespace: namespace.into(),
55            id: id.into(),
56        };
57        node.normalize()?;
58        Ok(node)
59    }
60
61    /// The case-sensitive namespace URI, stable across sessions.
62    pub fn namespace(&self) -> &str {
63        &self.namespace
64    }
65
66    /// The canonical identifier, including its OPC UA type prefix.
67    pub fn identifier(&self) -> &str {
68        &self.id
69    }
70
71    fn normalize(&mut self) -> Result<(), NodeIdError> {
72        // Part 3 ยง8.2 permits up to 4096 characters for strings or 4096 bytes
73        // for opaque identifiers. The four null representations only apply in ns=0.
74        if self.namespace.trim().is_empty() || self.namespace.chars().any(char::is_control) {
75            return Err(NodeIdError(
76                "expected a nonempty namespace URI without controls",
77            ));
78        }
79        let (kind, text) = self
80            .id
81            .split_once('=')
82            .ok_or(NodeIdError("expected an i=, s=, g= or b= identifier"))?;
83        let standard = self.namespace == "http://opcfoundation.org/UA/";
84        let null = match kind {
85            "i" => {
86                if !text.bytes().all(|byte| byte.is_ascii_digit()) {
87                    return Err(NodeIdError("numeric identifier must be unsigned decimal"));
88                }
89                let number = text
90                    .parse::<u32>()
91                    .map_err(|_| NodeIdError("numeric identifier is outside UInt32"))?;
92                self.id = format!("i={number}");
93                number == 0
94            }
95            "s" => {
96                if text.chars().count() > 4096 || text.chars().any(char::is_control) {
97                    return Err(NodeIdError(
98                        "string identifier exceeds 4096 characters or contains a control",
99                    ));
100                }
101                text.is_empty()
102            }
103            "g" => {
104                let guid =
105                    Uuid::try_parse(text).map_err(|_| NodeIdError("invalid hyphenated GUID"))?;
106                if text.len() != 36 {
107                    return Err(NodeIdError("GUID must use its hyphenated representation"));
108                }
109                self.id = format!("g={guid}");
110                guid.is_nil()
111            }
112            "b" => {
113                if text.len() > 5464 {
114                    return Err(NodeIdError("opaque identifier exceeds 4096 bytes"));
115                }
116                let bytes = STANDARD.decode(text).map_err(|_| {
117                    NodeIdError("opaque identifier must use standard padded base64")
118                })?;
119                if bytes.len() > 4096 {
120                    return Err(NodeIdError("opaque identifier exceeds 4096 bytes"));
121                }
122                bytes.is_empty()
123            }
124            _ => return Err(NodeIdError("expected an i=, s=, g= or b= identifier")),
125        };
126        if standard && null {
127            return Err(NodeIdError(
128                "null NodeId cannot identify a node or data type",
129            ));
130        }
131        Ok(())
132    }
133}