async-opcua-server 0.18.0

OPC UA server API
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
// OPCUA for Rust
// SPDX-License-Identifier: MPL-2.0
// Copyright (C) 2017-2024 Adam Lock

//! Provides configuration settings for the server including serialization and deserialization from file.

use std::{
    collections::BTreeMap,
    path::{Path, PathBuf},
};

use serde::{Deserialize, Serialize};
use tracing::{trace, warn};

use crate::constants;
use opcua_core::{comms::url::url_matches_except_host, config::Config};
use opcua_crypto::{CertificateStore, SecurityPolicy, Thumbprint};
use opcua_types::{
    ApplicationDescription, ApplicationType, DecodingOptions, LocalizedText, MessageSecurityMode,
    UAString,
};

use super::{endpoint::ServerEndpoint, limits::Limits};

/// Token ID for the anonymous user token.
pub const ANONYMOUS_USER_TOKEN_ID: &str = "ANONYMOUS";

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
/// Configuration for the TCP transport.
pub struct TcpConfig {
    /// Timeout for hello on a session in seconds
    pub hello_timeout: u32,
    /// The hostname to supply in the endpoints
    pub host: String,
    /// The port number of the service
    pub port: u16,
}

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone, Default)]
/// User token handled by the default authenticator.
pub struct ServerUserToken {
    /// User name
    pub user: String,
    /// Password
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pass: Option<String>,
    /// X509 file path (as a string)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub x509: Option<String>,
    /// X509 thumbprint.
    #[serde(skip)]
    pub thumbprint: Option<Thumbprint>,
    #[serde(default)]
    /// Access to read diagnostics on the server.
    pub read_diagnostics: bool,
}

impl ServerUserToken {
    /// Create a user pass token
    pub fn user_pass<T>(user: T, pass: T) -> Self
    where
        T: Into<String>,
    {
        ServerUserToken {
            user: user.into(),
            pass: Some(pass.into()),
            x509: None,
            thumbprint: None,
            read_diagnostics: false,
        }
    }

    /// Create an X509 token.
    pub fn x509<T>(user: T, cert_path: &Path) -> Self
    where
        T: Into<String>,
    {
        ServerUserToken {
            user: user.into(),
            pass: None,
            x509: Some(cert_path.to_string_lossy().to_string()),
            thumbprint: None,
            read_diagnostics: false,
        }
    }

    /// Read an X509 user token's certificate from disk and then hold onto the thumbprint for it.
    pub fn read_thumbprint(&mut self) {
        if self.is_x509() && self.thumbprint.is_none() {
            // As part of validation, we're going to try and load the x509 certificate from disk, and
            // obtain its thumbprint. This will be used when a session is activated.
            if let Some(ref x509_path) = self.x509 {
                let path = PathBuf::from(x509_path);
                if let Ok(x509) = CertificateStore::read_cert(&path) {
                    self.thumbprint = Some(x509.thumbprint());
                }
            }
        }
    }

