|
| 1 | +use rand::{distributions::Uniform, rngs::OsRng, Rng}; |
| 2 | +use sha2::{Digest, Sha256}; |
| 3 | + |
| 4 | +const TOKEN_LENGTH: usize = 32; |
| 5 | + |
| 6 | +pub(crate) struct SecureToken { |
| 7 | + sha256: Vec<u8>, |
| 8 | +} |
| 9 | + |
| 10 | +impl SecureToken { |
| 11 | + pub(crate) fn generate(kind: SecureTokenKind) -> NewSecureToken { |
| 12 | + let plaintext = format!( |
| 13 | + "{}{}", |
| 14 | + kind.prefix(), |
| 15 | + generate_secure_alphanumeric_string(TOKEN_LENGTH) |
| 16 | + ); |
| 17 | + let sha256 = Sha256::digest(plaintext.as_bytes()).as_slice().to_vec(); |
| 18 | + |
| 19 | + NewSecureToken { |
| 20 | + plaintext, |
| 21 | + inner: Self { sha256 }, |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + pub(crate) fn parse(kind: SecureTokenKind, plaintext: &str) -> Option<Self> { |
| 26 | + // This will both reject tokens without a prefix and tokens of the wrong kind. |
| 27 | + if SecureTokenKind::from_token(plaintext) != Some(kind) { |
| 28 | + return None; |
| 29 | + } |
| 30 | + |
| 31 | + let sha256 = Sha256::digest(plaintext.as_bytes()).as_slice().to_vec(); |
| 32 | + Some(Self { sha256 }) |
| 33 | + } |
| 34 | + |
| 35 | + pub(crate) fn sha256(&self) -> &[u8] { |
| 36 | + &self.sha256 |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +pub(crate) struct NewSecureToken { |
| 41 | + plaintext: String, |
| 42 | + inner: SecureToken, |
| 43 | +} |
| 44 | + |
| 45 | +impl NewSecureToken { |
| 46 | + pub(crate) fn plaintext(&self) -> &str { |
| 47 | + &self.plaintext |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl std::ops::Deref for NewSecureToken { |
| 52 | + type Target = SecureToken; |
| 53 | + |
| 54 | + fn deref(&self) -> &Self::Target { |
| 55 | + &self.inner |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +fn generate_secure_alphanumeric_string(len: usize) -> String { |
| 60 | + const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; |
| 61 | + |
| 62 | + OsRng |
| 63 | + .sample_iter(Uniform::from(0..CHARS.len())) |
| 64 | + .map(|idx| CHARS[idx] as char) |
| 65 | + .take(len) |
| 66 | + .collect() |
| 67 | +} |
| 68 | + |
| 69 | +macro_rules! secure_token_kind { |
| 70 | + ($(#[$attr:meta])* $vis:vis enum $name:ident { $($key:ident => $repr:expr,)* }) => { |
| 71 | + $(#[$attr])* |
| 72 | + $vis enum $name { |
| 73 | + $($key,)* |
| 74 | + } |
| 75 | + |
| 76 | + impl $name { |
| 77 | + const VARIANTS: &'static [Self] = &[$(Self::$key,)*]; |
| 78 | + |
| 79 | + fn prefix(&self) -> &'static str { |
| 80 | + match self { |
| 81 | + $(Self::$key => $repr,)* |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +secure_token_kind! { |
| 89 | + /// Represents every kind of secure token generated by crates.io. When you need to generate a |
| 90 | + /// new kind of token you should also add its own kind with its own unique prefix. |
| 91 | + /// |
| 92 | + /// NEVER CHANGE THE PREFIX OF EXISTING TOKEN TYPES!!! Doing so will implicitly revoke all the |
| 93 | + /// tokens of that kind, distrupting production users. |
| 94 | + #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] |
| 95 | + pub(crate) enum SecureTokenKind { |
| 96 | + API => "cio", // Crates.IO |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +impl SecureTokenKind { |
| 101 | + fn from_token(token: &str) -> Option<Self> { |
| 102 | + Self::VARIANTS |
| 103 | + .iter() |
| 104 | + .find(|v| token.starts_with(v.prefix())) |
| 105 | + .copied() |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +#[cfg(test)] |
| 110 | +mod tests { |
| 111 | + use super::*; |
| 112 | + use std::collections::HashSet; |
| 113 | + |
| 114 | + #[test] |
| 115 | + fn test_generated_and_parse() { |
| 116 | + const KIND: SecureTokenKind = SecureTokenKind::API; |
| 117 | + |
| 118 | + let token = SecureToken::generate(KIND); |
| 119 | + assert!(token.plaintext().starts_with(KIND.prefix())); |
| 120 | + assert_eq!( |
| 121 | + token.sha256(), |
| 122 | + Sha256::digest(token.plaintext().as_bytes()).as_slice() |
| 123 | + ); |
| 124 | + |
| 125 | + let parsed = |
| 126 | + SecureToken::parse(KIND, &token.plaintext()).expect("failed to parse back the token"); |
| 127 | + assert_eq!(parsed.sha256(), token.sha256()); |
| 128 | + } |
| 129 | + |
| 130 | + #[test] |
| 131 | + fn test_parse_no_kind() { |
| 132 | + assert!(SecureToken::parse(SecureTokenKind::API, "nokind").is_none()); |
| 133 | + } |
| 134 | + |
| 135 | + #[test] |
| 136 | + fn test_persistent_prefixes() { |
| 137 | + // Changing prefixes will implicitly revoke all the tokens of that kind, disrupting users. |
| 138 | + // This test serves as a reminder for future maintainers not to change the prefixes, and |
| 139 | + // to ensure all the variants are tested by this test. |
| 140 | + let mut remaining: HashSet<_> = SecureTokenKind::VARIANTS.iter().copied().collect(); |
| 141 | + let mut ensure = |kind: SecureTokenKind, prefix| { |
| 142 | + assert_eq!(kind.prefix(), prefix); |
| 143 | + remaining.remove(&kind); |
| 144 | + }; |
| 145 | + |
| 146 | + ensure(SecureTokenKind::API, "cio"); |
| 147 | + |
| 148 | + assert!( |
| 149 | + remaining.is_empty(), |
| 150 | + "not all variants have a test to check the prefix" |
| 151 | + ); |
| 152 | + } |
| 153 | + |
| 154 | + #[test] |
| 155 | + fn test_conflicting_prefixes() { |
| 156 | + // This sanity check prevents multiple tokens from starting with the same prefix, which |
| 157 | + // would mess up the token kind detection. If this test fails after adding another variant |
| 158 | + // do not change the test, choose another prefix instead. |
| 159 | + for variant in SecureTokenKind::VARIANTS { |
| 160 | + for other in SecureTokenKind::VARIANTS { |
| 161 | + if variant == other { |
| 162 | + continue; |
| 163 | + } |
| 164 | + if variant.prefix().starts_with(other.prefix()) { |
| 165 | + panic!("variants {:?} and {:?} share a prefix", variant, other); |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | + } |
| 170 | +} |
0 commit comments