spinoso_securerandom/lib.rs
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 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![allow(unknown_lints)]
#![allow(clippy::manual_let_else)]
#![warn(missing_docs)]
#![warn(missing_debug_implementations)]
#![warn(missing_copy_implementations)]
#![warn(rust_2018_idioms)]
#![warn(rust_2021_compatibility)]
#![warn(trivial_casts, trivial_numeric_casts)]
#![warn(unused_qualifications)]
#![warn(variant_size_differences)]
#![forbid(unsafe_code)]
// Enable feature callouts in generated documentation:
// https://doc.rust-lang.org/beta/unstable-book/language-features/doc-cfg.html
//
// This approach is borrowed from tokio.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, feature(doc_alias))]
//! Secure random number generator interface.
//!
//! This module implements the [`SecureRandom`] package from the Ruby Standard
//! Library. It is an interface to secure random number generators which are
//! suitable for generating session keys in HTTP cookies, etc.
//!
//! This implementation of `SecureRandom` supports the system RNG via the
//! [`getrandom`] crate. This implementation does not depend on OpenSSL.
//!
//! # Examples
//!
//! Generate cryptographically secure random bytes:
//!
//! ```rust
//! # fn example() -> Result<(), spinoso_securerandom::Error> {
//! let bytes = spinoso_securerandom::random_bytes(Some(1024))?;
//! assert_eq!(bytes.len(), 1024);
//! # Ok(())
//! # }
//! # example().unwrap()
//! ```
//!
//! Generate base64-encoded random data:
//!
//! ```rust
//! # fn example() -> Result<(), spinoso_securerandom::Error> {
//! let bytes = spinoso_securerandom::base64(Some(1024))?;
//! assert_eq!(bytes.len(), 1368);
//! assert!(bytes.is_ascii());
//! # Ok(())
//! # }
//! # example().unwrap()
//! ```
//!
//! Generate random floats and integers in a range bounded from zero to a
//! maximum:
//!
//! ```rust
//! # use spinoso_securerandom::{DomainError, Max, Rand};
//! # fn example() -> Result<(), DomainError> {
//! let rand = spinoso_securerandom::random_number(Max::None)?;
//! assert!(matches!(rand, Rand::Float(_)));
//!
//! let rand = spinoso_securerandom::random_number(Max::Integer(57))?;
//! assert!(matches!(rand, Rand::Integer(_)));
//!
//! let rand = spinoso_securerandom::random_number(Max::Float(57.0))?;
//! assert!(matches!(rand, Rand::Float(_)));
//! # Ok(())
//! # }
//! # example().unwrap()
//! ```
//!
//! Generate version 4 random UUIDs:
//!
//! ```rust
//! # fn example() -> Result<(), spinoso_securerandom::Error> {
//! let uuid = spinoso_securerandom::uuid()?;
//! assert_eq!(uuid.len(), 36);
//! assert!(uuid.chars().all(|ch| ch == '-' || ch.is_ascii_hexdigit()));
//! # Ok(())
//! # }
//! # example().unwrap()
//! ```
//!
//! [`SecureRandom`]: https://ruby-doc.org/stdlib-3.1.2/libdoc/securerandom/rdoc/SecureRandom.html
//! [`getrandom`]: https://crates.io/crates/getrandom
// Ensure code blocks in `README.md` compile
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme {}
use core::fmt;
use std::collections::TryReserveError;
use std::error;
use rand::distributions::Alphanumeric;
use rand::rngs::OsRng;
use rand::{CryptoRng, Rng, RngCore};
use scolapasta_hex as hex;
mod uuid;
const DEFAULT_REQUESTED_BYTES: usize = 16;
/// Sum type of all errors possibly returned from [`random_bytes`].
///
/// `random_bytes` can return errors under several conditions:
///
/// - The given byte length is not a valid [`usize`].
/// - The underlying source of randomness returns an error when generating the
/// requested random bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
/// Error that indicates an argument parsing or value logic error occurred.
///
/// See [`ArgumentError`].
Argument(ArgumentError),
/// Error that indicates the underlying source of randomness failed to
/// generate the requested random bytes.
///
/// See [`RandomBytesError`].
RandomBytes(RandomBytesError),
/// Error that indicates an error was received from the memory allocator.
///
/// This may mean that too many random bytes were requested or the system is
/// out of memory.
///
/// See [`TryReserveError`] and [`TryReserveErrorKind`] for more information.
///
/// [`TryReserveErrorKind`]: std::collections::TryReserveErrorKind
Memory(TryReserveError),
}
impl From<ArgumentError> for Error {
#[inline]
fn from(err: ArgumentError) -> Self {
Self::Argument(err)
}
}
impl From<RandomBytesError> for Error {
#[inline]
fn from(err: RandomBytesError) -> Self {
Self::RandomBytes(err)
}
}
impl From<rand::Error> for Error {
#[inline]
fn from(err: rand::Error) -> Self {
Self::from(RandomBytesError::from(err))
}
}
impl From<TryReserveError> for Error {
fn from(err: TryReserveError) -> Self {
Self::Memory(err)
}
}
impl fmt::Display for Error {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SecureRandom error")
}
}
impl error::Error for Error {
#[inline]
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Self::Argument(ref err) => Some(err),
Self::RandomBytes(ref err) => Some(err),
Self::Memory(ref err) => Some(err),
}
}
}
/// Error that indicates an argument parsing or value logic error occurred.
///
/// Argument errors have an associated message.
///
/// This error corresponds to the [Ruby `ArgumentError` Exception class].
///
/// # Examples
///
/// ```
/// # use spinoso_securerandom::ArgumentError;
/// let err = ArgumentError::new();
/// assert_eq!(err.message(), "ArgumentError");
///
/// let err = ArgumentError::with_message("negative string size (or size too big)");
/// assert_eq!(err.message(), "negative string size (or size too big)");
/// ```
///
/// [Ruby `ArgumentError` Exception class]: https://ruby-doc.org/core-3.1.2/ArgumentError.html
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct ArgumentError(&'static str);
impl From<&'static str> for ArgumentError {
#[inline]
fn from(message: &'static str) -> Self {
Self::with_message(message)
}
}
impl Default for ArgumentError {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for ArgumentError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.message())
}
}
impl error::Error for ArgumentError {}
impl ArgumentError {
/// Construct a new, default argument error.
///
/// # Examples
///
/// ```
/// # use spinoso_securerandom::ArgumentError;
/// const ERR: ArgumentError = ArgumentError::new();
/// assert_eq!(ERR.message(), "ArgumentError");
/// ```
#[inline]
#[must_use]
pub const fn new() -> Self {
Self("ArgumentError")
}
/// Construct a new argument error with a message.
///
/// # Examples
///
/// ```
/// # use spinoso_securerandom::ArgumentError;
/// const ERR: ArgumentError =
/// ArgumentError::with_message("negative string size (or size too big)");
/// assert_eq!(ERR.message(), "negative string size (or size too big)");
/// ```
#[inline]
#[must_use]
pub const fn with_message(message: &'static str) -> Self {
Self(message)
}
/// Retrieve the exception message associated with this argument error.
///
/// # Examples
///
/// ```
/// # use spinoso_securerandom::ArgumentError;
/// let err = ArgumentError::new();
/// assert_eq!(err.message(), "ArgumentError");
///
/// let err = ArgumentError::with_message("negative string size (or size too big)");
/// assert_eq!(err.message(), "negative string size (or size too big)");
/// ```
#[inline]
#[must_use]
pub const fn message(self) -> &'static str {
self.0
}
}
/// Error that indicates the underlying source of randomness failed to generate
/// the requested random bytes.
///
/// This error is typically returned by the operating system.
#[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct RandomBytesError {
_private: (),
}
impl fmt::Display for RandomBytesError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.message())
}
}
impl error::Error for RandomBytesError {}
impl RandomBytesError {
/// Construct a new, default random bytes error.
///
/// # Examples
///
/// ```
/// # use spinoso_securerandom::RandomBytesError;
/// const ERR: RandomBytesError = RandomBytesError::new();
/// assert_eq!(ERR.message(), "OS Error: Failed to generate random bytes");
/// ```
#[inline]
#[must_use]
pub const fn new() -> Self {
Self { _private: () }
}
/// Retrieve the exception message associated with this random bytes error.
///
/// # Examples
///
/// ```
/// # use spinoso_securerandom::RandomBytesError;
/// let err = RandomBytesError::new();
/// assert_eq!(err.message(), "OS Error: Failed to generate random bytes");
/// ```
#[inline]
#[must_use]
pub const fn message(self) -> &'static str {
"OS Error: Failed to generate random bytes"
}
}
impl From<rand::Error> for RandomBytesError {
fn from(_: rand::Error) -> Self {
Self::new()
}
}
/// Error that indicates the given maximum value is not finite and cannot be
/// used to bound a domain for generating random numbers.
///
/// This error is returned by [`random_number`].
#[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct DomainError {
_private: (),
}
impl fmt::Display for DomainError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.message())
}
}
impl error::Error for DomainError {}
impl DomainError {
/// Construct a new, default domain error.
///
/// # Examples
///
/// ```
/// # use spinoso_securerandom::DomainError;
/// const ERR: DomainError = DomainError::new();
/// assert_eq!(ERR.message(), "Numerical argument out of domain");
/// ```
#[inline]
#[must_use]
pub const fn new() -> Self {
Self { _private: () }
}
/// Retrieve the exception message associated with this domain error.
///
/// # Examples
///
/// ```
/// # use spinoso_securerandom::DomainError;
/// let err = DomainError::new();
/// assert_eq!(err.message(), "Numerical argument out of domain");
/// ```
#[inline]
#[must_use]
pub const fn message(self) -> &'static str {
"Numerical argument out of domain"
}
}
/// A handle to the underlying secure random number generator.
///
/// This is a copy zero-sized type with no associated methods. This type exists
/// so a Ruby VM can attempt to unbox this type and statically dispatch to
/// functions defined in this crate.
///
/// # Examples
///
/// ```
/// # use spinoso_securerandom::SecureRandom;
/// const RANDOM: SecureRandom = SecureRandom::new();
/// ```
#[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct SecureRandom {
_private: (),
}
impl SecureRandom {
/// Constructs a new, default `SecureRandom`.
///
/// # Examples
///
/// ```
/// # use spinoso_securerandom::SecureRandom;
/// const RANDOM: SecureRandom = SecureRandom::new();
/// ```
#[inline]
#[must_use]
pub const fn new() -> Self {
Self { _private: () }
}
}
/// Generate a vector of random bytes.
///
/// If `len` is [`Some`] and non-negative, generate a vector of `len` random
/// bytes. If `len` is [`None`], generate 16 random bytes.
///
/// # Examples
///
/// ```rust
/// # fn example() -> Result<(), spinoso_securerandom::Error> {
/// let bytes = spinoso_securerandom::random_bytes(Some(1024))?;
/// assert_eq!(bytes.len(), 1024);
/// # Ok(())
/// # }
/// # example().unwrap()
/// ```
///
/// # Errors
///
/// If the given length is negative, return an [`ArgumentError`].
///
/// If the underlying source of randomness returns an error, return a
/// [`RandomBytesError`].
///
/// If an allocation error occurs, an error is returned.
#[inline]
pub fn random_bytes(len: Option<i64>) -> Result<Vec<u8>, Error> {
fn get_random_bytes<T: RngCore + CryptoRng>(mut rng: T, slice: &mut [u8]) -> Result<(), RandomBytesError> {
rng.try_fill_bytes(slice)?;
Ok(())
}
let len = match len.map(usize::try_from) {
Some(Ok(0)) => return Ok(Vec::new()),
Some(Ok(len)) => len,
Some(Err(_)) => {
let err = ArgumentError::with_message("negative string size (or size too big)");
return Err(Error::Argument(err));
}
None => DEFAULT_REQUESTED_BYTES,
};
let mut bytes = Vec::new();
bytes.try_reserve(len)?;
bytes.resize(len, 0);
get_random_bytes(OsRng, &mut bytes)?;
Ok(bytes)
}
/// Max value when generating a random number from a range.
///
/// In Ruby, the `rand` family of functions generate random numbers form within
/// a range. This range is always anchored on the left by zero. The `Max` enum
/// allows callers to specify the upper bound of the range. If the `None`
/// variant is given, the default is set to generate floats in the range of
/// `[0.0, 1.0)`.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub enum Max {
/// Generate floats in the range `[0, max)`.
///
/// If `max` is less than or equal to zero, the range defaults to floats
/// in `[0.0, 1.0]`.
///
/// If `max` is [`NaN`](f64::NAN), an error is returned.
Float(f64),
/// Generate signed integers in the range `[0, max)`.
///
/// If `max` is less than or equal to zero, the range defaults to floats
/// in `[0.0, 1.0]`.
Integer(i64),
/// Generate floats in the range `[0.0, 1.0]`.
None,
}
/// Random numeric value generated from the secure random number generator.
///
/// In Ruby, the `rand` family of functions generate random numbers that are
/// either floats or signed integers.
///
/// The numeric contents of this enum will never be negative and will always be
/// finite.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub enum Rand {
/// A random float that is greater than or equal to zero.
Float(f64),
/// A random signed integer that is greater than or equal to zero.
Integer(i64),
}
/// Generate a single random number, either a float or an integer.
///
/// In Ruby, the `rand` family of functions generate random numbers that are
/// either floats or signed integers.
///
/// The random numbers returned by this function will never be negative and will
/// always be finite.
///
/// In Ruby, the `rand` family of functions generate random numbers form within
/// a range. This range is always anchored on the left by zero. See the [`Max`]
/// enum documentation for how to bound the random numbers returned by this
/// function.
///
/// # Examples
///
/// ```rust
/// # use spinoso_securerandom::{Max, Rand};
/// # fn example() -> Result<(), spinoso_securerandom::DomainError> {
/// let rand = spinoso_securerandom::random_number(Max::None)?;
/// assert!(matches!(rand, Rand::Float(_)));
///
/// let rand = spinoso_securerandom::random_number(Max::Integer(57))?;
/// assert!(matches!(rand, Rand::Integer(_)));
///
/// let rand = spinoso_securerandom::random_number(Max::Integer(-20))?;
/// assert!(matches!(rand, Rand::Float(_)));
///
/// let rand = spinoso_securerandom::random_number(Max::Integer(0))?;
/// assert!(matches!(rand, Rand::Float(_)));
///
/// let rand = spinoso_securerandom::random_number(Max::Float(57.0))?;
/// assert!(matches!(rand, Rand::Float(_)));
///
/// let rand = spinoso_securerandom::random_number(Max::Float(-20.0))?;
/// assert!(matches!(rand, Rand::Float(_)));
///
/// let rand = spinoso_securerandom::random_number(Max::Float(0.0))?;
/// assert!(matches!(rand, Rand::Float(_)));
/// # Ok(())
/// # }
/// # example().unwrap()
/// ```
///
/// # Errors
///
/// If the float given in a [`Max::Float`] variant is [`NaN`](f64::NAN) or
/// infinite, a [`DomainError`] is returned.
#[inline]
pub fn random_number(max: Max) -> Result<Rand, DomainError> {
fn get_random_number<T: RngCore + CryptoRng>(mut rng: T, max: Max) -> Result<Rand, DomainError> {
match max {
Max::Float(max) if !max.is_finite() => {
// NOTE: MRI returns `Errno::EDOM` exception class.
Err(DomainError::new())
}
Max::Float(max) if max <= 0.0 => {
let number = rng.gen_range(0.0..1.0);
Ok(Rand::Float(number))
}
Max::Float(max) => {
let number = rng.gen_range(0.0..max);
Ok(Rand::Float(number))
}
Max::Integer(max) if !max.is_positive() => {
let number = rng.gen_range(0.0..1.0);
Ok(Rand::Float(number))
}
Max::Integer(max) => {
let number = rng.gen_range(0..max);
Ok(Rand::Integer(number))
}
Max::None => {
let number = rng.gen_range(0.0..1.0);
Ok(Rand::Float(number))
}
}
}
get_random_number(OsRng, max)
}
/// Generate a hex-encoded [`String`] of random bytes.
///
/// If `len` is [`Some`] and non-negative, generate a vector of `len` random
/// bytes. If `len` is [`None`], generate 16 random bytes. Take the resulting
/// bytes and hexadecimal encode them.
///
/// # Examples
///
/// ```rust
/// # fn example() -> Result<(), spinoso_securerandom::Error> {
/// let bytes = spinoso_securerandom::hex(Some(1024))?;
/// assert_eq!(bytes.len(), 2048);
/// assert!(bytes.is_ascii());
/// # Ok(())
/// # }
/// # example().unwrap()
/// ```
///
/// # Errors
///
/// If the given length is negative, return an [`ArgumentError`].
///
/// If the underlying source of randomness returns an error, return a
/// [`RandomBytesError`].
#[inline]
pub fn hex(len: Option<i64>) -> Result<String, Error> {
let bytes = random_bytes(len)?;
let s = hex::try_encode(bytes)?;
Ok(s)
}
/// Generate a base64-encoded [`String`] of random bytes.
///
/// If `len` is [`Some`] and non-negative, generate a vector of `len` random
/// bytes. If `len` is [`None`], generate 16 random bytes. Take the resulting
/// bytes and base64 encode them.
///
/// # Examples
///
/// ```rust
/// # fn example() -> Result<(), spinoso_securerandom::Error> {
/// let bytes = spinoso_securerandom::base64(Some(1024))?;
/// assert_eq!(bytes.len(), 1368);
/// assert!(bytes.is_ascii());
/// # Ok(())
/// # }
/// # example().unwrap()
/// ```
///
/// # Errors
///
/// If the given length is negative, return an [`ArgumentError`].
///
/// If the underlying source of randomness returns an error, return a
/// [`RandomBytesError`].
#[inline]
pub fn base64(len: Option<i64>) -> Result<String, Error> {
// A `GeneralPurpose` engine using the `alphabet::STANDARD` base64 alphabet
// and PAD config.
use base64::engine::general_purpose::STANDARD;
use base64::engine::Engine as _;
let bytes = random_bytes(len)?;
Ok(STANDARD.encode(bytes))
}
/// Generate a URL-safe base64-encoded [`String`] of random bytes.
///
/// If `len` is [`Some`] and non-negative, generate a vector of `len` random
/// bytes. If `len` is [`None`], generate 16 random bytes. Take the resulting
/// bytes and base64 encode them.
///
/// # Examples
///
/// ```rust
/// # fn example() -> Result<(), spinoso_securerandom::Error> {
/// let bytes = spinoso_securerandom::urlsafe_base64(Some(1024), false)?;
/// assert_eq!(bytes.len(), 1366);
/// assert!(bytes.is_ascii());
/// # Ok(())
/// # }
/// # example().unwrap()
/// ```
///
/// # Errors
///
/// If the given length is negative, return an [`ArgumentError`].
///
/// If the underlying source of randomness returns an error, return a
/// [`RandomBytesError`].
#[inline]
pub fn urlsafe_base64(len: Option<i64>, padding: bool) -> Result<String, Error> {
use base64::engine::general_purpose::{URL_SAFE, URL_SAFE_NO_PAD};
use base64::engine::Engine as _;
let bytes = random_bytes(len)?;
let engine = if padding { URL_SAFE } else { URL_SAFE_NO_PAD };
Ok(engine.encode(bytes))
}
/// Generate a random sequence of ASCII alphanumeric bytes.
///
/// If `len` is [`Some`] and non-negative, generate a [`String`] of `len`
/// random ASCII alphanumeric bytes. If `len` is [`None`], generate 16 random
/// alphanumeric bytes.
///
/// The returned [`Vec<u8>`](Vec) is guaranteed to contain only ASCII bytes.
///
/// # Examples
///
/// ```rust
/// # use std::error::Error;
/// # fn example() -> Result<(), Box<dyn Error>> {
/// let bytes = spinoso_securerandom::alphanumeric(Some(1024))?;
/// let bytes = String::from_utf8(bytes)?;
/// assert_eq!(bytes.len(), 1024);
/// assert!(bytes.is_ascii());
/// assert!(bytes.find(|ch: char| !ch.is_ascii_alphanumeric()).is_none());
/// # Ok(())
/// # }
/// # example().unwrap()
/// ```
///
/// # Errors
///
/// If the given length is negative, return an [`ArgumentError`].
///
/// If an allocation error occurs, an error is returned.
#[inline]
pub fn alphanumeric(len: Option<i64>) -> Result<Vec<u8>, Error> {
fn get_alphanumeric<T: RngCore + CryptoRng>(rng: T, len: usize) -> Result<Vec<u8>, TryReserveError> {
let mut buf = Vec::new();
buf.try_reserve(len)?;
for ch in rng.sample_iter(Alphanumeric).take(len) {
buf.push(ch);
}
Ok(buf)
}
let len = match len.map(usize::try_from) {
Some(Ok(0)) => return Ok(Vec::new()),
Some(Ok(len)) => len,
Some(Err(_)) => {
let err = ArgumentError::with_message("negative string size (or size too big)");
return Err(err.into());
}
None => DEFAULT_REQUESTED_BYTES,
};
let string = get_alphanumeric(OsRng, len)?;
Ok(string)
}
/// Generate a Version 4 (random) UUID and return a [`String`].
///
/// A Version 4 UUID is randomly generated. See [RFC4122] for details.
///
/// # Examples
///
/// ```rust
/// # fn example() -> Result<(), spinoso_securerandom::Error> {
/// let uuid = spinoso_securerandom::uuid()?;
/// assert_eq!(uuid.len(), 36);
/// assert!(uuid.chars().all(|ch| ch == '-' || ch.is_ascii_hexdigit()));
/// # Ok(())
/// # }
/// # example().unwrap()
/// ```
///
/// # Errors
///
/// If the underlying source of randomness returns an error, an error is
/// returned.
///
/// If an allocation error occurs, an error is returned.
///
/// [RFC4122]: https://tools.ietf.org/html/rfc4122#section-4.4
#[inline]
pub fn uuid() -> Result<String, Error> {
uuid::v4()
}
#[cfg(test)]
mod tests {
use core::ops::Not;
use super::{alphanumeric, base64, hex, random_bytes, random_number, uuid, DomainError, Error, Max, Rand};
#[test]
fn random_bytes_default_bytes() {
// https://github.com/ruby/ruby/blob/v2_6_3/lib/securerandom.rb#L135
assert_eq!(super::DEFAULT_REQUESTED_BYTES, 16);
let default_requested_bytes = random_bytes(None).unwrap();
assert_eq!(default_requested_bytes.len(), 16);
}
#[test]
fn random_bytes_len_must_be_positive() {
assert!(matches!(random_bytes(Some(-1)), Err(Error::Argument(_))));
assert!(matches!(base64(Some(-1)), Err(Error::Argument(_))));
assert!(matches!(hex(Some(-1)), Err(Error::Argument(_))));
assert!(alphanumeric(Some(-1)).is_err());
}
#[test]
fn random_bytes_zero_len_gives_empty_result() {
assert!(random_bytes(Some(0)).unwrap().is_empty());
assert!(base64(Some(0)).unwrap().is_empty());
assert!(hex(Some(0)).unwrap().is_empty());
assert!(alphanumeric(Some(0)).unwrap().is_empty());
}
#[test]
fn random_bytes_nonzero_len_gives_len_result() {
assert_eq!(random_bytes(Some(32)).unwrap().len(), 32);
assert_eq!(base64(Some(32)).unwrap().len(), 44);
assert_eq!(hex(Some(32)).unwrap().len(), 64);
assert_eq!(alphanumeric(Some(32)).unwrap().len(), 32);
// for a length that is not a power of two
assert_eq!(random_bytes(Some(57)).unwrap().len(), 57);
assert_eq!(base64(Some(57)).unwrap().len(), 76);
assert_eq!(hex(Some(57)).unwrap().len(), 114);
assert_eq!(alphanumeric(Some(57)).unwrap().len(), 57);
}
#[test]
fn random_bytes_none_len_gives_len_16_result() {
assert_eq!(random_bytes(None).unwrap().len(), 16);
assert_eq!(base64(None).unwrap().len(), 24);
assert_eq!(hex(None).unwrap().len(), 32);
assert_eq!(alphanumeric(None).unwrap().len(), 16);
}
#[test]
fn random_number_domain_error() {
assert_eq!(random_number(Max::Float(f64::NAN)), Err(DomainError::new()));
assert_eq!(random_number(Max::Float(f64::INFINITY)), Err(DomainError::new()));
assert_eq!(random_number(Max::Float(f64::NEG_INFINITY)), Err(DomainError::new()));
}
#[test]
fn random_number_in_float_out_float() {
assert!(matches!(random_number(Max::None), Ok(Rand::Float(_))));
assert!(matches!(random_number(Max::Float(0.5)), Ok(Rand::Float(_))));
assert!(matches!(random_number(Max::Float(1.0)), Ok(Rand::Float(_))));
assert!(matches!(random_number(Max::Float(9000.63)), Ok(Rand::Float(_))));
assert!(matches!(random_number(Max::Float(0.0)), Ok(Rand::Float(_))));
assert!(matches!(random_number(Max::Float(-0.0)), Ok(Rand::Float(_))));
assert!(matches!(random_number(Max::Float(-1.0)), Ok(Rand::Float(_))));
}
#[test]
fn random_number_in_neg_integer_out_float() {
assert!(matches!(random_number(Max::Integer(-1)), Ok(Rand::Float(_))));
}
#[test]
fn random_number_in_zero_integer_out_float() {
assert!(matches!(random_number(Max::Integer(0)), Ok(Rand::Float(_))));
}
#[test]
fn random_number_in_pos_integer_out_integer() {
assert!(matches!(random_number(Max::Integer(1)), Ok(Rand::Integer(_))));
assert!(matches!(random_number(Max::Integer(9000)), Ok(Rand::Integer(_))));
assert!(matches!(random_number(Max::Integer(i64::MAX)), Ok(Rand::Integer(_))));
}
#[test]
fn uuid_format() {
let id = uuid().unwrap();
assert_eq!(id.len(), 36);
assert!(id.chars().all(|ch| ch == '-' || ch.is_ascii_hexdigit()));
assert!(id.chars().any(char::is_uppercase).not());
assert_eq!(&id[14..15], "4");
}
#[test]
fn alphanumeric_format() {
let random = alphanumeric(Some(1024)).unwrap();
assert!(random.iter().all(|&byte| byte.is_ascii_alphanumeric()));
}
}