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
//! A *zero-copy* library to parse and validate PKCS#11 URIs in accordance to [RFC7512][rfc7512] specifications.
//!
//!
//!
//! [rfc7512]: <https://datatracker.ietf.org/doc/html/rfc7512>
//!
//! ## Examples
//!
//! Using a sample URI from the specification:
//! ```
//! use pk11_uri_parser::{parse, PK11URIError};
//!
//! fn main() -> Result<(), PK11URIError> {
//! let pk11_uri = "pkcs11:token=The%20Software%20PKCS%2311%20Softtoken;
//! manufacturer=Snake%20Oil,%20Inc.;
//! model=1.0;
//! object=my-certificate;
//! type=cert;
//! id=%69%95%3E%5C%F4%BD%EC%91;
//! serial=
//! ?pin-source=file:/etc/token_pin";
//!
//! let mapping = parse(pk11_uri)?;
//!
//! println!("{mapping:?}");
//! Ok(())
//! }
//! ```
//! Will effectively print:
//! ```terminal
//! PK11URIMapping { token: Some("The%20Software%20PKCS%2311%20Softtoken"), manufacturer: Some("Snake%20Oil,%20Inc."), serial: Some(""), model: Some("1.0"), library_manufacturer: None, library_version: None, library_description: None, object: Some("my-certificate"), type: Some("cert"), id: Some("%69%95%3E%5C%F4%BD%EC%91"), slot_description: None, slot_manufacturer: None, slot_id: None, pin_source: Some("file:/etc/token_pin"), pin_value: None, module_name: None, module_path: None, vendor: {} }
//! ```
//!
//! The [parse] `Result`'s type is a [PK11URIMapping]. Users of the library do not need to be intimately
//! familiar with specification rules regarding what attributes belong to the path-component or the
//! query-component, or to be knowledgeable about the various vendor-specific attribute rules: the `PK11URIMapping`
//! provides appropriately named methods for retrieving standard component values and an intuitive
//! [vendor][`PK11URIMapping::vendor()`] method for retrieving *vendor-specific* attribute values.
//! ```
//! let pk11_uri = "pkcs11:vendor-attribute=my_vendor_attribte?pin-source=|/usr/lib/pinomatic";
//! let mapping = pk11_uri_parser::parse(pk11_uri).expect("mapping should be valid");
//! if let Some(pin_source) = mapping.pin_source() {
//! // do something with `pin_source`...
//! }
//! // see whether we've got `vendor-attribute` values:
//! if let Some(vendor_values) = mapping.vendor("vendor-attribute") {
//! // do something with `vendor_values`...
//! }
//! ```
//!
//! It's worth reiterating that vendor-specific attributes may have *multiple* values so therefore the `vendor`
//! method's `Option` return type is `&Vec<&'a str>`.
//!
//! ## Errors
//!
//! At least initially, PKCS#11 URIs will likely be derived from invoking exploratory commands in tools such as
//! `p11tool` or `pkcs11-tool`. While parsing URIs from these tools is pretty much guaranteed to be successful,
//! it's often *not* necessary to provide such verbose values in order to properly identify your targeted resource.
//! It's also generally beyond the scope of those tools to include query-components (such as `pin-value` or `pin-source`).
//! In the interest of making your life a little bit easier (and code more readable), a bit of exploration can result
//! in a considerably shorter (and potentially more *portable*) URI.
//!
//! Let's say for example you are in need of utilizing an HSM-bound private key (and read "somewhere on the internet"):
//! ```
//! // note: this isn't a valid pkcs11 uri
//! let pk11_uri = "pkcs11:object=Private key for Card Authentication;pin-value=123456";
//! #[cfg(feature = "validation")]
//! println!("{err:?}", err=pk11_uri_parser::parse(pk11_uri).expect_err("empty spaces in value violation"));
//! ```
//! Attempting to parse that uri will result in a [PK11URIError].
//! ```terminal
//! PK11URIError { pk11_uri: "pkcs11:object=Private key for Card Authentication;pin-value=123456", error_span: (7, 49), violation: "Invalid component value: Appendix A of [RFC3986] specifies component values may not contain empty spaces.", help: "Replace `Private key for Card Authentication` with `Private%20key%20for%20Card%20Authentication`." }
//! ```
//! Or if you'd prefer a fancier output, simply display the PK11URIError (*not* using `:?` debug):
//! ```
//! // note: this isn't a valid pkcs11 uri
//! let pk11_uri = "pkcs11:object=Private key for Card Authentication;pin-value=123456";
//! #[cfg(feature = "validation")]
//! println!("{err}", err=pk11_uri_parser::parse(pk11_uri).expect_err("empty spaces in value violation"))
//! ```
//! ```terminal
//! pkcs11:object=Private key for Card Authentication;pin-value=123456
//! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Invalid component value: Appendix A of [RFC3986] specifies component values may not contain empty spaces.
//!
//! help: Replace `Private key for Card Authentication` with `Private%20key%20for%20Card%20Authentication`.
//! ```
//! Great! Based on the "help" text, it's a simple fix:
//! ```
//! // note: again, this isn't a valid pkcs11 uri
//! let pk11_uri = "pkcs11:object=Private%20key%20for%20Card%20Authentication;pin-value=123456";
//! #[cfg(feature = "validation")]
//! println!("{err}", err=pk11_uri_parser::parse(pk11_uri).expect_err("query component naming collision violation"));
//! ```
//! This will once again fail to parse and brings up the fact that this library will *fail-quickly* (ie, short-circuit *further* parsing) if any violation is found.
//! ```terminal
//! pkcs11:object=Private%20key%20for%20Card%20Authentication;pin-value=123456
//! ^^^^^^^^^^^^^^^^ Naming collision with standard query component.
//!
//! help: Move `pin-value` and its value to the PKCS#11 URI query.
//! ```
//! In this case, `pin-value` is a standard *query-component* attribute name so its current location as a path attribute is a violation.
//! The "help" section again offers a simple solution.
//! ```no_run
//! let pk11_uri = "pkcs11:object=Private%20key%20for%20Card%20Authenciation?pin-value=123456";
//! pk11_uri_parser::parse(pk11_uri).expect("mapping should be valid");
//! ```
//! Which finally yields a valid mapping.
//!
//! ## Warnings
//!
//! The [RFC7512][rfc7512] specification uses terminology such as `SHOULD` and `SHOULD NOT` to indicate *optional*,
//! best-practice type treatment for attribute values. This library embraces these optional rules, but will only
//! emit *warning* messages to the terminal and only provide such warnings for *non-optimized* builds. Likewise,
//! violations of such optional rules will *never* result in a [PK11URIError]. The messages printed to the terminal
//! begin with `pkcs11 warning:`.
//!
//! Assuming a debug build:
//! ```no_run
//! let pk11_uri = "pkcs11:x-muppet=cookie<^^>monster!";
//! let mapping = pk11_uri_parser::parse(pk11_uri).expect("mapping should be valid");
//! let x_muppet = mapping.vendor("x-muppet").expect("valid x-muppet vendor-attribute");
//! println!("x-muppet: {:?}", x_muppet);
//! ```
//! prints
//! ```terminal
//! pkcs11 warning: per RFC7512, the previously used convention of starting vendor attributes with an "x-" prefix is now deprecated. Identified: `x-muppet`.
//! pkcs11 warning: the `<` identified at offset 6 in `cookie<^^>monster!` of component `x-muppet=cookie<^^>monster!` SHOULD be percent-encoded.
//! pkcs11 warning: the `^` identified at offset 7 in `cookie<^^>monster!` of component `x-muppet=cookie<^^>monster!` SHOULD be percent-encoded.
//! pkcs11 warning: the `^` identified at offset 8 in `cookie<^^>monster!` of component `x-muppet=cookie<^^>monster!` SHOULD be percent-encoded.
//! pkcs11 warning: the `>` identified at offset 9 in `cookie<^^>monster!` of component `x-muppet=cookie<^^>monster!` SHOULD be percent-encoded.
//! x-muppet: ["cookie<^^>monster!"]
//! ```
//! Any warning related code is explicitly **not** included in `--release` builds.
//!
//! ## Crate feature flags
//!
//! As alluded to above, the crate's **default** feature set is to *always* perform validation and for
//! debug builds, emit `pkcs11 warning:` messages when values do not comply with RFC7512 "SHOULD/
//! SHOULD NOT" guidelines.
//!
//! > "But sir, I implore you, I've *thoroughly* tested my input!"
//!
//! I hear you barking, big dog! It's perfectly reasonable to *not* want validation (and/or warnings). You
//! can eliminate that slight bit of runtime overhead by utilizing the `default-features=false` treatment
//! on your dependency:
//! ```toml
//! [dependencies]
//! pk11-uri-parser = {version = "0.1.4", default-features = false}
//! ```
//! It's important to note, however, that doing so will introduce `expect("my expectation")` calls to perform
//! unwrap functionality required in the parsing.
use error;
use HashMap;
use fmt;
const PKCS11_SCHEME: &str = "pkcs11:";
const PKCS11_SCHEME_LEN: usize = PKCS11_SCHEME.len;
/// Issued when [parsing][parse] a PKCS#11 URI is found to be in violation of [RFC7512][rfc7512] specifications.
///
/// The included `pk11_uri` is a "tidied" version of the one provided to the
/// `parse` function: any *newline* or *tab* formatting has been stripped out
/// in order to accurately identify the `error_span` within the uri. The `violation`
/// will refer to the [RFC7512 Augmented BNF][abnf] whenever possible, while the `help`
/// value provides a more human-friendly suggestion to correcting the violation.
///
/// [rfc7512]: <https://datatracker.ietf.org/doc/html/rfc7512>
/// [abnf]: <https://datatracker.ietf.org/doc/html/rfc7512#section-2.3>
/// Highlights the issue using the `error_span`.
/// Encapsulates the result of successfully [parsing][parse] a PKCS#11 URI.
/// Parses and verifies the contents of the given `pk11_uri` &str, making
/// parsed values available through a [PK11URIMapping]. Violations to [RFC7512][rfc7512]
/// specifications will result in issuing a [PK11URIError].
///
/// The contents of the `PK11URIMapping` are string slices of the `pk11_uri`,
/// so if you need the mapping to outlive the pk11_uri, simply clone it.
///
/// [rfc7512]: <https://datatracker.ietf.org/doc/html/rfc7512>
/// Helper function to identify the location of an empty path|query component.
/// An empty component is a phenomena of a superfluous ';' or '&' delimiter such
/// as `pkcs11:foo=bar;`
/// ^ trailing ';' is a RFC7512 violation.
/// Establish the basis for reliable error reporting by removing '\n' newline
/// and '\t' tab formatting.