    /// Test if the token is valid. This does not care for x509 tokens if the cert is present on
    /// the disk or not.
    pub fn validate(&self, id: &str) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();
        if id == ANONYMOUS_USER_TOKEN_ID {
            errors.push(format!(
                "User token {id} is invalid because id is a reserved value, use another value."
            ));
        }
        if self.user.is_empty() {
            errors.push(format!("User token {id} has an empty user name."));
        }
        if self.pass.is_some() && self.x509.is_some() {
            errors.push(format!(
                "User token {id} holds a password and certificate info - it cannot be both."
            ));
        } else if self.pass.is_none() && self.x509.is_none() {
            errors.push(format!(
                "User token {id} fails to provide a password or certificate info."
            ));
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Return `true` if this token is for username/password auth.
    pub fn is_user_pass(&self) -> bool {
        self.x509.is_none()
    }

    /// Return `true` if this token is for X509-based auth.
    pub fn is_x509(&self) -> bool {
        self.x509.is_some()
    }

    /// Set the ability for the user to read diagnostics on the server.
    pub fn read_diagnostics(mut self, read: bool) -> Self {
        self.read_diagnostics = read;
        self
    }
}

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
/// Configuration for certificate validation.
pub struct CertificateValidation {
    /// Auto trusts client certificates. For testing/samples only unless you're sure what you're
    /// doing.
    pub trust_client_certs: bool,
    /// Check the valid from/to fields of a certificate
    pub check_time: bool,
}

impl Default for CertificateValidation {
    fn default() -> Self {
        Self {
            trust_client_certs: false,
            check_time: true,
        }
    }
}

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
/// Server configuration object.
pub struct ServerConfig {
    /// An id for this server
    pub application_name: String,
    /// A description for this server
    pub application_uri: String,
    /// Product url
    pub product_uri: String,
    /// Autocreates public / private keypair if they don't exist. For testing/samples only
    /// since you do not have control of the values
    #[serde(default)]
    pub create_sample_keypair: bool,
    /// Path to a custom certificate, to be used instead of the default .der certificate
    #[serde(default)]
    pub certificate_path: Option<PathBuf>,
    /// Path to a custom private key, to be used instead of the default private key
    #[serde(default)]
    pub private_key_path: Option<PathBuf>,
    /// Checks the certificate's time validity
    #[serde(default)]
    pub certificate_validation: CertificateValidation,
    /// PKI folder, either absolute or relative to executable
    pub pki_dir: PathBuf,
    /// Url to a discovery server - adding this string causes the server to assume you wish to
    /// register the server with a discovery server.
    #[serde(default)]
    pub discovery_server_url: Option<String>,
    /// tcp configuration information
    pub tcp_config: TcpConfig,
    /// Server OPA UA limits
    #[serde(default)]
    pub limits: Limits,
    /// Supported locale ids
    #[serde(default)]
    pub locale_ids: Vec<String>,
    /// User tokens
    pub user_tokens: BTreeMap<String, ServerUserToken>,
    /// discovery endpoint url which may or may not be the same as the service endpoints below.
    pub discovery_urls: Vec<String>,
    /// Default endpoint id
    #[serde(default)]
    pub default_endpoint: Option<String>,
    /// Endpoints supported by the server
    pub endpoints: BTreeMap<String, ServerEndpoint>,
    /// Interval in milliseconds between each time the subscriptions are polled.
    #[serde(default = "defaults::subscription_poll_interval_ms")]
    pub subscription_poll_interval_ms: u64,
    /// Default publish request timeout.
    #[serde(default = "defaults::publish_timeout_default_ms")]
    pub publish_timeout_default_ms: u64,
    /// Max message timeout for non-publish requests.
    /// Will not be applied for requests that are handled synchronously.
    /// Set to 0 for no timeout, meaning that a timeout will only be applied if
    /// the client requests one.
    /// If this is greater than zero and the client requests a timeout of 0,
    /// this will be used.
    #[serde(default = "defaults::max_timeout_ms")]
    pub max_timeout_ms: u32,
    /// Maximum lifetime of secure channel tokens. The client will request a number,
    /// this just sets an upper limit on that value.
    /// Note that there is no lower limit, if a client sets an expiry of 0,
    /// we will just instantly time out.
    #[serde(default = "defaults::max_secure_channel_token_lifetime_ms")]
    pub max_secure_channel_token_lifetime_ms: u32,
    /// Maximum time before a session will be timed out. The client will request
    /// a number, this just sets the upper limit on that value.
    /// Note that there is no lower limit, if a client sets an expiry of 0
    /// we will instantly time out.
    #[serde(default = "defaults::max_session_timeout_ms")]
    pub max_session_timeout_ms: u64,
    /// Enable server diagnostics.
    #[serde(default)]
    pub diagnostics: bool,
    /// Length of the nonce generated for CreateSession responses.
    #[serde(default = "defaults::session_nonce_length")]
    pub session_nonce_length: usize,
    /// Delay in milliseconds before attempting to connect to a reverse connect target,
    /// if the previous attempt failed.
    #[serde(default = "defaults::reverse_connect_failure_delay_ms")]
    pub reverse_connect_failure_delay_ms: u64,
}

mod defaults {
    use crate::constants;

    pub(super) fn subscription_poll_interval_ms() -> u64 {
        constants::SUBSCRIPTION_TIMER_RATE_MS
    }

