tiberius 0.13.0

A TDS (MSSQL) driver
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
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
578
579
580
use super::{ConfigString, ServerDefinition};
use crate::error::Error;
use connection_string::JdbcString;
use std::str::FromStr;

pub(crate) struct JdbcConfig {
    config: JdbcString,
}

impl FromStr for JdbcConfig {
    type Err = Error;

    fn from_str(s: &str) -> crate::Result<Self> {
        let config = s.parse().map_err(|e| {
            super::connection_string_error(
                e,
                "wrap the value in braces (e.g. `password={p@ss;word}`); single \
                 and double quotes are ordinary characters in JDBC, not escapes",
                "Config::from_jdbc_string",
            )
        })?;
        Ok(Self { config })
    }
}

impl ConfigString for JdbcConfig {
    fn dict(&self) -> &std::collections::HashMap<String, String> {
        self.config.properties()
    }

    fn server(&self) -> crate::Result<ServerDefinition> {
        let def = ServerDefinition {
            host: self.config.server_name().map(|s| s.to_string()),
            port: self.config.port(),
            instance: self.config.instance_name().map(|s| s.to_string()),
        };

        Ok(def)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::AuthMethod;

    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    use crate::EncryptionLevel;

    #[test]
    fn server_parsing_no_browser() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200";
        let jdbc: JdbcConfig = test_str.parse()?;
        let server = jdbc.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(4200), server.port);
        assert_eq!(None, server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_no_jdbc_no_browser() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200";
        let jdbc: JdbcConfig = test_str.parse()?;
        let server = jdbc.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(4200), server.port);
        assert_eq!(None, server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_with_browser() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com\\TIBERIUS";
        let jdbc: JdbcConfig = test_str.parse()?;
        let server = jdbc.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(None, server.port);
        assert_eq!(Some("TIBERIUS".to_string()), server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_with_browser_and_port() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com\\TIBERIUS:666";
        let jdbc: JdbcConfig = test_str.parse()?;
        let server = jdbc.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(666), server.port);
        assert_eq!(Some("TIBERIUS".to_string()), server.instance);

        Ok(())
    }

    #[test]
    fn database_parsing() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://myserver.com:4200;database=Foo";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(Some("Foo".to_string()), jdbc.database());

        let test_str = "jdbc:sqlserver://myserver.com:4200;databaseName=Foo";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(Some("Foo".to_string()), jdbc.database());

        let test_str = "jdbc:sqlserver://myserver.com:4200;Initial Catalog=Foo";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(Some("Foo".to_string()), jdbc.database());

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_true() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;TrustServerCertificate=true;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert!(jdbc.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_false() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;TrustServerCertificate=false;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert!(!jdbc.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_yes() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;TrustServerCertificate=yes;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert!(jdbc.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_no() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;TrustServerCertificate=no;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert!(!jdbc.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_missing() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert!(!jdbc.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_faulty() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;TrustServerCertificate=musti;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert!(jdbc.trust_cert().is_err());

        Ok(())
    }

    #[test]
    fn trust_cert_ca_parsing_ok() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;TrustServerCertificateCA=someca.crt;";
        let ado: JdbcConfig = test_str.parse()?;

        assert_eq!(Some("someca.crt".to_string()), ado.trust_cert_ca());

        Ok(())
    }

    #[test]
    fn parsing_sql_server_authentication() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;User ID=Musti;pwd=Naukio;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(
            AuthMethod::sql_server("Musti", "Naukio"),
            jdbc.authentication()?
        );

        Ok(())
    }

    #[test]
    #[cfg(windows)]
    fn parsing_sspi_authentication() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;IntegratedSecurity=SSPI;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(AuthMethod::Integrated, jdbc.authentication()?);

        Ok(())
    }

    #[test]
    #[cfg(all(feature = "integrated-auth-gssapi", unix))]
    fn parsing_sspi_authentication() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;IntegratedSecurity=true;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(AuthMethod::Integrated, jdbc.authentication()?);

        Ok(())
    }

    #[test]
    #[cfg(windows)]
    fn parsing_windows_authentication() -> crate::Result<()> {
        let test_str =
            "jdbc:sqlserver://my-server.com:4200;uid=Musti;pwd=Naukio;IntegratedSecurity=SSPI;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(
            AuthMethod::windows("Musti", "Naukio"),
            jdbc.authentication()?
        );

