use crate::api::{Principal, PrincipalKind, TokenVerifier};
use crate::health::BoxFuture;
use sea_orm::entity::prelude::*;
use sea_orm::sea_query::Expr;
use sea_orm::{
ActiveValue::Set, Condition, ConnectionTrait, DatabaseConnection, DbErr, QueryFilter,
QueryOrder, QuerySelect, Schema,
};
use sha2::{Digest, Sha256};
use std::time::Duration;
pub mod api_keys {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "api_keys")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub owner_id: Option<i64>,
#[sea_orm(column_type = "Text")]
pub name: String,
#[sea_orm(unique, column_type = "String(StringLen::N(16))")]
pub prefix: String,
#[sea_orm(column_type = "String(StringLen::N(64))")]
pub secret_hash: String,
#[sea_orm(column_type = "Text")]
pub scopes: String,
pub created_at: i64,
pub last_used_at: Option<i64>,
pub expires_at: Option<i64>,
pub revoked_at: Option<i64>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
use api_keys::{Column, Entity, Model};
const PREFIX_LEN: usize = 8;
const SECRET_LEN: usize = 43;
const KEY_LEN: usize = 4 + PREFIX_LEN + 1 + SECRET_LEN;
const LAST_USED_EVERY: i64 = 60;
#[derive(Debug, thiserror::Error)]
pub enum ApiKeyError {
#[error("database: {0}")]
Db(#[from] DbErr),
#[error("OS random number generator failed")]
Rng,
#[error("invalid api key input: {0}")]
Invalid(&'static str),
}
#[derive(Clone)]
pub struct NewKey {
pub id: i64,
pub prefix: String,
pub plaintext: String,
}
impl std::fmt::Debug for NewKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NewKey")
.field("id", &self.id)
.field("prefix", &self.prefix)
.field("plaintext", &"<redacted>")
.finish()
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct ApiKeyInfo {
pub id: i64,
pub name: String,
pub prefix: String,
pub scopes: Vec<String>,
pub created_at: i64,
pub last_used_at: Option<i64>,
pub expires_at: Option<i64>,
pub revoked_at: Option<i64>,
}
#[derive(Clone)]
pub struct ApiKeys {
db: DatabaseConnection,
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
fn hash(key: &str) -> String {
Sha256::digest(key.as_bytes())
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn ct_eq(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len()
&& std::hint::black_box(a.iter().zip(b).fold(0u8, |d, (x, y)| d | (x ^ y))) == 0
}
fn random<const N: usize>() -> Result<[u8; N], ApiKeyError> {
use rand::TryRng;
let mut raw = [0u8; N];
rand::rngs::SysRng
.try_fill_bytes(&mut raw)
.map_err(|_| ApiKeyError::Rng)?;
Ok(raw)
}
fn b64url(bytes: &[u8]) -> String {
const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let mut out = String::with_capacity(bytes.len() * 4 / 3 + 3);
for c in bytes.chunks(3) {
let n = (c[0] as u32) << 16
| (*c.get(1).unwrap_or(&0) as u32) << 8
| *c.get(2).unwrap_or(&0) as u32;
for i in 0..=c.len() {
out.push(A[(n >> (18 - 6 * i) & 63) as usize] as char);
}
}
out
}
fn parse(key: &str) -> Option<&str> {
let b = key.as_bytes();
let ok = b.len() == KEY_LEN
&& key.starts_with("ryk_")
&& b[4 + PREFIX_LEN] == b'_'
&& b[4..4 + PREFIX_LEN].iter().all(u8::is_ascii_alphanumeric)
&& b[5 + PREFIX_LEN..]
.iter()
.all(|c| c.is_ascii_alphanumeric() || *c == b'-' || *c == b'_');
ok.then(|| &key[4..4 + PREFIX_LEN])
}
fn valid_scope(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 64
&& s.bytes()
.all(|c| matches!(c, b'a'..=b'z' | b'0'..=b'9' | b':' | b'_' | b'*' | b'.' | b'-'))
}
fn split_scopes(s: &str) -> Vec<String> {
s.split_whitespace().map(String::from).collect()
}
fn info(m: Model) -> ApiKeyInfo {
ApiKeyInfo {
id: m.id,
scopes: split_scopes(&m.scopes),
name: m.name,
prefix: m.prefix,
created_at: m.created_at,
last_used_at: m.last_used_at,
expires_at: m.expires_at,
revoked_at: m.revoked_at,
}
}
impl ApiKeys {
pub fn new(db: DatabaseConnection) -> Self {
Self { db }
}
pub async fn ensure_tables(&self) -> Result<(), DbErr> {
let mut t = Schema::new(self.db.get_database_backend()).create_table_from_entity(Entity);
self.db.execute(t.if_not_exists()).await?;
Ok(())
}
pub async fn issue(
&self,
owner: Option<i64>,
name: &str,
scopes: &[&str],
ttl: Option<Duration>,
) -> Result<NewKey, ApiKeyError> {
if !(1..=100).contains(&name.chars().count()) {
return Err(ApiKeyError::Invalid("name must be 1 to 100 characters"));
}
if scopes.len() > 20 || !scopes.iter().all(|s| valid_scope(s)) {
return Err(ApiKeyError::Invalid("at most 20 scopes of [a-z0-9:_*.-]+"));
}
if ttl == Some(Duration::ZERO) {
return Err(ApiKeyError::Invalid("ttl must be greater than zero"));
}
const ALNUM: &[u8; 62] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let prefix = loop {
let p: String = random::<PREFIX_LEN>()?
.iter()
.map(|b| ALNUM[*b as usize % 62] as char)
.collect();
if Entity::find()
.filter(Column::Prefix.eq(p.as_str()))
.one(&self.db)
.await?
.is_none()
{
break p;
}
};
let plaintext = format!("ryk_{prefix}_{}", b64url(&random::<32>()?));
let t = now();
let row = api_keys::ActiveModel {
owner_id: Set(owner),
name: Set(name.into()),
prefix: Set(prefix.clone()),
secret_hash: Set(hash(&plaintext)),
scopes: Set(scopes.join(" ")),
created_at: Set(t),
expires_at: Set(
ttl.map(|d| t.saturating_add(d.as_secs().min(i64::MAX as u64 / 2) as i64))
),
..Default::default()
}
.insert(&self.db)
.await?;
Ok(NewKey {
id: row.id,
prefix,
plaintext,
})
}
pub async fn list(&self, owner: i64) -> Result<Vec<ApiKeyInfo>, ApiKeyError> {
Ok(Entity::find()
.filter(Column::OwnerId.eq(owner))
.order_by_desc(Column::Id)
.all(&self.db)
.await?
.into_iter()
.map(info)
.collect())
}
pub async fn revoke(&self, owner: i64, id: i64) -> Result<bool, ApiKeyError> {
let live = Entity::find_by_id(id)
.filter(Column::OwnerId.eq(owner))
.filter(Column::RevokedAt.is_null())
.one(&self.db)
.await?
.is_some();
if live {
Entity::update_many()
.col_expr(Column::RevokedAt, Expr::value(now()))
.filter(Column::Id.eq(id))
.filter(Column::OwnerId.eq(owner))
.filter(Column::RevokedAt.is_null())
.exec(&self.db)
.await?;
}
Ok(live)
}
pub async fn revoke_all(&self, owner: i64) -> Result<u64, ApiKeyError> {
let live = Entity::find()
.filter(Column::OwnerId.eq(owner))
.filter(Column::RevokedAt.is_null())
.count(&self.db)
.await?;
Entity::update_many()
.col_expr(Column::RevokedAt, Expr::value(now()))
.filter(Column::OwnerId.eq(owner))
.filter(Column::RevokedAt.is_null())
.exec(&self.db)
.await?;
Ok(live)
}
pub async fn prune(&self, retention: Duration) -> Result<u64, ApiKeyError> {
let t = now();
let old = t - retention.as_secs().min(i64::MAX as u64 / 4) as i64;
let dead = Condition::any()
.add(Column::ExpiresAt.lte(t))
.add(Column::RevokedAt.lte(old));
let mut n = 0u64;
loop {
let ids: Vec<i64> = Entity::find()
.filter(dead.clone())
.limit(500)
.all(&self.db)
.await?
.into_iter()
.map(|r| r.id)
.collect();
n += ids.len() as u64;
let full = ids.len() == 500;
Entity::delete_many()
.filter(Column::Id.is_in(ids))
.exec(&self.db)
.await?;
if !full {
return Ok(n);
}
}
}
pub async fn verify(&self, key: &str) -> Option<Principal> {
let prefix = parse(key)?;
let row = match Entity::find()
.filter(Column::Prefix.eq(prefix))
.one(&self.db)
.await
{
Ok(r) => r,
Err(e) => {
tracing::error!("api key lookup failed: {e}");
return None;
}
};
let presented = hash(key);
let stored = row
.as_ref()
.map_or("0".repeat(64), |r| r.secret_hash.clone());
let hash_ok = ct_eq(presented.as_bytes(), stored.as_bytes());
let r = row?;
let t = now();
if !hash_ok || r.revoked_at.is_some() || r.expires_at.is_some_and(|e| e <= t) {
return None;
}
if r.last_used_at.is_none_or(|l| l <= t - LAST_USED_EVERY) {
let touched = Entity::update_many()
.col_expr(Column::LastUsedAt, Expr::value(t))
.filter(Column::Id.eq(r.id))
.exec(&self.db)
.await;
if let Err(e) = touched {
tracing::warn!("api key last_used update failed: {e}");
}
}
Some(Principal {
kind: PrincipalKind::ApiKey,
id: r.id.to_string(),
user_id: r.owner_id,
client_id: None,
scopes: split_scopes(&r.scopes),
name: Some(r.name),
})
}
}
impl TokenVerifier for ApiKeys {
fn verify<'a>(&'a self, bearer: &'a str) -> BoxFuture<'a, Option<Principal>> {
Box::pin(ApiKeys::verify(self, bearer))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn helpers() {
assert!(ct_eq(b"abc", b"abc") && !ct_eq(b"abc", b"abd") && !ct_eq(b"abc", b"ab"));
assert_eq!(b64url(&[0u8; 32]).len(), SECRET_LEN);
let k = format!("ryk_AbCd1234_{}", b64url(&[7u8; 32]));
assert_eq!(k.len(), KEY_LEN);
assert_eq!(parse(&k), Some("AbCd1234"));
for bad in [
"",
"ryk_",
"ryk_AbCd1234_short",
&k.replace("ryk_", "xyz_"),
&format!("{k}x"),
&k.replace('_', "!"),
] {
assert_eq!(parse(bad), None, "{bad}");
}
assert!(valid_scope("posts:read") && valid_scope("*") && valid_scope("a.b-c_d"));
assert!(!valid_scope("") && !valid_scope("Up") && !valid_scope("a b"));
assert!(!valid_scope(&"a".repeat(65)));
}
#[cfg(feature = "sqlite")]
async fn dbs() -> Vec<(&'static str, DatabaseConnection)> {
let ns = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let path = std::env::temp_dir().join(format!("ryuk-apikey-{ns}.db"));
let mut v = vec![(
"sqlite",
sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display()))
.await
.unwrap(),
)];
for (name, var) in [
("postgres", "TEST_POSTGRES_URL"),
("mysql", "TEST_MYSQL_URL"),
] {
if let Ok(url) = std::env::var(var) {
v.push((name, sea_orm::Database::connect(url).await.unwrap()));
}
}
v
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn lifecycle_all_backends() {
for (name, db) in dbs().await {
let k = ApiKeys::new(db.clone());
k.ensure_tables().await.unwrap();
k.ensure_tables().await.unwrap();
let owner = chrono::Utc::now().timestamp_nanos_opt().unwrap();
let other = owner + 1;
let n = k
.issue(Some(owner), "ci", &["posts:read", "posts:*"], None)
.await
.unwrap();
assert_eq!(n.plaintext.len(), KEY_LEN, "{name}");
assert!(n.plaintext.starts_with(&format!("ryk_{}_", n.prefix)));
let p = k.verify(&n.plaintext).await.expect(name);
assert_eq!(p.kind, PrincipalKind::ApiKey);
assert_eq!(p.id, n.id.to_string());
assert_eq!(p.user_id, Some(owner));
assert_eq!(p.name.as_deref(), Some("ci"));
assert_eq!(p.scopes, ["posts:read", "posts:*"]);
assert!(TokenVerifier::verify(&k, &n.plaintext).await.is_some());
let secret = &n.plaintext[13..];
let row = Entity::find_by_id(n.id).one(&db).await.unwrap().unwrap();
assert_eq!(row.secret_hash, hash(&n.plaintext));
assert!(!format!("{row:?}").contains(secret), "{name}");
assert!(!format!("{n:?}").contains(secret));
assert!(k.verify("garbage").await.is_none());
assert!(k.verify("").await.is_none());
let unknown = format!("ryk_ZZZZZZZZ_{secret}");
assert!(k.verify(&unknown).await.is_none(), "{name}");
let wrong = format!("ryk_{}_{}", n.prefix, b64url(&[1u8; 32]));
assert!(k.verify(&wrong).await.is_none(), "{name}");
let used = || async {
Entity::find_by_id(n.id)
.one(&db)
.await
.unwrap()
.unwrap()
.last_used_at
};
let dbr = &db;
let set = |v: i64| async move {
Entity::update_many()
.col_expr(Column::LastUsedAt, Expr::value(v))
.filter(Column::Id.eq(n.id))
.exec(dbr)
.await
.unwrap();
};
let first = used().await.expect("set on first use");
set(first - 10).await;
k.verify(&n.plaintext).await.unwrap();
assert_eq!(used().await, Some(first - 10), "{name}: within 60s");
set(first - 100).await;
k.verify(&n.plaintext).await.unwrap();
assert!(used().await.unwrap() >= first, "{name}: refreshed");
let theirs = k.issue(Some(other), "x", &[], None).await.unwrap();
let l = k.list(owner).await.unwrap();
assert_eq!(l.len(), 1);
assert_eq!(l[0].prefix, n.prefix);
assert!(!format!("{l:?}").contains(secret));
assert!(!k.revoke(owner, theirs.id).await.unwrap(), "{name}");
assert!(k.verify(&theirs.plaintext).await.is_some());
assert!(k.revoke(owner, n.id).await.unwrap(), "{name}");
assert!(!k.revoke(owner, n.id).await.unwrap(), "{name}: twice");
assert!(k.verify(&n.plaintext).await.is_none(), "{name}: revoked");
assert!(k.list(owner).await.unwrap()[0].revoked_at.is_some());
let ttl = Some(Duration::from_secs(3600));
let e = k.issue(None, "sys", &[], ttl).await.unwrap();
assert_eq!(k.verify(&e.plaintext).await.unwrap().user_id, None);
Entity::update_many()
.col_expr(Column::ExpiresAt, Expr::value(now() - 1))
.filter(Column::Id.eq(e.id))
.exec(&db)
.await
.unwrap();
assert!(k.verify(&e.plaintext).await.is_none(), "{name}: expired");
}
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn revoke_all_and_prune() {
for (name, db) in dbs().await {
let k = ApiKeys::new(db.clone());
k.ensure_tables().await.unwrap();
let owner = chrono::Utc::now().timestamp_nanos_opt().unwrap();
let other = owner + 1;
let hour = Duration::from_secs(3600);
let set = |id: i64, c: Column, v: i64| {
let db = db.clone();
async move {
Entity::update_many()
.col_expr(c, Expr::value(v))
.filter(Column::Id.eq(id))
.exec(&db)
.await
.unwrap();
}
};
let there = |id: i64| {
let db = db.clone();
async move { Entity::find_by_id(id).one(&db).await.unwrap().is_some() }
};
let mut mine = Vec::new();
for i in 0..3 {
mine.push(
k.issue(Some(owner), &format!("k{i}"), &["a"], None)
.await
.unwrap(),
);
}
let theirs = k.issue(Some(other), "t", &[], None).await.unwrap();
assert!(k.revoke(owner, mine[0].id).await.unwrap());
assert_eq!(k.revoke_all(owner).await.unwrap(), 2, "{name}");
assert_eq!(k.revoke_all(owner).await.unwrap(), 0, "{name}");
for m in &mine {
assert!(k.verify(&m.plaintext).await.is_none(), "{name}");
}
assert!(
k.verify(&theirs.plaintext).await.is_some(),
"{name}: other owner"
);
assert!(k.prune(hour).await.is_ok());
assert!(there(mine[1].id).await, "{name}");
set(mine[0].id, Column::RevokedAt, now() - 7200).await;
set(mine[2].id, Column::ExpiresAt, now() - 1).await;
set(mine[2].id, Column::RevokedAt, now()).await;
let expired = k.issue(Some(other), "e", &[], Some(hour)).await.unwrap();
set(expired.id, Column::ExpiresAt, now() - 1).await;
assert!(k.prune(hour).await.unwrap() >= 3, "{name}");
assert!(
!there(mine[0].id).await && !there(mine[2].id).await && !there(expired.id).await,
"{name}"
);
assert!(there(mine[1].id).await && there(theirs.id).await, "{name}");
assert!(
k.verify(&theirs.plaintext).await.is_some(),
"{name}: live key survives prune"
);
k.prune(Duration::ZERO).await.unwrap();
assert!(!there(mine[1].id).await && there(theirs.id).await, "{name}");
}
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn issue_validates_input() {
let (_, db) = dbs().await.remove(0);
let k = ApiKeys::new(db);
k.ensure_tables().await.unwrap();
let many = vec!["a"; 21];
let long = "n".repeat(101);
for (name, scopes, ttl) in [
("", vec![], None),
(long.as_str(), vec![], None),
("ok", vec!["Bad Scope"], None),
("ok", vec![""], None),
("ok", many, None),
("ok", vec![], Some(Duration::ZERO)),
] {
let r = k.issue(None, name, &scopes, ttl).await;
assert!(matches!(r, Err(ApiKeyError::Invalid(_))), "{name:?}");
}
let max = k.issue(None, &"é".repeat(100), &["a"; 20], None).await;
assert!(max.is_ok());
}
}