90 lines
3.3 KiB
Rust
90 lines
3.3 KiB
Rust
use axum::http::StatusCode;
|
|
use chrono::{DateTime, Utc};
|
|
use serde::{Deserialize, Serialize};
|
|
use uuid::Uuid;
|
|
#[derive(Default, Clone, Deserialize, schemars::JsonSchema)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct PageQuery {
|
|
pub cursor: Option<String>,
|
|
pub limit: Option<u16>,
|
|
}
|
|
#[derive(Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Cursor {
|
|
domain: String,
|
|
tenant: Uuid,
|
|
principal: String,
|
|
scope: String,
|
|
pub as_of: DateTime<Utc>,
|
|
pub last: Uuid,
|
|
pub limit: u16,
|
|
}
|
|
impl Cursor {
|
|
pub fn parse(
|
|
state: &crate::State,
|
|
p: &crate::auth::Principal,
|
|
scope: &str,
|
|
q: PageQuery,
|
|
) -> Result<Self, StatusCode> {
|
|
if q.limit.is_some_and(|n| n == 0 || n > 500) {
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
if let Some(raw) = q.cursor {
|
|
if raw.len() > 4096 {
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
let (bytes, signature) = raw.split_once('.').ok_or(StatusCode::BAD_REQUEST)?;
|
|
let bytes = hex::decode(bytes).map_err(|_| StatusCode::BAD_REQUEST)?;
|
|
let signature = hex::decode(signature).map_err(|_| StatusCode::BAD_REQUEST)?;
|
|
let public = openssl::pkey::PKey::public_key_from_raw_bytes(
|
|
&state
|
|
.job_signer
|
|
.public_key()
|
|
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?,
|
|
openssl::pkey::Id::ED25519,
|
|
)
|
|
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
|
let verified = openssl::sign::Verifier::new_without_digest(&public)
|
|
.and_then(|mut v| v.verify_oneshot(&signature, &bytes))
|
|
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
|
if !verified {
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
let cursor: Self =
|
|
serde_json::from_slice(&bytes).map_err(|_| StatusCode::BAD_REQUEST)?;
|
|
if cursor.domain != "rmm.page-cursor.v1"
|
|
|| cursor.tenant != p.tenant
|
|
|| cursor.principal != p.name
|
|
|| cursor.scope != scope
|
|
|| (Utc::now() - cursor.as_of).num_seconds() > 600
|
|
|| cursor.as_of > Utc::now()
|
|
|| q.limit.is_some_and(|n| n != cursor.limit)
|
|
{
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
Ok(cursor)
|
|
} else {
|
|
Ok(Self {
|
|
domain: "rmm.page-cursor.v1".into(),
|
|
tenant: p.tenant,
|
|
principal: p.name.clone(),
|
|
scope: scope.into(),
|
|
as_of: Utc::now(),
|
|
last: Uuid::nil(),
|
|
limit: q.limit.unwrap_or(100),
|
|
})
|
|
}
|
|
}
|
|
pub fn next(&mut self, state: &crate::State, last: Uuid) -> Result<String, StatusCode> {
|
|
self.last = last;
|
|
// Distinct domain, despite sharing the administrative signing primitive:
|
|
// the signer cannot interpret these bytes as an execution permit.
|
|
let bytes = serde_json::to_vec(self).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
let signature = state
|
|
.job_signer
|
|
.sign(&bytes)
|
|
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
|
Ok(format!("{}.{}", hex::encode(bytes), hex::encode(signature)))
|
|
}
|
|
}
|