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
// OPCUA for Rust

// SPDX-License-Identifier: MPL-2.0

// Copyright (C) 2017-2020 Adam Lock


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

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::str::FromStr;

use opcua_core::{
    comms::url::url_matches_except_host,
    config::Config,
};
use opcua_crypto::{CertificateStore, SecurityPolicy, Thumbprint};
use opcua_types::{
    constants as opcua_types_constants, DecodingLimits, MessageSecurityMode,
    service_types::ApplicationType,
    UAString,
};

use crate::constants;

pub const ANONYMOUS_USER_TOKEN_ID: &str = "ANONYMOUS";

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
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)]
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>,
    #[serde(skip)]
    pub thumbprint: Option<Thumbprint>,
}

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,
        }
    }

    /// Create an X509 token.

    pub fn x509<T>(user: T, cert_path: &PathBuf) -> Self where T: Into<String> {
        ServerUserToken {
            user: user.into(),
            pass: None,
            x509: Some(cert_path.to_string_lossy().to_string()),
            thumbprint: None,
        }
    }

    /// 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 is_valid(&self, id: &str) -> bool {
        let mut valid = true;
        if id == ANONYMOUS_USER_TOKEN_ID {
            error!("User token {} is invalid because id is a reserved value, use another value.", id);
            valid = false;
        }
        if self.user.is_empty() {
            error!("User token {} has an empty user name.", id);
            valid = false;
        }
        if self.pass.is_some() && self.x509.is_some() {
            error!("User token {} holds a password and certificate info - it cannot be both.", id);
            valid = false;
        } else if self.pass.is_none() && self.x509.is_none() {
            error!("User token {} fails to provide a password or certificate info.", id);
            valid = false;
        }
        valid
    }

    pub fn is_user_pass(&self) -> bool {
        self.x509.is_none()
    }

    pub fn is_x509(&self) -> bool {
        self.x509.is_some()
    }
}

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct ServerLimits {
    /// Indicates if clients are able to modify the address space through the node management service

    /// set. This is a very broad flag and is likely to require more fine grained per user control

    /// in a later revision. By default, this value is `false`

    pub clients_can_modify_address_space: bool,
    /// Maximum number of subscriptions in a session, 0 for no limit

    pub max_subscriptions: u32,
    /// Maximum number of monitored items per subscription, 0 for no limit

    pub max_monitored_items_per_sub: u32,
    /// Max array length in elements

    pub max_array_length: u32,
    /// Max string length in characters

    pub max_string_length: u32,
    /// Max bytestring length in bytes

    pub max_byte_string_length: u32,
    /// Specifies the minimum sampling interval for this server in seconds.

    pub min_sampling_interval: f64,
    /// Specifies the minimum publishing interval for this server in seconds.

    pub min_publishing_interval: f64,
}

impl Default for ServerLimits {
    fn default() -> Self {
        Self {
            max_array_length: opcua_types_constants::MAX_ARRAY_LENGTH as u32,
            max_string_length: opcua_types_constants::MAX_STRING_LENGTH as u32,
            max_byte_string_length: opcua_types_constants::MAX_BYTE_STRING_LENGTH as u32,
            max_subscriptions: constants::DEFAULT_MAX_SUBSCRIPTIONS,
            max_monitored_items_per_sub: constants::DEFAULT_MAX_MONITORED_ITEMS_PER_SUB,
            clients_can_modify_address_space: false,
            min_sampling_interval: constants::MIN_SAMPLING_INTERVAL,
            min_publishing_interval: constants::MIN_PUBLISHING_INTERVAL,
        }
    }
}

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct ServerEndpoint {
    /// Endpoint path

    pub path: String,
    /// Security policy

    pub security_policy: String,
    /// Security mode

    pub security_mode: String,
    /// Security level, higher being more secure

    pub security_level: u8,
    /// Password security policy when a client supplies a user name identity token

    pub password_security_policy: Option<String>,
    /// User tokens

    pub user_token_ids: BTreeSet<String>,
}

/// Convenience method to make an endpoint from a tuple

