Skip to main content

malwaredb_api/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2
3#![doc = include_str!("../README.md")]
4#![deny(missing_docs)]
5#![deny(clippy::all)]
6#![deny(clippy::pedantic)]
7#![forbid(unsafe_code)]
8
9/// Wrapper for fixed-size cryptographic hash digests from hex strings
10pub mod digest;
11
12use crate::digest::HashType;
13
14use std::collections::HashMap;
15use std::error::Error;
16use std::fmt::{Display, Formatter};
17
18use chrono::serde::ts_seconds_option;
19use chrono::{DateTime, Utc};
20use serde::{Deserialize, Serialize};
21use zeroize::{Zeroize, ZeroizeOnDrop};
22
23/// MDB version
24pub const MDB_VERSION: &str = env!("CARGO_PKG_VERSION");
25
26/// HTTP header used to present the API key to the server
27pub const MDB_API_HEADER: &str = "mdb-api-key";
28
29/// Authentication endpoint, POST
30pub const USER_LOGIN_URL: &str = "/v1/users/getkey";
31
32/// Endpoint name for use with Multicast DNS
33pub const MDNS_NAME: &str = "_malwaredb._tcp.local.";
34
35/// The size of the API key in **bytes**. The string length will be double.
36pub const MDB_API_KEY_LENGTH_BYTES: usize = 64;
37
38/// User authentication with username and password to get the API key
39#[derive(Deserialize, Serialize, Zeroize, ZeroizeOnDrop)]
40pub struct GetAPIKeyRequest {
41    /// Username
42    pub user: String,
43
44    /// User's password
45    pub password: String,
46}
47
48/// Logout API endpoint to clear their API key, GET, authenticated.
49pub const USER_LOGOUT_URL: &str = "/v1/users/clearkey";
50
51/// Respond to authentication with the key if the credentials were correct,
52/// and possibly show a message related to errors or warnings.
53#[derive(Deserialize, Serialize, Zeroize, ZeroizeOnDrop)]
54pub struct GetAPIKeyResponse {
55    /// User's API key if successful
56    pub key: String,
57
58    /// Error response
59    pub message: Option<String>,
60}
61
62/// For request types, wrap in this struct to handle some error conditions
63///
64/// All API endpoints use this response format EXCEPT:
65///   * [`USER_LOGOUT_URL`]
66///   * [`UPLOAD_SAMPLE_JSON_URL`]
67///   * [`UPLOAD_SAMPLE_CBOR_URL`]
68///   * [`DOWNLOAD_SAMPLE_URL`]
69///   * [`DOWNLOAD_SAMPLE_CART_URL`]
70#[derive(Clone, Debug, Deserialize, Serialize)]
71pub enum ServerResponse<D> {
72    /// Request successful
73    #[serde(alias = "success")]
74    Success(D),
75
76    /// Request unsuccessful
77    #[serde(alias = "error")]
78    Error(ServerError),
79}
80
81impl<D> ServerResponse<D> {
82    /// Unwrap a server response
83    ///
84    /// # Panics
85    ///
86    /// Will panic if the response is an error
87    #[inline]
88    pub fn unwrap(self) -> D {
89        match self {
90            ServerResponse::Success(d) => d,
91            ServerResponse::Error(e) => panic!("forced ServerResponse::unwrap() on error: {e}"),
92        }
93    }
94
95    /// Convert the server response into a traditional [`Result`] type
96    ///
97    /// # Errors
98    ///
99    /// The return error is the server error, if present
100    #[inline]
101    pub fn into_result(self) -> Result<D, ServerError> {
102        match self {
103            ServerResponse::Success(d) => Ok(d),
104            ServerResponse::Error(e) => Err(e),
105        }
106    }
107
108    /// If the server response was successful
109    #[inline]
110    pub const fn is_successful(&self) -> bool {
111        matches!(*self, ServerResponse::Success(_))
112    }
113
114    /// If the server response was not successful
115    #[inline]
116    pub const fn is_err(&self) -> bool {
117        matches!(*self, ServerResponse::Error(_))
118    }
119}
120
121/// Server error responses
122#[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
123pub enum ServerError {
124    /// The server was asked for samples but doesn't store them
125    NoSamples,
126
127    /// The requested item was not found or the search yielded no results
128    NotFound,
129
130    /// Internal server error, details not disclosed to the client
131    ServerError,
132
133    /// Unauthorized: API key was not provided, or the user doesn't have access to the requested item(s)
134    Unauthorized,
135
136    /// Request was for a feature which is not supported by the server, such as Yara for example
137    Unsupported,
138}
139
140impl Display for ServerError {
141    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
142        match self {
143            ServerError::NoSamples => write!(f, "NoSamples"),
144            ServerError::NotFound => write!(f, "NotFound"),
145            ServerError::ServerError => write!(f, "ServerError"),
146            ServerError::Unauthorized => write!(f, "Unauthorized"),
147            ServerError::Unsupported => write!(f, "Unsupported"),
148        }
149    }
150}
151
152impl Error for ServerError {}
153
154/// User's account information API endpoint, GET, authenticated
155pub const USER_INFO_URL: &str = "/v1/users/info";
156
157/// User account information
158#[derive(Clone, Debug, Deserialize, Serialize)]
159pub struct GetUserInfoResponse {
160    /// User's numeric ID
161    pub id: u32,
162
163    /// User's name
164    pub username: String,
165
166    /// User's group memberships, if any
167    pub groups: Vec<String>,
168
169    /// User's available sample sources, if any
170    pub sources: Vec<String>,
171
172    /// If the user is an admin
173    pub is_admin: bool,
174
175    /// When the account was created
176    pub created: DateTime<Utc>,
177
178    /// User has read-only access, perhaps a guest or demo account
179    pub is_readonly: bool,
180}
181
182/// Server information, request is empty, GET, Unauthenticated.
183pub const SERVER_INFO_URL: &str = "/v1/server/info";
184
185/// Information about the server
186#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
187pub struct ServerInfo {
188    /// Operating System used
189    pub os_name: String,
190
191    /// Memory footprint
192    pub memory_used: String,
193
194    /// MDB version
195    pub mdb_version: semver::Version,
196
197    /// Type and version of the database
198    pub db_version: String,
199
200    /// Size of the database on disk
201    pub db_size: String,
202
203    /// Total number of samples in Malware DB
204    pub num_samples: u64,
205
206    /// Total users of Malware DB
207    pub num_users: u32,
208
209    /// Uptime of Malware DB in a human-readable format
210    pub uptime: String,
211
212    /// The name of the Malware DB instance
213    pub instance_name: String,
214
215    /// If the server was compiled with Virus Total support
216    pub vt_support: bool,
217
218    /// If the server was compiled with Yara support
219    pub yara_enabled: bool,
220}
221
222/// File types supported by Malware DB, request is empty, GET, Unauthenticated.
223pub const SUPPORTED_FILE_TYPES_URL: &str = "/v1/server/types";
224
225/// One record of supported file types
226#[derive(Clone, Debug, Deserialize, Serialize)]
227pub struct SupportedFileType {
228    /// Common name of the file type
229    pub name: String,
230
231    /// Magic number bytes in hex of the file type
232    pub magic: Vec<String>,
233
234    /// Whether the file type is executable
235    pub is_executable: bool,
236
237    /// Description of the file type
238    pub description: Option<String>,
239}
240
241/// Server's supported types, the response
242#[derive(Clone, Debug, Deserialize, Serialize)]
243pub struct SupportedFileTypes {
244    /// Supported file types
245    pub types: Vec<SupportedFileType>,
246
247    /// Optional server messages
248    pub message: Option<String>,
249}
250
251/// Endpoint for the sources, per-user, GET, authenticated
252pub const LIST_SOURCES_URL: &str = "/v1/sources/list";
253
254/// Information about a sample source
255#[derive(Clone, Debug, Deserialize, Serialize)]
256pub struct SourceInfo {
257    /// ID of the source
258    pub id: u32,
259
260    /// Name of the source
261    pub name: String,
262
263    /// Description of the source
264    pub description: Option<String>,
265
266    /// URL of the source, or where the files were found
267    pub url: Option<String>,
268
269    /// Creation date or first acquisition date of or from the source
270    pub first_acquisition: DateTime<Utc>,
271
272    /// Whether the source holds malware
273    pub malicious: Option<bool>,
274}
275
276/// Sources response for request for sources
277#[derive(Clone, Debug, Deserialize, Serialize)]
278pub struct Sources {
279    /// List of sources
280    pub sources: Vec<SourceInfo>,
281
282    /// Error message, if any
283    pub message: Option<String>,
284}
285
286/// API endpoint for uploading a sample with JSON, POST, Authenticated
287pub const UPLOAD_SAMPLE_JSON_URL: &str = "/v1/samples/json/upload";
288
289/// API endpoint for uploading a sample with CBOR, POST, Authenticated
290pub const UPLOAD_SAMPLE_CBOR_URL: &str = "/v1/samples/cbor/upload";
291
292/// New file sample being sent to Malware DB via [`UPLOAD_SAMPLE_JSON_URL`]
293#[derive(Clone, Debug, Deserialize, Serialize)]
294pub struct NewSampleB64 {
295    /// The original file name, which might not be known. If it's not known,
296    /// use a hash or something like "unknown.bin".
297    pub file_name: String,
298
299    /// ID of the source for this sample
300    pub source_id: u32,
301
302    /// Base64 encoding of the binary file
303    pub file_contents_b64: String,
304
305    /// SHA-256 of the sample being sent, for server-side validation
306    pub sha256: String,
307}
308
309/// New file sample being sent to Malware DB via [`UPLOAD_SAMPLE_CBOR_URL`]
310#[derive(Clone, Debug, Deserialize, Serialize)]
311pub struct NewSampleBytes {
312    /// The original file name, which might not be known. If it's not known,
313    /// use a hash or something like "unknown.bin".
314    pub file_name: String,
315
316    /// ID of the source for this sample
317    pub source_id: u32,
318
319    /// Raw binary contents
320    pub file_contents: Vec<u8>,
321
322    /// SHA-256 of the sample being sent, for server-side validation
323    pub sha256: String,
324}
325
326/// API endpoint for downloading a sample, GET. The hash value goes at the end of the URL.
327/// Example: `/v1/samples/download/aabbccddeeff0011223344556677889900`
328/// Response is raw bytes of the file, or HTTP 404 if not found
329pub const DOWNLOAD_SAMPLE_URL: &str = "/v1/samples/download";
330
331/// API endpoint for downloading a sample as a `CaRT` container file, GET
332/// Example: `/v1/samples/download/cart/aabbccddeeff0011223344556677889900`
333/// Response is the file encoded in a `CaRT` container file, or HTTP 404 if not found
334pub const DOWNLOAD_SAMPLE_CART_URL: &str = "/v1/samples/download/cart";
335
336/// API endpoint to get a report for a given sample
337/// Example: `/v1/samples/report/aabbccddeeff0011223344556677889900`
338pub const SAMPLE_REPORT_URL: &str = "/v1/samples/report";
339
340/// Virus Total hits summary for a specific sample
341#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
342pub struct VirusTotalSummary {
343    /// Anti-Virus products which identified the sample as malicious
344    pub hits: u32,
345
346    /// Anti-Virus products available when last analyzed
347    pub total: u32,
348
349    /// Hit details in JSON format, if available
350    #[serde(default)]
351    pub detail: Option<serde_json::Value>,
352
353    /// Most recent analysis date, if available
354    #[serde(default, with = "ts_seconds_option")]
355    pub last_analysis_date: Option<DateTime<Utc>>,
356}
357
358// TODO: Add sections for parsed fields for documents, executables
359/// Information for an individual sample
360#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
361pub struct Report {
362    /// MD-5 hash
363    pub md5: String,
364
365    /// SHA-1 hash
366    pub sha1: String,
367
368    /// SHA-256 hash
369    pub sha256: String,
370
371    /// SHA-384 hash
372    pub sha384: String,
373
374    /// SHA-512 hash
375    pub sha512: String,
376
377    /// LZJD similarity hash, if available
378    /// <https://github.com/EdwardRaff/LZJD>
379    pub lzjd: Option<String>,
380
381    /// TLSH similarity hash, if available
382    /// <https://github.com/trendmicro/tlsh>
383    pub tlsh: Option<String>,
384
385    /// `SSDeep` similarity hash, if available
386    /// <https://ssdeep-project.github.io/ssdeep/index.html>
387    pub ssdeep: Option<String>,
388
389    /// Human hash
390    /// <https://github.com/zacharyvoase/humanhash>
391    pub humanhash: Option<String>,
392
393    /// The output from libmagic, aka the `file` command
394    /// <https://man7.org/linux/man-pages/man3/libmagic.3.html>
395    pub filecommand: Option<String>,
396
397    /// Sample size in bytes
398    pub bytes: u64,
399
400    /// Sample size in human-readable size (2048 becomes 2 kb, for example)
401    pub size: String,
402
403    /// Entropy of the file, values over 6.5 may indicate compression or encryption
404    pub entropy: f32,
405
406    /// Virus Total summary data, if enabled on the server
407    /// <https://www.virustotal.com>
408    #[serde(default)]
409    pub vt: Option<VirusTotalSummary>,
410}
411
412impl Display for Report {
413    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
414        writeln!(f, "Size: {} bytes, or {}", self.bytes, self.size)?;
415        writeln!(f, "Entropy: {}", self.entropy)?;
416        if let Some(filecmd) = &self.filecommand {
417            writeln!(f, "File command: {filecmd}")?;
418        }
419        if let Some(vt) = &self.vt {
420            writeln!(f, "VT Hits: {}/{}", vt.hits, vt.total)?;
421        }
422        writeln!(f, "MD5: {}", self.md5)?;
423        writeln!(f, "SHA-1: {}", self.sha1)?;
424        writeln!(f, "SHA256: {}", self.sha256)
425    }
426}
427
428/// API endpoint for finding samples which are similar to a specific file, POST, Authenticated.
429pub const SIMILAR_SAMPLES_URL: &str = "/v1/samples/similar";
430
431/// The hash by which a sample is identified
432#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
433#[non_exhaustive]
434pub enum SimilarityHashType {
435    /// `SSDeep` similarity of the whole file
436    SSDeep,
437
438    /// `LZJD` similarity of the whole file
439    LZJD,
440
441    /// TLSH similarity of the hole file
442    TLSH,
443
444    /// `PEHash`, for PE32 files
445    PEHash,
446
447    /// Import Hash for executable files
448    ImportHash,
449
450    /// `SSDeep` fuzzy hash of the import data, for executable files
451    FuzzyImportHash,
452}
453
454impl SimilarityHashType {
455    /// For a similarity hash type, return:
456    /// * The database table and field which stores the hash
457    /// * If applicable, the similarity hash function which calculates the similarity
458    #[must_use]
459    pub fn get_table_field_simfunc(&self) -> (&'static str, Option<&'static str>) {
460        match self {
461            SimilarityHashType::SSDeep => ("file.ssdeep", Some("fuzzy_hash_compare")),
462            SimilarityHashType::LZJD => ("file.lzjd", Some("lzjd_compare")),
463            SimilarityHashType::TLSH => ("file.tlsh", Some("tlsh_compare")),
464            SimilarityHashType::PEHash => ("executable.pehash", None),
465            SimilarityHashType::ImportHash => ("executable.importhash", None),
466            SimilarityHashType::FuzzyImportHash => {
467                ("executable.importhashfuzzy", Some("fuzzy_hash_compare"))
468            }
469        }
470    }
471}
472
473impl Display for SimilarityHashType {
474    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
475        match self {
476            SimilarityHashType::SSDeep => write!(f, "SSDeep"),
477            SimilarityHashType::LZJD => write!(f, "LZJD"),
478            SimilarityHashType::TLSH => write!(f, "TLSH"),
479            SimilarityHashType::PEHash => write!(f, "PeHash"),
480            SimilarityHashType::ImportHash => write!(f, "Import Hash (IMPHASH)"),
481            SimilarityHashType::FuzzyImportHash => write!(f, "Fuzzy Import hash"),
482        }
483    }
484}
485
486/// Requesting hashes of possible similar samples by similarity hash
487#[derive(Clone, Debug, Deserialize, Serialize)]
488pub struct SimilarSamplesRequest {
489    /// The hashes of the requested sample
490    pub hashes: Vec<(SimilarityHashType, String)>,
491}
492
493/// Relation between a similar sample and the hashes by which the sample is similar
494#[derive(Clone, Debug, Deserialize, Serialize)]
495pub struct SimilarSample {
496    /// The SHA-256 hash of the found sample
497    pub sha256: String,
498
499    /// Matches from the requested sample to this sample by algorithm and score
500    pub algorithms: Vec<(SimilarityHashType, f32)>,
501}
502
503/// Response indicating samples which are similar
504#[derive(Clone, Debug, Deserialize, Serialize)]
505pub struct SimilarSamplesResponse {
506    /// The responses
507    pub results: Vec<SimilarSample>,
508
509    /// Possible messages from the server, if any
510    pub message: Option<String>,
511}
512
513/// APU endpoint for searching for files with some criteria
514pub const SEARCH_URL: &str = "/v1/search";
515
516/// Searching the next batch from a prior search, or the initial search
517#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
518pub enum SearchType {
519    /// The next batch of results from a prior search
520    Continuation(uuid::Uuid),
521
522    /// The initial search
523    Search(SearchRequestParameters),
524}
525
526/// Search for a file by some criteria, all of which are an AND operation:
527/// * Partial hash
528/// * Name of the sample
529/// * Type of the sample
530/// * Libmagic description of the sample
531/// * Labels applied to the sample
532#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
533pub struct SearchRequestParameters {
534    /// Search for a file by partial hash
535    pub partial_hash: Option<(PartialHashSearchType, String)>,
536
537    /// Search for a file by whole or partial file name
538    pub file_name: Option<String>,
539
540    /// Maximum number of results to return, 100 results or fewer.
541    pub limit: u32,
542
543    /// Optionally search for samples of a specific file type.
544    pub file_type: Option<String>,
545
546    /// Optionally search for samples based on `libmagic`, also known as the file command.
547    pub magic: Option<String>,
548
549    /// Optionally search for samples with specific label(s).
550    pub labels: Option<Vec<String>>,
551
552    /// Get the returned result by a hash type.
553    /// [`PartialHashSearchType::Any`] results in SHA-256
554    pub response: PartialHashSearchType,
555}
556
557impl SearchRequestParameters {
558    /// Ensure the search request is valid:
559    /// * The partial hash is valid hexidecimal, if present
560    /// * At least one search parameter is provided
561    /// * The limit must be greater than zero
562    #[must_use]
563    #[inline]
564    pub fn is_valid(&self) -> bool {
565        if self.limit == 0 {
566            return false;
567        }
568
569        if let Some((_hash_type, partial_hash)) = &self.partial_hash {
570            let hex = hex::decode(partial_hash);
571            return hex.is_ok();
572        }
573
574        self.partial_hash.is_some()
575            || self.file_name.is_some()
576            || self.file_type.is_some()
577            || self.magic.is_some()
578            || self.labels.is_some()
579    }
580}
581
582/// This trait implementation is provided as a convenience. This does not create a valid object.
583impl Default for SearchRequestParameters {
584    fn default() -> Self {
585        Self {
586            partial_hash: None,
587            file_name: None,
588            limit: 100,
589            labels: None,
590            file_type: None,
591            magic: None,
592            response: PartialHashSearchType::default(),
593        }
594    }
595}
596
597/// Search for a file by some criteria
598/// Specifying both a hash and file name is an AND operation!
599#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
600pub struct SearchRequest {
601    /// Search or continuation of a search
602    pub search: SearchType,
603}
604
605impl SearchRequest {
606    /// Ensure the search request is valid:
607    /// * The partial hash is valid hexidecimal
608    /// * At least a file path or partial hash is provided
609    #[must_use]
610    #[inline]
611    pub fn is_valid(&self) -> bool {
612        if let SearchType::Search(search) = &self.search {
613            search.is_valid()
614        } else {
615            true
616        }
617    }
618}
619
620/// Search result
621#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
622pub struct SearchResponse {
623    /// Hashes of samples which match the search criteria
624    pub hashes: Vec<String>,
625
626    /// Identifier for getting the next batch of results
627    pub pagination: Option<uuid::Uuid>,
628
629    /// The total number of samples which match the search criteria
630    pub total_results: u64,
631
632    /// Optional server messages
633    pub message: Option<String>,
634}
635
636/// Specify the type of hash when searching for a partial match
637#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
638pub enum PartialHashSearchType {
639    /// Search by any known hash type
640    Any,
641
642    /// Search only for MD5 hashes
643    MD5,
644
645    /// Search only for SHA-1 hashes
646    SHA1,
647
648    /// Search only for SHA-256 hashes
649    #[default]
650    SHA256,
651
652    /// Search only for SHA-384 hashes
653    SHA384,
654
655    /// Search only for SHA-512 hashes
656    SHA512,
657}
658
659impl Display for PartialHashSearchType {
660    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
661        match self {
662            PartialHashSearchType::Any => write!(f, "any"),
663            PartialHashSearchType::MD5 => write!(f, "md5"),
664            PartialHashSearchType::SHA1 => write!(f, "sha1"),
665            PartialHashSearchType::SHA256 => write!(f, "sha256"),
666            PartialHashSearchType::SHA384 => write!(f, "sha384"),
667            PartialHashSearchType::SHA512 => write!(f, "sha512"),
668        }
669    }
670}
671
672impl TryInto<PartialHashSearchType> for &str {
673    type Error = String;
674
675    fn try_into(self) -> Result<PartialHashSearchType, Self::Error> {
676        match self {
677            "any" => Ok(PartialHashSearchType::Any),
678            "md5" => Ok(PartialHashSearchType::MD5),
679            "sha1" => Ok(PartialHashSearchType::SHA1),
680            "sha256" => Ok(PartialHashSearchType::SHA256),
681            "sha384" => Ok(PartialHashSearchType::SHA384),
682            "sha512" => Ok(PartialHashSearchType::SHA512),
683            x => Err(format!("Invalid hash type {x}")),
684        }
685    }
686}
687
688impl TryInto<PartialHashSearchType> for Option<&str> {
689    type Error = String;
690
691    fn try_into(self) -> Result<PartialHashSearchType, Self::Error> {
692        if let Some(hash) = self {
693            hash.try_into()
694        } else {
695            Ok(PartialHashSearchType::SHA256)
696        }
697    }
698}
699
700/// API endpoint for searching for samples using YARA rules.
701/// * POST: submit the search request
702/// * GET: get the search results or check on status
703pub const YARA_SEARCH_URL: &str = "/v1/yara";
704
705/// Search for samples using YARA
706#[derive(Clone, Debug, Deserialize, Serialize)]
707pub struct YaraSearchRequest {
708    /// The Yara rules
709    pub rules: Vec<String>,
710
711    /// Get the returned result by a hash type.
712    /// [`PartialHashSearchType::Any`] results in SHA-256
713    pub response: PartialHashSearchType,
714}
715
716/// Provide the client the UUID of the search request.
717#[derive(Clone, Debug, Deserialize, Serialize)]
718pub struct YaraSearchRequestResponse {
719    /// UUID response
720    pub uuid: uuid::Uuid,
721}
722
723/// Search result from Yara
724#[derive(Clone, Debug, Deserialize, Serialize)]
725pub struct YaraSearchResponse {
726    /// Vector of pairs of hash and Yara search name
727    pub results: HashMap<String, Vec<HashType>>,
728}
729
730/// API endpoint for finding samples which are similar to a specific file, POST
731pub const LIST_LABELS_URL: &str = "/v1/labels";
732
733/// A label, used for describing sources and/or samples
734#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
735pub struct Label {
736    /// Label ID
737    pub id: u64,
738
739    /// Label value
740    pub name: String,
741
742    /// Label parent
743    pub parent: Option<String>,
744}
745
746/// One or more available labels
747#[derive(Clone, Debug, Default, Deserialize, Serialize)]
748pub struct Labels(pub Vec<Label>);
749
750// Convenience functions
751impl Labels {
752    /// Number of labels
753    #[must_use]
754    pub fn len(&self) -> usize {
755        self.0.len()
756    }
757
758    /// If the labels are empty
759    #[must_use]
760    pub fn is_empty(&self) -> bool {
761        self.0.is_empty()
762    }
763}
764
765impl Display for Labels {
766    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
767        if self.is_empty() {
768            return writeln!(f, "No labels.");
769        }
770        for label in &self.0 {
771            let parent = if let Some(parent) = &label.parent {
772                format!(", parent: {parent}")
773            } else {
774                String::new()
775            };
776            writeln!(f, "{}: {}{parent}", label.id, label.name)?;
777        }
778        Ok(())
779    }
780}