use std::time::Duration;
use alloy_primitives::Address;
use chrono::{DateTime, Utc};
use super::Credentials;
use crate::{
Error, Result,
model::{
CredentialCreated, CredentialInput, CredentialRotated, CredentialScope, RotationBody,
expires_at,
},
protocol::checks::maker::check_created_credential,
transport::{Call, ops},
types::QuoteIdentityId,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CredentialRequest {
name: String,
quote_signer: Address,
scopes: Vec<CredentialScope>,
expires_in: Duration,
}
impl CredentialRequest {
pub fn new(name: impl Into<String>, quote_signer: Address, expires_in: Duration) -> Self {
Self {
name: name.into(),
quote_signer,
scopes: vec![CredentialScope::Read, CredentialScope::Quote, CredentialScope::Cancel],
expires_in,
}
}
#[must_use]
pub fn scopes(mut self, scopes: impl IntoIterator<Item = CredentialScope>) -> Self {
self.scopes.clear();
for scope in scopes {
if !self.scopes.contains(&scope) {
self.scopes.push(scope);
}
}
self
}
fn body(&self, now: DateTime<Utc>) -> Result<CredentialInput> {
let chars = self.name.chars().count();
if self.name.trim().is_empty() || chars > 80 {
return Err(Error::InvalidRequest("name must be 1 to 80 characters, not blank".into()));
}
if self.quote_signer.is_zero() {
return Err(Error::InvalidRequest("quote_signer must be nonzero".into()));
}
if self.scopes.is_empty() || self.scopes.iter().any(CredentialScope::is_unknown) {
return Err(Error::InvalidRequest("scopes must be some of read, quote, cancel".into()));
}
Ok(CredentialInput {
name: self.name.clone(),
quote_signer: self.quote_signer,
scopes: self.scopes.clone(),
expires_at: expires_at(now, self.expires_in)?,
})
}
}
impl Credentials<'_> {
pub async fn create(&self, request: &CredentialRequest) -> Result<CredentialCreated> {
let body = request.body(self.inner.now())?;
let created: CredentialCreated =
self.inner.send(Call::new(&ops::CREATE_CREDENTIAL).json(&body)?, self.auth).await?;
check_created_credential(&created, body.quote_signer, &body.scopes)?;
Ok(created)
}
pub async fn rotate(
&self,
id: QuoteIdentityId,
expires_in: Duration,
) -> Result<CredentialRotated> {
let body = RotationBody { expires_at: expires_at(self.inner.now(), expires_in)? };
let call = Call::new(&ops::ROTATE_CREDENTIAL).segment(id).json(&body)?;
self.inner.send(call, self.auth).await
}
pub async fn delete(&self, id: QuoteIdentityId) -> Result<()> {
self.inner.send(Call::new(&ops::DELETE_CREDENTIAL).segment(id), self.auth).await
}
}
#[cfg(test)]
mod tests;