impl<'a> From<(&'a str, SecurityPolicy, MessageSecurityMode, &'a [&'a str])> for ServerEndpoint {
    fn from(v: (&'a str, SecurityPolicy, MessageSecurityMode, &'a [&'a str])) -> ServerEndpoint {
        ServerEndpoint {
            path: v.0.into(),
            security_policy: v.1.to_string(),
            security_mode: v.2.to_string(),
            security_level: Self::security_level(v.1, v.2),
            password_security_policy: None,
            user_token_ids: v.3.iter().map(|id| id.to_string()).collect(),
        }
    }
}

impl ServerEndpoint {
    pub fn new<T>(path: T, security_policy: SecurityPolicy, security_mode: MessageSecurityMode, user_token_ids: &[String]) -> Self where T: Into<String> {
        ServerEndpoint {
            path: path.into(),
            security_policy: security_policy.to_string(),
            security_mode: security_mode.to_string(),
            security_level: Self::security_level(security_policy, security_mode),
            password_security_policy: None,
            user_token_ids: user_token_ids.iter().map(|id| id.clone()).collect(),
        }
    }

    /// Recommends a security level for the supplied security policy

    fn security_level(security_policy: SecurityPolicy, security_mode: MessageSecurityMode) -> u8 {
        let security_level = match security_policy {
            SecurityPolicy::Basic128Rsa15 => 1,
            SecurityPolicy::Aes128Sha256RsaOaep => 2,
            SecurityPolicy::Basic256 => 3,
            SecurityPolicy::Basic256Sha256 => 4,
            SecurityPolicy::Aes256Sha256RsaPss => 5,
            _ => 0
        };
        if security_mode == MessageSecurityMode::SignAndEncrypt {
            security_level + 10
        } else {
            security_level
        }
    }

    pub fn new_none<T>(path: T, user_token_ids: &[String]) -> Self where T: Into<String> {
        Self::new(path, SecurityPolicy::None, MessageSecurityMode::None, user_token_ids)
    }

    pub fn new_basic128rsa15_sign<T>(path: T, user_token_ids: &[String]) -> Self where T: Into<String> {
        Self::new(path, SecurityPolicy::Basic128Rsa15, MessageSecurityMode::Sign, user_token_ids)
    }

    pub fn new_basic128rsa15_sign_encrypt<T>(path: T, user_token_ids: &[String]) -> Self where T: Into<String> {
        Self::new(path, SecurityPolicy::Basic128Rsa15, MessageSecurityMode::SignAndEncrypt, user_token_ids)
    }

    pub fn new_basic256_sign<T>(path: T, user_token_ids: &[String]) -> Self where T: Into<String> {
        Self::new(path, SecurityPolicy::Basic256, MessageSecurityMode::Sign, user_token_ids)
    }

    pub fn new_basic256_sign_encrypt<T>(path: T, user_token_ids: &[String]) -> Self where T: Into<String> {
        Self::new(path, SecurityPolicy::Basic256, MessageSecurityMode::SignAndEncrypt, user_token_ids)
    }

    pub fn new_basic256sha256_sign<T>(path: T, user_token_ids: &[String]) -> Self where T: Into<String> {
        Self::new(path, SecurityPolicy::Basic256Sha256, MessageSecurityMode::Sign, user_token_ids)
    }

    pub fn new_basic256sha256_sign_encrypt<T>(path: T, user_token_ids: &[String]) -> Self where T: Into<String> {
        Self::new(path, SecurityPolicy::Basic256Sha256, MessageSecurityMode::SignAndEncrypt, user_token_ids)
    }

    pub fn new_aes128_sha256_rsaoaep_sign<T>(path: T, user_token_ids: &[String]) -> Self where T: Into<String> {
        Self::new(path, SecurityPolicy::Aes128Sha256RsaOaep, MessageSecurityMode::Sign, user_token_ids)
    }

    pub fn new_aes128_sha256_rsaoaep_sign_encrypt<T>(path: T, user_token_ids: &[String]) -> Self where T: Into<String> {
        Self::new(path, SecurityPolicy::Aes128Sha256RsaOaep, MessageSecurityMode::SignAndEncrypt, user_token_ids)
    }

    pub fn new_aes256_sha256_rsapss_sign<T>(path: T, user_token_ids: &[String]) -> Self where T: Into<String> {
        Self::new(path, SecurityPolicy::Aes256Sha256RsaPss, MessageSecurityMode::Sign, user_token_ids)
    }

    pub fn new_aes256_sha256_rsapss_sign_encrypt<T>(path: T, user_token_ids: &[String]) -> Self where T: Into<String> {
        Self::new(path, SecurityPolicy::Aes256Sha256RsaPss, MessageSecurityMode::SignAndEncrypt, user_token_ids)
    }

    pub fn is_valid(&self, id: &str, user_tokens: &BTreeMap<String, ServerUserToken>) -> bool {
        let mut valid = true;

        // Validate that the user token ids exist

        for id in &self.user_token_ids {
            // Skip anonymous

            if id == ANONYMOUS_USER_TOKEN_ID {
                continue;
            }
            if !user_tokens.contains_key(id) {
                error!("Cannot find user token with id {}", id);
                valid = false;
            }
        }

        if let Some(ref password_security_policy) = self.password_security_policy {
            let password_security_policy = SecurityPolicy::from_str(password_security_policy).unwrap();
            if password_security_policy == SecurityPolicy::Unknown {
                error!("Endpoint {} is invalid. Password security policy \"{}\" is invalid. Valid values are None, Basic128Rsa15, Basic256, Basic256Sha256", id, password_security_policy);
                valid = false;
            }
        }

        // Validate the security policy and mode

        let security_policy = SecurityPolicy::from_str(&self.security_policy).unwrap();
        let security_mode = MessageSecurityMode::from(self.security_mode.as_ref());
        if security_policy == SecurityPolicy::Unknown {
            error!("Endpoint {} is invalid. Security policy \"{}\" is invalid. Valid values are None, Basic128Rsa15, Basic256, Basic256Sha256, Aes128Sha256RsaOaep, Aes256Sha256RsaPss,", id, self.security_policy);
            valid = false;
        } else if security_mode == MessageSecurityMode::Invalid {
            error!("Endpoint {} is invalid. Security mode \"{}\" is invalid. Valid values are None, Sign, SignAndEncrypt", id, self.security_mode);
            valid = false;
        } else if (security_policy == SecurityPolicy::None && security_mode != MessageSecurityMode::None) ||
            (security_policy != SecurityPolicy::None && security_mode == MessageSecurityMode::None) {
            error!("Endpoint {} is invalid. Security policy and security mode must both contain None or neither of them should (1).", id);
            valid = false;
        } else if security_policy != SecurityPolicy::None && security_mode == MessageSecurityMode::None {
            error!("Endpoint {} is invalid. Security policy and security mode must both contain None or neither of them should (2).", id);
            valid = false;
        }
        valid
    }

    pub fn security_policy(&self) -> SecurityPolicy {
        SecurityPolicy::from_str(&self.security_policy).unwrap()
    }

    pub fn message_security_mode(&self) -> MessageSecurityMode {
        MessageSecurityMode::from(self.security_mode.as_ref())
    }

    pub fn endpoint_url(&self, base_endpoint: &str) -> String {
        format!("{}{}", base_endpoint, self.path)
    }

    /// Returns the effective password security policy for the endpoint. This is the explicitly set password

    /// security policy, or just the regular security policy.

    pub fn password_security_policy(&self) -> SecurityPolicy {
        let mut password_security_policy = self.security_policy();
        if let Some(ref security_policy) = self.password_security_policy {
            match SecurityPolicy::from_str(security_policy).unwrap() {
                SecurityPolicy::Unknown => {
                    panic!("Password security policy {} is unrecognized", security_policy);
                }
                security_policy => {
                    password_security_policy = security_policy;
                }
            }
        }
        password_security_policy
    }

    /// Test if the endpoint supports anonymous users

    pub fn supports_anonymous(&self) -> bool {
        self.supports_user_token_id(ANONYMOUS_USER_TOKEN_ID)
    }

    /// Tests if this endpoint supports user pass tokens. It does this by looking to see

    /// if any of the users allowed to access this endpoint are user pass users.

    pub fn supports_user_pass(&self, server_tokens: &BTreeMap<String, ServerUserToken>) -> bool {
        for user_token_id in &self.user_token_ids {
            if user_token_id != ANONYMOUS_USER_TOKEN_ID {
                if let Some(user_token) = server_tokens.get(user_token_id) {
                    if user_token.is_user_pass() {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Tests if this endpoint supports x509 tokens.  It does this by looking to see

    /// if any of the users allowed to access this endpoint are x509 users.

    pub fn supports_x509(&self, server_tokens: &BTreeMap<String, ServerUserToken>) -> bool {
        for user_token_id in &self.user_token_ids {
            if user_token_id != ANONYMOUS_USER_TOKEN_ID {
                if let Some(user_token) = server_tokens.get(user_token_id) {
                    if user_token.is_x509() {
                        return true;
                    }
                }
            }
        }
        false
    }

    pub fn supports_user_token_id(&self, id: &str) -> bool {
        self.user_token_ids.contains(id)
    }
}

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
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,
    /// pki folder, either absolute or relative to executable

    pub pki_dir: PathBuf,
    /// Autocreates public / private keypair if they don't exist. For testing/samples only

    /// since you do not have control of the values

    pub create_sample_keypair: bool,
    /// Auto trusts client certificates. For testing/samples only unless you're sure what you're

    /// doing.

    pub trust_client_certs: bool,
    /// Url to a discovery server - adding this string causes the server to assume you wish to

    /// register the server with a discovery server.

    pub discovery_server_url: Option<String>,
    /// tcp configuration information

    pub tcp_config: TcpConfig,
    /// Server limits

    pub limits: ServerLimits,
    /// Supported locale ids

    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

    pub default_endpoint: Option<String>,
    /// Endpoints supported by the server

    pub endpoints: BTreeMap<String, ServerEndpoint>,
}

impl Config for ServerConfig {
    fn is_valid(&self) -> bool {
        let mut valid = true;
        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() {
            error!("Server configuration is invalid. It defines no endpoints");
            valid = false;
        }
        for (id, endpoint) in &self.endpoints {
            if !endpoint.is_valid(&id, &self.user_tokens) {
                valid = false;
            }
        }
        if let Some(ref default_endpoint) = self.default_endpoint {
            if !self.endpoints.contains_key(default_endpoint) {
                valid = false;
            }
        }
        for (id, user_token) in &self.user_tokens {
            if !user_token.is_valid(&id) {
                valid = false;
            }
        }
        if self.limits.max_array_length == 0 {
            error!("Server configuration is invalid. Max array length is invalid");
            valid = false;
        }
        if self.limits.max_string_length == 0 {
            error!("Server configuration is invalid. Max string length is invalid");
            valid = false;
        }
        if self.limits.max_byte_string_length == 0 {
            error!("Server configuration is invalid. Max byte string length is invalid");
            valid = false;
        }
        if self.discovery_urls.is_empty() {
            error!("Server configuration is invalid. Discovery urls not set");
            valid = false;
        }
        valid
    }

    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(|v| UAString::from(v)).collect();
        Some(discovery_urls)
    }
}

impl Default for ServerConfig {
    fn default() -> Self {
        let pki_dir = PathBuf::from("./pki");
        ServerConfig {
            application_name: String::new(),
            application_uri: String::new(),
            product_uri: String::new(),
            pki_dir,
            create_sample_keypair: false,
            trust_client_certs: false,
            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: ServerLimits::default(),
            user_tokens: BTreeMap::new(),
            locale_ids: vec!["en".to_string()],
            discovery_urls: Vec::new(),
            default_endpoint: None,
            endpoints: BTreeMap::new(),
        }
    }
}

impl ServerConfig {
    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 pki_dir = PathBuf::from("./pki");
        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()];

        ServerConfig {
            application_name,
            application_uri,
            product_uri,
            pki_dir,
            create_sample_keypair: false,
            trust_client_certs: false,
            discovery_server_url,
            tcp_config: TcpConfig {
                host,
                port,
                hello_timeout: constants::DEFAULT_HELLO_TIMEOUT_SECONDS,
            },
            limits: ServerLimits::default(),
            locale_ids,
            user_tokens,
            discovery_urls,
            default_endpoint: None,
            endpoints,
        }
    }

    pub fn decoding_limits(&self) -> DecodingLimits {
        DecodingLimits {
            max_chunk_size: 0,
            max_string_length: self.limits.max_string_length as usize,
            max_byte_string_length: self.limits.max_byte_string_length as usize,
            max_array_length: self.limits.max_array_length as usize,
        }
    }

    pub fn add_endpoint(&mut self, id: &str, endpoint: ServerEndpoint) {
        self.endpoints.insert(id.to_string(), endpoint);
    }

    pub fn read_x509_thumbprints(&mut self) {
        self.user_tokens.iter_mut().for_each(|(_, token)| token.read_thumbprint());
    }

    /// Returns a opc.tcp://server:port url that paths can be appended onto

    pub fn base_endpoint_url(&self) -> String {
        format!("opc.tcp://{}:{}", self.tcp_config.host, self.tcp_config.port)
    }

    /// 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, security_policy: SecurityPolicy, security_mode: MessageSecurityMode) -> Option<&ServerEndpoint> {
        let base_endpoint_url = self.base_endpoint_url();
        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)
    }
}