Skip to main content

opcua_kit/client/
connection.rs

1use crate::secure_channel::Identity;
2pub use crate::secure_channel::SecurityPolicy;
3use crate::ua::StatusCode;
4use std::{fmt, sync::Arc, time::Duration};
5use time::OffsetDateTime;
6use x509_parser::prelude::X509Certificate;
7#[path = "session.rs"]
8mod session;
9pub(super) use session::Session;
10
11/// User authentication within the pinned encrypted session.
12#[derive(Clone, Copy, Default)]
13pub enum UserIdentity<'a> {
14    /// Use the anonymous user token.
15    #[default]
16    Anonymous,
17    /// Present a site account and password.
18    Username {
19        /// Site account name.
20        username: &'a str,
21        /// Password supplied by the host.
22        password: &'a str,
23    },
24}
25impl UserIdentity<'_> {
26    pub(super) fn validate(self) -> Result<(), ConnectError> {
27        if let Self::Username { username, password } = self
28            && (username.trim().is_empty()
29                || username.len() > 256
30                || username.chars().any(char::is_control)
31                || password.is_empty()
32                || password.len() > 4096)
33        {
34            return Err(InvalidConfiguration(
35                "expected a user name up to 256 bytes and password of 1–4096 bytes",
36            ));
37        }
38        Ok(())
39    }
40
41    /// Scope label used in contracts, snapshots and readings.
42    pub fn principal(self) -> String {
43        match self {
44            Self::Anonymous => "anonymous".to_owned(),
45            Self::Username { username, .. } => format!("username:{username}"),
46        }
47    }
48}
49
50/// Select a channel policy and session user. The default is pinned Basic256Sha256 with an anonymous user.
51#[derive(Clone, Copy, Default)]
52pub struct ConnectionOptions<'a> {
53    /// Explicit channel policy. A failed connection never falls back to a weaker policy.
54    pub security_policy: SecurityPolicy,
55    /// User token, independent of the client application certificate.
56    pub user_identity: UserIdentity<'a>,
57}
58
59const MAX_CREDENTIAL_BYTES: usize = 64 * 1024;
60
61/// Endpoint and application credentials shared by all pinned user sessions.
62/// Certificate and unencrypted private key inputs use DER encoding (up to 64 KiB each).
63#[derive(Clone, Copy)]
64pub struct ConnectionConfig<'a> {
65    /// Explicit opc.tcp URL including port, e.g. `opc.tcp://plc.example:4840`.
66    pub endpoint: &'a str,
67    /// URI from the reviewed server identity and its certificate SAN.
68    pub server_application_uri: &'a str,
69    /// Exact server leaf certificate, obtained through a trusted channel.
70    pub server_certificate_der: &'a [u8],
71    /// URI of the client application in its certificate SAN.
72    pub client_application_uri: &'a str,
73    /// Client application certificate, trusted by the selected server.
74    pub client_certificate_der: &'a [u8],
75    /// Private key matching the client certificate. Its storage remains the caller's responsibility.
76    pub client_private_key_der: &'a [u8],
77    /// Response timeout between one millisecond and 60 seconds.
78    pub timeout: Duration,
79}
80
81/// A local configuration rejection or an OPC UA connection failure.
82#[derive(Debug)]
83pub enum ConnectError {
84    /// A configuration or credential failed local validation before dialing the endpoint.
85    InvalidConfiguration(&'static str),
86    /// The secure channel or session could not be opened.
87    Connection(StatusCode),
88}
89
90impl fmt::Display for ConnectError {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        match self {
93            Self::InvalidConfiguration(reason) => f.write_str(reason),
94            Self::Connection(error) => write!(f, "could not open secure OPC UA session: {error}"),
95        }
96    }
97}
98
99impl std::error::Error for ConnectError {
100    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
101        match self {
102            Self::InvalidConfiguration(_) => None,
103            Self::Connection(error) => Some(error),
104        }
105    }
106}
107
108use ConnectError::InvalidConfiguration;
109
110fn application_certificate<'a>(
111    der: &'a [u8],
112    uri: &str,
113    server_host: Option<&str>,
114    require_current: bool,
115) -> Result<X509Certificate<'a>, ConnectError> {
116    crate::certificate::application_certificate(der, uri, server_host, require_current)
117        .map_err(InvalidConfiguration)
118}
119
120/// A separately provisioned successor leaf for the same server and host.
121#[derive(Clone, Copy)]
122pub struct CertificateRollover<'a> {
123    /// DER-encoded replacement leaf, obtained out of band.
124    pub replacement_der: &'a [u8],
125    /// Last UTC second in which the original leaf may start a new connection.
126    pub original_valid_until: OffsetDateTime,
127}
128
129impl CertificateRollover<'_> {
130    pub(super) fn validate_length(&self) -> Result<(), ConnectError> {
131        if !(1..=MAX_CREDENTIAL_BYTES).contains(&self.replacement_der.len()) {
132            return Err(InvalidConfiguration(
133                "replacement leaf must contain 1 to 65536 bytes",
134            ));
135        }
136        Ok(())
137    }
138}
139
140struct LeafPin {
141    der: Vec<u8>,
142    not_before: i64,
143    not_after: i64,
144}
145
146impl ConnectionConfig<'_> {
147    /// Validate the endpoint, user, certificate bindings and matching private key locally.
148    /// This performs the same checks as a single-pin connection without dialing or resolving the host.
149    pub fn validate(&self, options: ConnectionOptions<'_>) -> Result<(), ConnectError> {
150        self.prepare(options, true).map(|_| ())
151    }
152
153    fn prepare(
154        &self,
155        options: ConnectionOptions<'_>,
156        require_current: bool,
157    ) -> Result<(LeafPin, Identity, &str), ConnectError> {
158        self.validate_input_lengths()?;
159        options.user_identity.validate()?;
160        let (host, _) = crate::discovery::address(self.endpoint).map_err(|_| {
161            InvalidConfiguration("expected opc.tcp://HOST:PORT with an optional path")
162        })?;
163        let server = application_certificate(
164            self.server_certificate_der,
165            self.server_application_uri,
166            Some(host),
167            require_current,
168        )?;
169        application_certificate(
170            self.client_certificate_der,
171            self.client_application_uri,
172            None,
173            true,
174        )?;
175        if self.client_private_key_der.first() != Some(&0x30) {
176            return Err(InvalidConfiguration(
177                "expected an unencrypted DER client private key",
178            ));
179        }
180
181        let original = LeafPin {
182            der: self.server_certificate_der.to_vec(),
183            not_before: server.validity().not_before.timestamp(),
184            not_after: server.validity().not_after.timestamp(),
185        };
186        let local = Identity::new(self.client_certificate_der, self.client_private_key_der)
187            .map_err(|_| InvalidConfiguration("certificate and RSA private key must match"))?;
188        Ok((original, local, host))
189    }
190
191    pub(super) fn validate_input_lengths(&self) -> Result<(), ConnectError> {
192        if [
193            self.endpoint,
194            self.client_application_uri,
195            self.server_application_uri,
196        ]
197        .iter()
198        .any(|uri| uri.is_empty() || uri.len() > 2048 || uri.chars().any(char::is_control))
199        {
200            return Err(InvalidConfiguration(
201                "endpoint and application URIs must contain 1–2048 bytes",
202            ));
203        }
204        if !(Duration::from_millis(1)..=Duration::from_secs(60)).contains(&self.timeout) {
205            return Err(InvalidConfiguration(
206                "timeout must be between 1 ms and 60 s",
207            ));
208        }
209        for bytes in [
210            self.server_certificate_der,
211            self.client_certificate_der,
212            self.client_private_key_der,
213        ] {
214            if bytes.is_empty() || bytes.len() > MAX_CREDENTIAL_BYTES {
215                return Err(InvalidConfiguration(
216                    "each DER credential must contain 1 to 65536 bytes",
217                ));
218            }
219        }
220        Ok(())
221    }
222}
223
224/// A native OPC UA client connected to one pinned server.
225pub struct Client {
226    pub(super) inner: Arc<Session>,
227    pub(super) server_uri: String,
228    pub(super) reads: tokio::sync::Mutex<super::ReadSession>,
229    pub(super) metadata: tokio::sync::OnceCell<super::ReadMetadata>,
230    pub(super) publish_groups: super::subscription::PublishGroups,
231    pub(super) principal: String,
232    pub(super) subscriptions: tokio::sync::Semaphore,
233}
234
235impl Client {
236    /// Opens a Basic256Sha256 SignAndEncrypt channel and an anonymous user session.
237    ///
238    /// The initial handshake is synchronous. On an async executor, call this method
239    /// on a blocking worker. Each channel establishment checks the pinned server leaf.
240    pub fn connect(config: ConnectionConfig<'_>) -> Result<Self, ConnectError> {
241        Self::connect_with(config, ConnectionOptions::default())
242    }
243
244    /// Open a pinned encrypted session with an explicit policy and user identity.
245    pub fn connect_with(
246        config: ConnectionConfig<'_>,
247        options: ConnectionOptions<'_>,
248    ) -> Result<Self, ConnectError> {
249        Self::connect_pinned(config, options, None)
250    }
251
252    /// Open a pinned session during a planned certificate replacement. New handshakes
253    /// accept the original leaf until the specified deadline, or the replacement within
254    /// its certificate validity period. Both must identify the configured host and URI.
255    pub fn connect_with_rollover(
256        config: ConnectionConfig<'_>,
257        options: ConnectionOptions<'_>,
258        rollover: CertificateRollover<'_>,
259    ) -> Result<Self, ConnectError> {
260        Self::connect_pinned(config, options, Some(rollover))
261    }
262
263    pub(super) fn connect_pinned(
264        config: ConnectionConfig<'_>,
265        options: ConnectionOptions<'_>,
266        rollover: Option<CertificateRollover<'_>>,
267    ) -> Result<Self, ConnectError> {
268        let (mut original, local, host) = config.prepare(options, rollover.is_none())?;
269        let mut leaves = Vec::with_capacity(2);
270        if let Some(rollover) = rollover {
271            rollover.validate_length()?;
272            if rollover.replacement_der == config.server_certificate_der {
273                return Err(InvalidConfiguration(
274                    "replacement and original leaf must differ",
275                ));
276            }
277            let next = application_certificate(
278                rollover.replacement_der,
279                config.server_application_uri,
280                Some(host),
281                false,
282            )?;
283            original.not_after = original
284                .not_after
285                .min(rollover.original_valid_until.unix_timestamp());
286            leaves.push(LeafPin {
287                der: rollover.replacement_der.to_owned(),
288                not_before: next.validity().not_before.timestamp(),
289                not_after: next.validity().not_after.timestamp(),
290            });
291        }
292        leaves.push(original);
293        let now = OffsetDateTime::now_utc().unix_timestamp();
294        leaves.retain(|leaf| (leaf.not_before..=leaf.not_after).contains(&now));
295        let selected = match leaves.as_slice() {
296            [] => {
297                return Err(ConnectError::Connection(
298                    StatusCode::BadCertificateTimeInvalid,
299                ));
300            }
301            [only] => only,
302            overlapping => {
303                // The receiver thumbprint must be known before encrypting the first OPN.
304                // With two eligible leaves discovery selects between the provisioned keys.
305                let endpoints =
306                    crate::discovery::discover_endpoints(config.endpoint, config.timeout)
307                        .map_err(|e| ConnectError::Connection(session::discovery_error(e)))?;
308                overlapping
309                    .iter()
310                    .find(|leaf| {
311                        endpoints.iter().any(|ep| {
312                            ep.security_mode == 3
313                                && ep.security_policy_uri == options.security_policy.uri()
314                                && ep.application_uri == config.server_application_uri
315                                && ep.certificate.starts_with(&leaf.der)
316                        })
317                    })
318                    .ok_or(ConnectError::Connection(
319                        StatusCode::BadCertificateUntrusted,
320                    ))?
321            }
322        };
323        let inner =
324            Session::connect(config, options, local, selected).map_err(ConnectError::Connection)?;
325        Ok(Self {
326            inner: Arc::new(inner),
327            principal: options.user_identity.principal(),
328            subscriptions: tokio::sync::Semaphore::new(8),
329            server_uri: config.server_application_uri.to_owned(),
330            reads: tokio::sync::Mutex::default(),
331            metadata: tokio::sync::OnceCell::new(),
332            publish_groups: Default::default(),
333        })
334    }
335
336    pub(super) fn initial_channel(&self) -> bool {
337        self.inner.is_alive()
338    }
339
340    /// Authenticated contract scope: `anonymous` or `username:<account>`.
341    pub fn principal(&self) -> &str {
342        &self.principal
343    }
344
345    /// Closes the session and stops the client's background driver.
346    pub async fn disconnect(self) {
347        self.inner.disconnect().await;
348    }
349}