    pub(super) fn publish_timeout_default_ms() -> u64 {
        constants::DEFAULT_PUBLISH_TIMEOUT_MS
    }

    pub(super) fn max_timeout_ms() -> u32 {
        300_000
    }

    pub(super) fn max_secure_channel_token_lifetime_ms() -> u32 {
        300_000
    }

    pub(super) fn max_session_timeout_ms() -> u64 {
        constants::MAX_SESSION_TIMEOUT
    }

    pub(super) fn session_nonce_length() -> usize {
        32
    }

    pub(super) fn reverse_connect_failure_delay_ms() -> u64 {
        30_000
    }
}

impl Config for ServerConfig {
    fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();
        if self.application_name.is_empty() {
            warn!("No application was set");
        }
        if self.application_uri.is_empty() {
            warn!("No application uri was set");
        }
        if self.product_uri.is_empty() {
            warn!("No product uri was set");
        }
        if self.endpoints.is_empty() {
            errors.push("Server configuration is invalid. It defines no endpoints".to_owned());
        }
        for (id, endpoint) in &self.endpoints {
            if let Err(e) = endpoint.validate(id, &self.user_tokens) {
                errors.push(format!(
                    "Endpoint {id} failed to validate: {}",
                    e.join(", ")
                ));
            }
        }
        if let Some(ref default_endpoint) = self.default_endpoint {
            if !self.endpoints.contains_key(default_endpoint) {
                errors.push(format!(
                    "Endpoints does not contain default endpoint {default_endpoint}"
                ));
            }
        }
        for (id, user_token) in &self.user_tokens {
            if let Err(e) = user_token.validate(id) {
                errors.push(format!(
                    "User token {id} failed to validate: {}",
                    e.join(", ")
                ))
            }
        }
        if self.limits.max_array_length == 0 {
            errors.push("Server configuration is invalid. Max array length is invalid".to_owned());
        }
        if self.limits.max_string_length == 0 {
            errors.push("Server configuration is invalid. Max string length is invalid".to_owned());
        }
        if self.limits.max_byte_string_length == 0 {
            errors.push(
                "Server configuration is invalid. Max byte string length is invalid".to_owned(),
            );
        }
        if self.discovery_urls.is_empty() {
            errors.push("Server configuration is invalid. Discovery urls not set".to_owned());
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    fn application_name(&self) -> UAString {
        UAString::from(&self.application_name)
    }

    fn application_uri(&self) -> UAString {
        UAString::from(&self.application_uri)
    }

    fn product_uri(&self) -> UAString {
        UAString::from(&self.product_uri)
    }

    fn application_type(&self) -> ApplicationType {
        ApplicationType::Server
    }

    fn discovery_urls(&self) -> Option<Vec<UAString>> {
        let discovery_urls: Vec<UAString> =
            self.discovery_urls.iter().map(UAString::from).collect();
        Some(discovery_urls)
    }

    fn application_description(&self) -> ApplicationDescription {
        ApplicationDescription {
            application_uri: self.application_uri(),
            application_name: LocalizedText::new("", self.application_name().as_ref()),
            application_type: self.application_type(),
            product_uri: self.product_uri(),
            gateway_server_uri: UAString::null(),
            discovery_profile_uri: UAString::null(),
            discovery_urls: self.discovery_urls(),
        }
    }
}

impl Default for ServerConfig {
    fn default() -> Self {
        let mut pki_dir = std::env::current_dir().unwrap();
        pki_dir.push(Self::PKI_DIR);

        ServerConfig {
            application_name: String::new(),
            application_uri: String::new(),
            product_uri: String::new(),
            create_sample_keypair: false,
            certificate_path: None,
            private_key_path: None,
            pki_dir,
            certificate_validation: CertificateValidation::default(),
            discovery_server_url: None,
            tcp_config: TcpConfig {
                host: "127.0.0.1".to_string(),
                port: constants::DEFAULT_RUST_OPC_UA_SERVER_PORT,
                hello_timeout: constants::DEFAULT_HELLO_TIMEOUT_SECONDS,
            },
            limits: Limits::default(),
            user_tokens: BTreeMap::new(),
            locale_ids: vec!["en".to_string()],
            discovery_urls: Vec::new(),
            default_endpoint: None,
            endpoints: BTreeMap::new(),
            subscription_poll_interval_ms: defaults::subscription_poll_interval_ms(),
            publish_timeout_default_ms: defaults::publish_timeout_default_ms(),
            max_timeout_ms: defaults::max_timeout_ms(),
            max_secure_channel_token_lifetime_ms: defaults::max_secure_channel_token_lifetime_ms(),
            max_session_timeout_ms: defaults::max_session_timeout_ms(),
            diagnostics: false,
            session_nonce_length: defaults::session_nonce_length(),
            reverse_connect_failure_delay_ms: defaults::reverse_connect_failure_delay_ms(),
        }
    }
}

impl ServerConfig {
    /// The default PKI directory
    pub const PKI_DIR: &'static str = "pki";

