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#[derive(Clone, Copy, Default)]
13pub enum UserIdentity<'a> {
14 #[default]
16 Anonymous,
17 Username {
19 username: &'a str,
21 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 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#[derive(Clone, Copy, Default)]
52pub struct ConnectionOptions<'a> {
53 pub security_policy: SecurityPolicy,
55 pub user_identity: UserIdentity<'a>,
57}
58
59const MAX_CREDENTIAL_BYTES: usize = 64 * 1024;
60
61#[derive(Clone, Copy)]
64pub struct ConnectionConfig<'a> {
65 pub endpoint: &'a str,
67 pub server_application_uri: &'a str,
69 pub server_certificate_der: &'a [u8],
71 pub client_application_uri: &'a str,
73 pub client_certificate_der: &'a [u8],
75 pub client_private_key_der: &'a [u8],
77 pub timeout: Duration,
79}
80
81#[derive(Debug)]
83pub enum ConnectError {
84 InvalidConfiguration(&'static str),
86 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#[derive(Clone, Copy)]
122pub struct CertificateRollover<'a> {
123 pub replacement_der: &'a [u8],
125 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 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
224pub 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 pub fn connect(config: ConnectionConfig<'_>) -> Result<Self, ConnectError> {
241 Self::connect_with(config, ConnectionOptions::default())
242 }
243
244 pub fn connect_with(
246 config: ConnectionConfig<'_>,
247 options: ConnectionOptions<'_>,
248 ) -> Result<Self, ConnectError> {
249 Self::connect_pinned(config, options, None)
250 }
251
252 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 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 pub fn principal(&self) -> &str {
342 &self.principal
343 }
344
345 pub async fn disconnect(self) {
347 self.inner.disconnect().await;
348 }
349}