oid_registry/
lib.rs

1//! [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE-MIT)
2//! [![Apache License 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](./LICENSE-APACHE)
3//! [![docs.rs](https://docs.rs/oid-registry/badge.svg)](https://docs.rs/oid-registry)
4//! [![crates.io](https://img.shields.io/crates/v/oid-registry.svg)](https://crates.io/crates/oid-registry)
5//! [![Github CI](https://github.com/rusticata/oid-registry/workflows/Continuous%20integration/badge.svg)](https://github.com/rusticata/oid-registry/actions)
6//! [![Minimum rustc version](https://img.shields.io/badge/rustc-1.63.0+-lightgray.svg)](#rust-version-requirements)
7//! # OID Registry
8//!
9//! This crate is a helper crate, containing a database of OID objects. These objects are intended
10//! for use when manipulating ASN.1 grammars and BER/DER encodings, for example.
11//!
12//! This crate provides only a simple registry (similar to a `HashMap`) by default. This object can
13//! be used to get names and descriptions from OID.
14//!
15//! This crate provides default lists of known OIDs, that can be selected using the build features.
16//! By default, the registry has no feature enabled, to avoid embedding a huge database in crates.
17//!
18//! It also declares constants for most of these OIDs.
19//!
20//! ```rust
21//! use oid_registry::OidRegistry;
22//!
23//! let mut registry = OidRegistry::default()
24//! # ;
25//! # #[cfg(feature = "crypto")] {
26//! #     registry = registry
27//!     .with_crypto() // only if the 'crypto' feature is enabled
28//! # }
29//! ;
30//!
31//! let e = registry.get(&oid_registry::OID_PKCS1_SHA256WITHRSA);
32//! if let Some(entry) = e {
33//!     // get sn: sha256WithRSAEncryption
34//!     println!("sn: {}", entry.sn());
35//!     // get description: SHA256 with RSA encryption
36//!     println!("description: {}", entry.description());
37//! }
38//!
39//! ```
40//!
41//! ## Extending the registry
42//!
43//! These provided lists are often incomplete, or may lack some specific OIDs.
44//! This is why the registry allows adding new entries after construction:
45//!
46//! ```rust
47//! use asn1_rs::oid;
48//! use oid_registry::{OidEntry, OidRegistry};
49//!
50//! let mut registry = OidRegistry::default();
51//!
52//! // entries can be added by creating an OidEntry object:
53//! let entry = OidEntry::new("shortName", "description");
54//! registry.insert(oid!(1.2.3.4), entry);
55//!
56//! // when using static strings, a tuple can also be used directly for the entry:
57//! registry.insert(oid!(1.2.3.5), ("shortName", "A description"));
58//!
59//! ```
60//!
61//! ## Versions and compatibility with `asn1-rs`
62//!
63//! Versions of `oid-registry` must be chosen specifically, to depend on a precise version of `asn1-rs`.
64//! The following table summarizes the matching versions:
65//!
66//! - `oid-registry` 0.7.x depends on `asn1-rs` 0.6.0
67//! - `oid-registry` 0.6.x depends on `asn1-rs` 0.5.0
68//! - `oid-registry` 0.5.x depends on `asn1-rs` 0.4.0
69//!
70//! ## Contributing OIDs
71//!
72//! All OID values, constants, and features are derived from files in the `assets` directory in the
73//! build script (see `build.rs`).
74//! See `load_file` for documentation of the file format.
75
76#![deny(missing_docs, unstable_features, unused_import_braces, unused_qualifications, unreachable_pub)]
77#![forbid(unsafe_code)]
78#![warn(
79      /* missing_docs,
80      rust_2018_idioms,*/
81      missing_debug_implementations,
82  )]
83// pragmas for doc
84// #![deny(intra_doc_link_resolution_failure)]
85#![cfg_attr(docsrs, feature(doc_cfg))]
86
87pub use asn1_rs;
88pub use asn1_rs::Oid;
89
90use asn1_rs::oid;
91use std::borrow::Cow;
92use std::collections::HashMap;
93
94mod load;
95
96pub use load::*;
97
98/// An entry stored in the OID registry
99#[derive(Debug)]
100pub struct OidEntry {
101    // Short name
102    sn: Cow<'static, str>,
103    description: Cow<'static, str>,
104}
105
106impl OidEntry {
107    /// Create a new entry
108    pub fn new<S, T>(sn: S, description: T) -> OidEntry
109    where
110        S: Into<Cow<'static, str>>,
111        T: Into<Cow<'static, str>>,
112    {
113        let sn = sn.into();
114        let description = description.into();
115        OidEntry { sn, description }
116    }
117
118    /// Get the short name for this entry
119    #[inline]
120    pub fn sn(&self) -> &str {
121        &self.sn
122    }
123
124    /// Get the description for this entry
125    #[inline]
126    pub fn description(&self) -> &str {
127        &self.description
128    }
129}
130
131impl From<(&'static str, &'static str)> for OidEntry {
132    fn from(t: (&'static str, &'static str)) -> Self {
133        Self::new(t.0, t.1)
134    }
135}
136
137/// Registry of known OIDs
138///
139/// Use `OidRegistry::default()` to create an empty registry. If the corresponding features have
140/// been selected, the `with_xxx()` methods can be used to add sets of known objets to the
141/// database.
142///
143/// # Example
144///
145/// ```rust
146/// use asn1_rs::{oid, Oid};
147/// use oid_registry::{OidEntry, OidRegistry};
148///
149/// let mut registry = OidRegistry::default()
150/// # ;
151/// # #[cfg(feature = "crypto")] {
152/// #     registry = registry
153///     .with_crypto() // only if the 'crypto' feature is enabled
154/// # }
155/// ;
156///
157/// // entries can be added by creating an OidEntry object:
158/// let entry = OidEntry::new("shortName", "description");
159/// registry.insert(oid!(1.2.3.4), entry);
160///
161/// // when using static strings, a tuple can also be used directly for the entry:
162/// registry.insert(oid!(1.2.3.5), ("shortName", "A description"));
163///
164/// // To query an entry, use the `get` method:
165/// const OID_1234: Oid<'static> = oid!(1.2.3.4);
166/// let e = registry.get(&OID_1234);
167/// assert!(e.is_some());
168/// if let Some(e) = e {
169///     assert_eq!(e.sn(), "shortName");
170/// }
171/// ```
172#[derive(Debug, Default)]
173pub struct OidRegistry<'a> {
174    map: HashMap<Oid<'a>, OidEntry>,
175}
176
177impl<'a> OidRegistry<'a> {
178    /// Insert a new entry
179    pub fn insert<E>(&mut self, oid: Oid<'a>, entry: E) -> Option<OidEntry>
180    where
181        E: Into<OidEntry>,
182    {
183        self.map.insert(oid, entry.into())
184    }
185
186    /// Returns a reference to the registry entry, if found for this OID.
187    pub fn get(&self, oid: &Oid<'a>) -> Option<&OidEntry> {
188        self.map.get(oid)
189    }
190
191    /// Return an Iterator over references to the OID numbers (registry keys)
192    pub fn keys(&self) -> impl Iterator<Item = &Oid<'a>> {
193        self.map.keys()
194    }
195
196    /// Return an Iterator over references to the `OidEntry` values
197    pub fn values(&self) -> impl Iterator<Item = &OidEntry> {
198        self.map.values()
199    }
200
201    /// Return an Iterator over references to the `(Oid, OidEntry)` key/value pairs
202    pub fn iter(&self) -> impl Iterator<Item = (&Oid<'a>, &OidEntry)> {
203        self.map.iter()
204    }
205
206    /// Return the `(Oid, OidEntry)` key/value pairs, matching a short name
207    ///
208    /// The registry should not contain entries with same short name to avoid ambiguity, but it is
209    /// not mandatory.
210    ///
211    /// This function returns an iterator over the key/value pairs. In most cases, it will have 0
212    /// (not found) or 1 item, but can contain more if there are multiple definitions.
213    ///
214    /// ```rust
215    /// # use oid_registry::OidRegistry;
216    /// #
217    /// # let registry = OidRegistry::default();
218    /// // iterate all entries matching "shortName"
219    /// for (oid, entry) in registry.iter_by_sn("shortName") {
220    ///     // do something
221    /// }
222    ///
223    /// // if you are *sure* that there is at most one entry:
224    /// let opt_sn = registry.iter_by_sn("shortName").next();
225    /// if let Some((oid, entry)) = opt_sn {
226    ///     // do something
227    /// }
228    /// ```
229    pub fn iter_by_sn<S: Into<String>>(&self, sn: S) -> impl Iterator<Item = (&Oid<'a>, &OidEntry)> {
230        let s = sn.into();
231        self.map.iter().filter(move |(_, entry)| entry.sn == s)
232    }
233
234    /// Populate registry with common crypto OIDs (encryption, hash algorithms)
235    #[cfg(feature = "crypto")]
236    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
237    pub fn with_crypto(self) -> Self {
238        self.with_pkcs1().with_x962().with_kdf().with_nist_algs()
239    }
240
241    /// Populate registry with all known crypto OIDs (encryption, hash algorithms, PKCS constants,
242    /// etc.)
243    #[cfg(feature = "crypto")]
244    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
245    pub fn with_all_crypto(self) -> Self {
246        self.with_crypto().with_pkcs7().with_pkcs9().with_pkcs12()
247    }
248}
249
250/// Format a OID to a `String`, using the provided registry to get the short name if present.
251pub fn format_oid(oid: &Oid, registry: &OidRegistry) -> String {
252    if let Some(entry) = registry.map.get(oid) {
253        format!("{} ({})", entry.sn, oid)
254    } else {
255        format!("{}", oid)
256    }
257}
258
259include!(concat!(env!("OUT_DIR"), "/oid_db.rs"));
260
261#[rustfmt::skip::macros(oid)]
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    // This test is mostly a compile test, to ensure the API has not changed
267    #[test]
268    fn test_lifetimes() {
269        fn add_entry(input: &str, oid: Oid<'static>, registry: &mut OidRegistry) {
270            // test insertion of owned string
271            let s = String::from(input);
272            let entry = OidEntry::new("test", s);
273            registry.insert(oid, entry);
274        }
275
276        let mut registry = OidRegistry::default();
277        add_entry("a", oid!(1.2.3.4), &mut registry);
278        add_entry("b", oid!(1.2.3.5), &mut registry);
279
280        // test insertion of owned data
281        let e = OidEntry::new("c", "test_c");
282        registry.insert(oid!(1.2.4.1), e);
283
284        registry.insert(oid!(1.2.5.1), ("a", "b"));
285
286        let iter = registry.iter_by_sn("test");
287        assert_eq!(iter.count(), 2);
288
289        // dbg!(&registry);
290    }
291}