    /// Create a new default server config with the given list
    /// of user tokens and endpoints.
    pub fn new<T>(
        application_name: T,
        user_tokens: BTreeMap<String, ServerUserToken>,
        endpoints: BTreeMap<String, ServerEndpoint>,
    ) -> Self
    where
        T: Into<String>,
    {
        let host = "127.0.0.1".to_string();
        let port = constants::DEFAULT_RUST_OPC_UA_SERVER_PORT;

        let application_name = application_name.into();
        let application_uri = format!("urn:{application_name}");
        let product_uri = format!("urn:{application_name}");
        let discovery_server_url = Some(constants::DEFAULT_DISCOVERY_SERVER_URL.to_string());
        let discovery_urls = vec![format!("opc.tcp://{}:{}/", host, port)];
        let locale_ids = vec!["en".to_string()];

        let mut pki_dir = std::env::current_dir().unwrap();
        pki_dir.push(Self::PKI_DIR);

        ServerConfig {
            application_name,
            application_uri,
            product_uri,
            certificate_validation: CertificateValidation {
                trust_client_certs: false,
                check_time: true,
            },
            pki_dir,
            discovery_server_url,
            tcp_config: TcpConfig {
                host,
                port,
                hello_timeout: constants::DEFAULT_HELLO_TIMEOUT_SECONDS,
            },
            locale_ids,
            user_tokens,
            discovery_urls,
            endpoints,
            ..Default::default()
        }
    }

    /// Decoding options given by this config.
    pub fn decoding_options(&self) -> DecodingOptions {
        DecodingOptions {
            client_offset: chrono::Duration::zero(),
            max_message_size: self.limits.max_message_size,
            max_chunk_count: self.limits.max_chunk_count,
            max_string_length: self.limits.max_string_length,
            max_byte_string_length: self.limits.max_byte_string_length,
            max_array_length: self.limits.max_array_length,
            ..Default::default()
        }
    }

    /// Add an endpoint to the server config.
    pub fn add_endpoint(&mut self, id: &str, endpoint: ServerEndpoint) {
        self.endpoints.insert(id.to_string(), endpoint);
    }

    /// Get x509 thumbprints from registered server user tokens.
    pub fn read_x509_thumbprints(&mut self) {
        self.user_tokens
            .iter_mut()
            .for_each(|(_, token)| token.read_thumbprint());
    }

    /// Find the default endpoint
    pub fn default_endpoint(&self) -> Option<&ServerEndpoint> {
        if let Some(ref default_endpoint) = self.default_endpoint {
            self.endpoints.get(default_endpoint)
        } else {
            None
        }
    }

    /// Find the first endpoint that matches the specified url, security policy and message
    /// security mode.
    pub fn find_endpoint(
        &self,
        endpoint_url: &str,
        base_endpoint_url: &str,
        security_policy: SecurityPolicy,
        security_mode: MessageSecurityMode,
    ) -> Option<&ServerEndpoint> {
        let endpoint = self.endpoints.iter().find(|&(_, e)| {
            // Test end point's security_policy_uri and matching url
            if url_matches_except_host(&e.endpoint_url(base_endpoint_url), endpoint_url) {
                if e.security_policy() == security_policy
                    && e.message_security_mode() == security_mode
                {
                    trace!("Found matching endpoint for url {} - {:?}", endpoint_url, e);
                    true
                } else {
                    false
                }
            } else {
                false
            }
        });
        endpoint.map(|endpoint| endpoint.1)
    }
}