diff --git a/crates/schema/public/tokens/src/prefixes.rs b/crates/schema/public/tokens/src/prefixes.rs index fba133d614..671f543701 100644 --- a/crates/schema/public/tokens/src/prefixes.rs +++ b/crates/schema/public/tokens/src/prefixes.rs @@ -23,6 +23,7 @@ use strum::EnumIter; #[cfg_attr(test, derive(EnumIter, EnumCount))] pub(crate) enum TokenPrefix { AnonymousVisitorTracking, // AVTs are not stored as primary keys in any table, but an index in many tables. + ApiKey, AppSession, // NB: These are generated client-side (!) AuditLog, BatchGeneration, @@ -112,6 +113,7 @@ impl PrefixGenerator for TokenPrefix { fn prefix(self) -> &'static str { match self { Self::AnonymousVisitorTracking => "avt_", + Self::ApiKey => "api_key_", Self::AppSession => "app_session_", Self::AuditLog => "audit_", Self::BatchGeneration => "batch_g_", @@ -348,6 +350,7 @@ mod tests { || prefix == "INT_API:" || prefix == "batch_g_" || prefix == "beta_key_" + || prefix == "api_key_" || prefix == "email_job_" || prefix == "pw_reset_" || prefix == "tts_task_" diff --git a/crates/schema/public/tokens/src/tokens/api_keys.rs b/crates/schema/public/tokens/src/tokens/api_keys.rs new file mode 100644 index 0000000000..2125b8dc8e --- /dev/null +++ b/crates/schema/public/tokens/src/tokens/api_keys.rs @@ -0,0 +1,17 @@ +use std::fmt::Debug; + +use serde::Deserialize; +use serde::Serialize; +use utoipa::ToSchema; + +use crate::prefixes::TokenPrefix; + +/// The primary key for api_keys. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Serialize, Deserialize, Default, ToSchema)] +#[cfg_attr(feature = "database", derive(sqlx::Type))] +#[cfg_attr(feature = "database", sqlx(transparent))] +pub struct ApiKeyToken(pub String); + +impl_mysql_token_from_row!(ApiKeyToken); +impl_string_token!(ApiKeyToken); +impl_crockford_generator!(ApiKeyToken, 32usize, TokenPrefix::ApiKey, CrockfordLower); diff --git a/crates/schema/public/tokens/src/tokens/mod.rs b/crates/schema/public/tokens/src/tokens/mod.rs index c2aa44c55c..0d356f836f 100644 --- a/crates/schema/public/tokens/src/tokens/mod.rs +++ b/crates/schema/public/tokens/src/tokens/mod.rs @@ -1,4 +1,5 @@ pub mod anonymous_visitor_tracking; +pub mod api_keys; pub mod api_tokens_external; pub mod api_tokens_internal; pub mod app_session; diff --git a/crates/service/web/storyteller_web/src/util/generate_api_key.rs b/crates/service/web/storyteller_web/src/util/generate_api_key.rs new file mode 100644 index 0000000000..e6e486a3e8 --- /dev/null +++ b/crates/service/web/storyteller_web/src/util/generate_api_key.rs @@ -0,0 +1,114 @@ +use rand::Rng; + +/// All Artcraft API keys begin with this prefix. It counts toward the total key length. +/// +/// The underscores in this literal are the ONLY underscores permitted in a key — the random +/// suffix is pure Crockford-lowercase alphanumeric. (Well-known keys do this too: Stripe uses +/// `sk_live_`, GitHub `ghp_`, etc. — a readable prefix plus a long random body.) +const API_KEY_PREFIX: &str = "artcraft_api_"; + +/// Crockford base32 lowercase alphabet — 32 symbols, deliberately excluding the ambiguous +/// `i`, `l`, `o`, `u`. Every symbol is alphanumeric, so keys never contain `.`, `+`, `/`, `_`, +/// or any other punctuation in the random body. Each symbol carries log2(32) = 5 bits. +/// +/// NB: Unlike Stripe/GitHub keys (which use a full base-36 `0-9a-z` alphabet), ours is Crockford +/// so the body is unambiguous to read/transcribe. +const CROCKFORD_LOWERCASE_CHARSET: &[u8] = b"0123456789abcdefghjkmnpqrstvwxyz"; + +/// Number of random Crockford characters in the entropy suffix. +/// +/// 40 symbols * 5 bits = **200 bits** of entropy — far above the ~128-bit cryptographic-security +/// floor, and ahead of a typical Stripe secret key (~24 base-36 chars ≈ 124 bits). The total key +/// length is therefore `API_KEY_PREFIX.len() + 40` = 53 characters. +const ENTROPY_CHAR_COUNT: usize = 40; + +/// Generate a cryptographically-secure Artcraft API key, e.g. +/// `artcraft_api_3k7q9w0xv2hs5n8m4d6r1t...` (40 Crockford chars after the prefix). +/// +/// Infallible: it draws from the thread-local CSPRNG (`rand::rng()`, a ChaCha-based, OS-seeded +/// generator), which never fails. +pub fn generate_api_key() -> String { + let mut rng = rand::rng(); + + let mut key = String::with_capacity(API_KEY_PREFIX.len() + ENTROPY_CHAR_COUNT); + key.push_str(API_KEY_PREFIX); + + for _ in 0..ENTROPY_CHAR_COUNT { + let index = rng.random_range(0..CROCKFORD_LOWERCASE_CHARSET.len()); + key.push(CROCKFORD_LOWERCASE_CHARSET[index] as char); + } + + key +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use super::*; + + #[test] + fn starts_with_prefix() { + assert!(generate_api_key().starts_with("artcraft_api_")); + assert!(generate_api_key().starts_with(API_KEY_PREFIX)); + } + + #[test] + fn has_expected_total_length() { + assert_eq!(generate_api_key().len(), API_KEY_PREFIX.len() + ENTROPY_CHAR_COUNT); + } + + #[test] + fn entropy_suffix_is_crockford_lowercase() { + let key = generate_api_key(); + let suffix = key.strip_prefix(API_KEY_PREFIX).expect("key must start with the prefix"); + + assert_eq!(suffix.len(), ENTROPY_CHAR_COUNT); + for byte in suffix.bytes() { + assert!( + CROCKFORD_LOWERCASE_CHARSET.contains(&byte), + "unexpected character {:?} in entropy suffix", + byte as char, + ); + } + // Crockford excludes the ambiguous i, l, o, u. + assert!(!suffix.contains(['i', 'l', 'o', 'u'])); + } + + #[test] + fn forbidden_characters_are_absent() { + let key = generate_api_key(); + for forbidden in ['.', '+', '/'] { + assert!(!key.contains(forbidden), "key must not contain {:?}", forbidden); + } + } + + #[test] + fn underscores_only_appear_in_the_prefix() { + let key = generate_api_key(); + let suffix = key.strip_prefix(API_KEY_PREFIX).expect("key must start with the prefix"); + assert!(!suffix.contains('_'), "the random body must not contain underscores"); + } + + #[test] + fn entropy_suffix_is_alphanumeric() { + let key = generate_api_key(); + let suffix = key.strip_prefix(API_KEY_PREFIX).expect("key must start with the prefix"); + assert!(suffix.chars().all(|c| c.is_ascii_alphanumeric())); + } + + #[test] + fn entropy_is_cryptographically_sufficient() { + // 32-symbol alphabet => 5 bits per character. Require a comfortable margin over 128 bits. + let bits = ENTROPY_CHAR_COUNT * 5; + assert!(bits >= 128, "insufficient entropy: {bits} bits"); + } + + #[test] + fn keys_are_unique() { + let mut seen = HashSet::new(); + for _ in 0..1000 { + assert!(seen.insert(generate_api_key()), "generated a duplicate key"); + } + } +} diff --git a/crates/service/web/storyteller_web/src/util/mod.rs b/crates/service/web/storyteller_web/src/util/mod.rs index 3dbe31fbd1..54665af215 100644 --- a/crates/service/web/storyteller_web/src/util/mod.rs +++ b/crates/service/web/storyteller_web/src/util/mod.rs @@ -7,6 +7,7 @@ pub mod cleaners; pub mod delete_role_disambiguation; pub mod encrypted_sort_id; pub mod enroll_in_studio; +pub mod generate_api_key; pub mod http_download_url_to_bytes; pub mod http_download_url_to_tempfile; pub mod lookup;