mod endpoints;
mod error;
mod model;
mod verify;
use fastauth_core::plugin_prelude::*;
use http::HeaderName;
pub use endpoints::{
ApiKeyList, ApiKeyView, CreateApiKey, CreateApiKeyInput, CreatedApiKey,
DeleteAllExpiredApiKeys, DeleteApiKey, DeleteApiKeyInput, DeleteExpiredOutput, GetApiKey,
GetApiKeyInput, ListApiKeys, ListApiKeysInput, SortDirection, Success, UpdateApiKey,
UpdateApiKeyInput, VerifyApiKey, VerifyApiKeyInput, VerifyError, VerifyOutput,
};
pub use error::ApiKeyError;
pub use model::{ApiKey, Permissions};
type KeyGetter = Arc<dyn Fn(&HeaderMap) -> Option<String> + Send + Sync>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct RateLimitDefaults {
enabled: bool,
window: Duration,
max: i64,
}
#[derive(Clone)]
pub struct ApiKeys {
key_length: usize,
default_prefix: Option<String>,
start_length: usize,
default_expires_in: Option<Duration>,
min_expires_in: Duration,
max_expires_in: Duration,
enable_metadata: bool,
require_name: bool,
default_permissions: Option<Permissions>,
rate_limit: RateLimitDefaults,
header: HeaderName,
getter: Option<KeyGetter>,
sessions: bool,
}
impl std::fmt::Debug for ApiKeys {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ApiKeys")
.field("key_length", &self.key_length)
.field("default_prefix", &self.default_prefix)
.field("header", &self.header)
.field("sessions", &self.sessions)
.finish_non_exhaustive()
}
}
impl Default for ApiKeys {
fn default() -> Self {
Self {
key_length: 64,
default_prefix: None,
start_length: 6,
default_expires_in: None,
min_expires_in: Duration::days(1),
max_expires_in: Duration::days(365),
enable_metadata: false,
require_name: false,
default_permissions: None,
rate_limit: RateLimitDefaults {
enabled: true,
window: Duration::days(1),
max: 10,
},
header: HeaderName::from_static("x-api-key"),
getter: None,
sessions: false,
}
}
}
impl ApiKeys {
pub fn new() -> Self {
Self::default()
}
pub fn key_length(mut self, length: usize) -> Self {
assert!(length >= 16, "API keys need at least 16 random characters");
self.key_length = length;
self
}
pub fn default_prefix(mut self, prefix: impl Into<String>) -> Self {
self.default_prefix = Some(prefix.into());
self
}
pub fn start_length(mut self, length: usize) -> Self {
self.start_length = length;
self
}
pub fn default_expires_in(mut self, ttl: Duration) -> Self {
self.default_expires_in = Some(ttl);
self
}
pub fn min_expires_in(mut self, min: Duration) -> Self {
self.min_expires_in = min;
self
}
pub fn max_expires_in(mut self, max: Duration) -> Self {
self.max_expires_in = max;
self
}
pub fn enable_metadata(mut self, enabled: bool) -> Self {
self.enable_metadata = enabled;
self
}
pub fn require_name(mut self, required: bool) -> Self {
self.require_name = required;
self
}
pub fn default_permissions(mut self, permissions: Permissions) -> Self {
self.default_permissions = Some(permissions);
self
}
pub fn rate_limit(mut self, window: Duration, max: i64) -> Self {
self.rate_limit.window = window;
self.rate_limit.max = max;
self
}
pub fn disable_rate_limit(mut self) -> Self {
self.rate_limit.enabled = false;
self
}
pub fn header(mut self, name: HeaderName) -> Self {
self.header = name;
self
}
pub fn key_getter(
mut self,
getter: impl Fn(&HeaderMap) -> Option<String> + Send + Sync + 'static,
) -> Self {
self.getter = Some(Arc::new(getter));
self
}
pub fn sessions(mut self, enabled: bool) -> Self {
self.sessions = enabled;
self
}
fn key_from(&self, headers: &HeaderMap) -> Option<String> {
match &self.getter {
Some(getter) => getter(headers),
None => headers
.get(&self.header)
.and_then(|v| v.to_str().ok())
.map(str::to_owned),
}
.filter(|key| !key.is_empty())
}
}
impl Plugin for ApiKeys {
const ID: &'static str = "api-key";
type Requires = ();
type UserFields = ();
type SessionFields = ();
fn schema(&self, schema: &mut SchemaBuilder) {
schema.model::<ApiKey>();
}
fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
app.endpoint(CreateApiKey::client(self.clone()))
.endpoint(GetApiKey::client())
.endpoint(UpdateApiKey::client(self.clone()))
.endpoint(DeleteApiKey::client())
.endpoint(ListApiKeys::client())
.server_endpoint::<VerifyApiKey>()
.server_endpoint::<DeleteAllExpiredApiKeys>()
.errors::<ApiKeyError>();
if self.sessions {
app.session_resolver(verify::KeyResolver(self.clone()));
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ApiKeyCreated {
pub id: Id,
pub user_id: Id,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ApiKeyDeleted {
pub id: Id,
pub user_id: Id,
}
impl Event for ApiKeyCreated {}
impl Event for ApiKeyDeleted {}
pub trait ApiKeysExt: AuthInstance + Sized {
fn api_keys<I>(&self) -> ApiKeysApi<'_, Self>
where
Self: HasPlugin<ApiKeys, I>,
{
ApiKeysApi {
auth: self,
plugin: self.plugin_arc().clone(),
headers: HeaderMap::new(),
}
}
}
impl<A: AuthInstance> ApiKeysExt for A {}
pub struct ApiKeysApi<'a, A> {
auth: &'a A,
plugin: Arc<ApiKeys>,
headers: HeaderMap,
}
impl<A> std::fmt::Debug for ApiKeysApi<'_, A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("ApiKeysApi")
}
}
impl<A: AuthInstance> ApiKeysApi<'_, A> {
pub fn headers(mut self, headers: &HeaderMap) -> Self {
self.headers = headers.clone();
self
}
async fn call<E: Endpoint<A::Db>>(
&self,
endpoint: &E,
input: E::Input,
) -> Result<E::Output, AuthError> {
Ok(self
.auth
.api()
.headers(&self.headers)
.call(endpoint, input)
.await?
.data)
}
pub async fn create(&self, input: CreateApiKeyInput) -> Result<CreatedApiKey, AuthError> {
self.call(&CreateApiKey::server(self.plugin.clone()), input)
.await
}
pub async fn verify(
&self,
key: &str,
permissions: Option<Permissions>,
) -> Result<VerifyOutput, AuthError> {
let input = VerifyApiKeyInput {
key: key.to_owned(),
permissions,
};
self.call(&VerifyApiKey(self.plugin.clone()), input).await
}
pub async fn get(&self, input: GetApiKeyInput) -> Result<ApiKeyView, AuthError> {
self.call(&GetApiKey::server(), input).await
}
pub async fn update(&self, input: UpdateApiKeyInput) -> Result<ApiKeyView, AuthError> {
self.call(&UpdateApiKey::server(self.plugin.clone()), input)
.await
}
pub async fn delete(&self, input: DeleteApiKeyInput) -> Result<Success, AuthError> {
self.call(&DeleteApiKey::server(), input).await
}
pub async fn list(&self, input: ListApiKeysInput) -> Result<ApiKeyList, AuthError> {
self.call(&ListApiKeys::server(), input).await
}
pub async fn delete_all_expired(&self) -> Result<DeleteExpiredOutput, AuthError> {
self.call(&DeleteAllExpiredApiKeys, Empty {}).await
}
}