        Ok(())
    }

    #[test]
    fn parsing_database() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;database=Cats;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(Some("Cats".to_string()), jdbc.database());

        Ok(())
    }

    #[test]
    fn parsing_login_credentials_escaping() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;User ID=musti;Password={abc;}}45}";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(
            AuthMethod::sql_server("musti", "abc;}45}"),
            jdbc.authentication()?
        );

        Ok(())
    }

    #[test]
    fn parsing_password_special_characters() -> crate::Result<()> {
        // (value as written after `Password=`, exact parsed password). Unlike
        // ADO.NET, the JDBC parser only supports brace (`{...}`) quoting — not
        // single or double quotes — so `'` and `"` are ordinary characters.
        let cases: &[(&str, &str)] = &[
            // Braces are required for structural characters.
            ("{a;b}", "a;b"),
            ("{a=b}", "a=b"),
            ("{a:b}", "a:b"),
            ("{a b}", "a b"),
            ("{a$b}", "a$b"),
            ("{a'b}", "a'b"),
            ("{a\"b}", "a\"b"),
            // `\`, `/`, `[` and `]` are structural in JDBC values and need
            // braces (they would otherwise terminate the value).
            ("{a\\b}", "a\\b"),
            ("{a/b}", "a/b"),
            ("{a[b]}", "a[b]"),
            // Non-structural characters pass through unquoted, including `}`,
            // `'` and `"` (which are not special to the JDBC parser).
            ("a$b", "a$b"),
            ("a@b", "a@b"),
            ("a!b", "a!b"),
            ("a#b", "a#b"),
            ("a%b", "a%b"),
            ("a&b", "a&b"),
            ("a,b", "a,b"),
            ("a'b", "a'b"),
            ("a\"b", "a\"b"),
            ("a}b", "a}b"),
            ("a b", "a b"),
            // Percent-encoding is NOT decoded: `%24` stays literal.
            ("a%24b", "a%24b"),
        ];

        for (value, expected) in cases {
            let s = format!("jdbc:sqlserver://host.com:1433;User ID=sa;Password={value}");
            let jdbc: JdbcConfig = s.parse()?;
            assert_eq!(
                AuthMethod::sql_server("sa", *expected),
                jdbc.authentication()?,
                "value `{value}` should parse to password `{expected}`"
            );
        }

        Ok(())
    }

    #[test]
    fn parsing_password_preserves_surrounding_whitespace() -> crate::Result<()> {
        // Unlike the ADO parser, JDBC does not trim; braced whitespace is kept.
        let jdbc: JdbcConfig =
            "jdbc:sqlserver://host.com:1433;User ID=sa;Password={ a }".parse()?;
        assert_eq!(AuthMethod::sql_server("sa", " a "), jdbc.authentication()?);

        Ok(())
    }

    #[test]
    fn parsing_password_brace_cannot_hold_close_brace() -> crate::Result<()> {
        // Like ADO.NET, JDBC brace quoting has no `}}` doubling: the brace
        // closes at the first `}`, so the inner `}` is consumed as the
        // terminator. Since JDBC has no quote escaping, a value needing braces
        // that also contains `}` cannot be represented — document the limit.
        let jdbc: JdbcConfig =
            "jdbc:sqlserver://host.com:1433;User ID=sa;Password={a}b}".parse()?;
        assert_eq!(AuthMethod::sql_server("sa", "ab}"), jdbc.authentication()?);

        Ok(())
    }

    #[test]
    fn parsing_password_non_ascii_is_rejected() {
        // The JDBC parser only accepts ASCII, in every position; non-ASCII
        // passwords must use the programmatic `Config` API instead.
        assert!("jdbc:sqlserver://host.com:1433;User ID=sa;Password=café"
            .parse::<JdbcConfig>()
            .is_err());
        // Braces are JDBC's only quoting mechanism; non-ASCII is rejected there
        // too (mirrors the ADO quoted-value test).
        assert!("jdbc:sqlserver://host.com:1433;User ID=sa;Password={café}"
            .parse::<JdbcConfig>()
            .is_err());
    }

    #[test]
    fn empty_password_is_rejected() {
        // Unlike the ADO parser (which accepts an empty value), the JDBC parser
        // requires a non-empty property value, so `Password=` fails to parse.
        assert!("jdbc:sqlserver://host.com:1433;User ID=sa;Password="
            .parse::<JdbcConfig>()
            .is_err());
    }

    #[test]
    fn unquoted_special_char_password_error_has_hint() {
        // An unquoted `;` in a password breaks parsing. The error must guide
        // the user toward brace quoting (JDBC's only escape) or the programmatic
        // API, while preserving the underlying parser message.
        let err = "jdbc:sqlserver://host.com:1433;User ID=sa;Password=a;b"
            .parse::<JdbcConfig>()
            .err()
            .unwrap();
        let msg = err.to_string();
        // Underlying terse parser message is preserved (not replaced).
        assert!(msg.contains("must be joined"), "message was: {msg}");
        // JDBC guidance must steer toward braces and its own constructor docs.
        assert!(msg.contains("braces"), "message was: {msg}");
        assert!(
            msg.contains("Config::from_jdbc_string"),
            "message was: {msg}"
        );
        // The `Conversion error:` prefix must not be doubled.
        assert!(
            !msg.contains("Conversion error: Conversion error:"),
            "message was: {msg}"
        );
    }

    #[test]
    fn unclosed_brace_error_has_hint() {
        // An unclosed brace is a quoting mistake; the hint should attach.
        let err = "jdbc:sqlserver://host.com:1433;User ID=sa;Password={abc"
            .parse::<JdbcConfig>()
            .err()
            .unwrap();
        let msg = err.to_string();
        assert!(msg.contains("must be quoted"), "message was: {msg}");
        assert!(
            !msg.contains("Conversion error: Conversion error:"),
            "message was: {msg}"
        );
    }

    #[test]
    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    fn encryption_parsing_on() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;encrypt=true;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(EncryptionLevel::Required, jdbc.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    fn encryption_parsing_off() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;encrypt=false;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(EncryptionLevel::Off, jdbc.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    fn encryption_parsing_plaintext() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;encrypt=DANGER_PLAINTEXT;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(EncryptionLevel::NotSupported, jdbc.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    fn encryption_parsing_missing() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(EncryptionLevel::Required, jdbc.encrypt()?);

        Ok(())
    }

    // No-TLS build: an explicit encryption request must error (not silently
    // downgrade to plaintext, #305); opting out and an omitted keyword stay
    // `NotSupported`.

    #[test]
    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encryption_parsing_on_errors_without_tls_backend() -> crate::Result<()> {
        for enc in ["true", "yes"] {
            let test_str = format!("jdbc:sqlserver://my-server.com:4200;encrypt={enc};");
            let jdbc: JdbcConfig = test_str.parse()?;
            let err = jdbc.encrypt().unwrap_err();
            assert!(
                matches!(err, crate::Error::Tls(_)),
                "expected Error::Tls for {test_str}, got {err:?}"
            );
            let msg = err.to_string();
            assert!(msg.contains("without a TLS backend"), "message was: {msg}");
        }

        Ok(())
    }

    #[test]
    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encryption_parsing_strict_errors_without_tls_backend() {
        let jdbc: JdbcConfig = "jdbc:sqlserver://my-server.com:4200;encrypt=strict;"
            .parse()
            .unwrap();
        let err = jdbc.encrypt().unwrap_err();
        assert!(
            matches!(err, crate::Error::Tls(_)),
            "expected Error::Tls, got {err:?}"
        );
    }

    #[test]
    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encryption_parsing_mandatory_errors_without_tls_backend() {
        // `mandatory` is not an accepted token in either build; the with-TLS
        // parser rejects it as a bad boolean, so the no-TLS branch mirrors that
        // (still an error, just not the TLS-missing one).
        let jdbc: JdbcConfig = "jdbc:sqlserver://my-server.com:4200;encrypt=mandatory;"
            .parse()
            .unwrap();
        assert!(jdbc.encrypt().is_err());
    }

    #[test]
    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encryption_parsing_off_ok_without_tls_backend() -> crate::Result<()> {
        for enc in ["false", "no"] {
            let test_str = format!("jdbc:sqlserver://my-server.com:4200;encrypt={enc};");
            let jdbc: JdbcConfig = test_str.parse()?;
            assert_eq!(crate::EncryptionLevel::NotSupported, jdbc.encrypt()?);
        }

        Ok(())
    }

    #[test]
    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encryption_parsing_plaintext_ok_without_tls_backend() -> crate::Result<()> {
        let jdbc: JdbcConfig =
            "jdbc:sqlserver://my-server.com:4200;encrypt=DANGER_PLAINTEXT;".parse()?;
        assert_eq!(crate::EncryptionLevel::NotSupported, jdbc.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encryption_parsing_missing_ok_without_tls_backend() -> crate::Result<()> {
        let jdbc: JdbcConfig = "jdbc:sqlserver://my-server.com:4200;".parse()?;
        assert_eq!(crate::EncryptionLevel::NotSupported, jdbc.encrypt()?);

        Ok(())
    }

    #[test]
    fn application_name_parsing() -> crate::Result<()> {
        let test_str = "jdbc:sqlserver://my-server.com:4200;Application Name=meow";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(Some("meow".into()), jdbc.application_name());

        let test_str = "jdbc:sqlserver://my-server.com:4200;ApplicationName=meow";
        let jdbc: JdbcConfig = test_str.parse()?;

        assert_eq!(Some("meow".into()), jdbc.application_name());

        Ok(())
    }
}