use super::{
HostFallbackReason, PermissionActor, PermissionAdmissionContext, PermissionAdmissionDecision,
PermissionAdmissionError, PermissionAdmissionFuture, PermissionAdmissionSource,
PermissionRequest, validate_optional_reason, validate_optional_user_note,
};
use merry_core::ApprovalScope;
use thiserror::Error;
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;
pub struct PermissionReviewRequest {
request: PermissionRequest,
host_fallback_reason: Option<HostFallbackReason>,
actor: PermissionActor,
cancellation_token: CancellationToken,
response_sender: Option<oneshot::Sender<PermissionReviewResponse>>,
}
impl std::fmt::Debug for PermissionReviewRequest {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("PermissionReviewRequest")
.field("approval_id", &self.approval_id())
.field("fingerprint", &self.fingerprint())
.field("actor", &self.actor)
.field("request", &self.request)
.finish_non_exhaustive()
}
}
impl PermissionReviewRequest {
#[must_use]
pub fn request(&self) -> &PermissionRequest {
&self.request
}
#[must_use]
pub const fn actor(&self) -> &PermissionActor {
&self.actor
}
#[must_use]
pub fn approval_id(&self) -> String {
self.request.approval_id()
}
#[must_use]
pub fn fingerprint(&self) -> String {
self.request.fingerprint()
}
#[must_use]
pub const fn host_fallback_reason(&self) -> Option<&HostFallbackReason> {
self.host_fallback_reason.as_ref()
}
#[must_use]
pub fn is_cancelled(&self) -> bool {
self.cancellation_token.is_cancelled()
}
pub fn approve(
self,
rationale: impl Into<String>,
) -> Result<(), PermissionReviewResponseError> {
self.approve_with_scope(ApprovalScope::Once, rationale)
}
pub fn approve_with_scope(
self,
scope: ApprovalScope,
rationale: impl Into<String>,
) -> Result<(), PermissionReviewResponseError> {
self.approve_with_scope_and_note(scope, rationale, None)
}
pub fn approve_with_scope_and_note(
self,
scope: ApprovalScope,
rationale: impl Into<String>,
user_note: Option<String>,
) -> Result<(), PermissionReviewResponseError> {
let approval_id = self.approval_id();
let fingerprint = self.fingerprint();
self.respond(
PermissionReviewResponse::allow_with_scope(approval_id, fingerprint, scope, rationale)
.with_user_note(user_note),
)
}
pub fn deny(self, rationale: impl Into<String>) -> Result<(), PermissionReviewResponseError> {
self.deny_with_note(rationale, None)
}
pub fn deny_with_note(
self,
rationale: impl Into<String>,
user_note: Option<String>,
) -> Result<(), PermissionReviewResponseError> {
let approval_id = self.approval_id();
let fingerprint = self.fingerprint();
self.respond(
PermissionReviewResponse::deny(approval_id, fingerprint, rationale)
.with_user_note(user_note),
)
}
pub fn respond(
mut self,
response: PermissionReviewResponse,
) -> Result<(), PermissionReviewResponseError> {
let Some(sender) = self.response_sender.take() else {
return Err(PermissionReviewResponseError::AlreadyResolved);
};
sender
.send(response)
.map_err(|_| PermissionReviewResponseError::Closed)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PermissionReviewResponse {
approval_id: String,
fingerprint: String,
decision: PermissionReviewResponseDecision,
scope: ApprovalScope,
rationale: String,
user_note: Option<String>,
}
impl PermissionReviewResponse {
#[must_use]
pub fn allow(
approval_id: impl Into<String>,
fingerprint: impl Into<String>,
rationale: impl Into<String>,
) -> Self {
Self::allow_with_scope(approval_id, fingerprint, ApprovalScope::Once, rationale)
}
#[must_use]
pub fn allow_with_scope(
approval_id: impl Into<String>,
fingerprint: impl Into<String>,
scope: ApprovalScope,
rationale: impl Into<String>,
) -> Self {
Self {
approval_id: approval_id.into(),
fingerprint: fingerprint.into(),
decision: PermissionReviewResponseDecision::Allow,
scope,
rationale: rationale.into(),
user_note: None,
}
}
#[must_use]
pub fn deny(
approval_id: impl Into<String>,
fingerprint: impl Into<String>,
rationale: impl Into<String>,
) -> Self {
Self {
approval_id: approval_id.into(),
fingerprint: fingerprint.into(),
decision: PermissionReviewResponseDecision::Deny,
scope: ApprovalScope::Once,
rationale: rationale.into(),
user_note: None,
}
}
#[must_use]
pub fn with_user_note(mut self, user_note: Option<String>) -> Self {
self.user_note = user_note
.map(|note| note.trim().to_owned())
.filter(|note| !note.is_empty());
self
}
#[must_use]
pub fn user_note(&self) -> Option<&str> {
self.user_note.as_deref()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PermissionReviewResponseDecision {
Allow,
Deny,
}
#[derive(Debug, Clone)]
pub struct ChannelPermissionAdmissionSource {
sender: mpsc::Sender<PermissionReviewRequest>,
}
impl ChannelPermissionAdmissionSource {
pub fn channel(capacity: usize) -> (Self, mpsc::Receiver<PermissionReviewRequest>) {
let (sender, receiver) = mpsc::channel(capacity.max(1));
(Self { sender }, receiver)
}
}
impl PermissionAdmissionSource for ChannelPermissionAdmissionSource {
fn review<'a>(
&'a self,
request: PermissionRequest,
context: PermissionAdmissionContext,
) -> PermissionAdmissionFuture<'a> {
Box::pin(async move {
let approval_id = request.approval_id();
let fingerprint = request.fingerprint();
let (response_sender, response_receiver) = oneshot::channel();
let pending = PermissionReviewRequest {
request: request.clone(),
host_fallback_reason: context.host_fallback_reason().cloned(),
actor: context.actor().clone(),
cancellation_token: context.cancellation_token().clone(),
response_sender: Some(response_sender),
};
tokio::select! {
biased;
() = context.cancellation_token().cancelled() => {
Err(PermissionAdmissionError::Cancelled)
}
result = self.sender.send(pending) => {
result.map_err(|_| PermissionAdmissionError::HumanReviewUnavailable {
message: "human permission review channel is closed".to_owned(),
})?;
let response = tokio::select! {
biased;
() = context.cancellation_token().cancelled() => {
return Err(PermissionAdmissionError::Cancelled);
}
response = response_receiver => response.map_err(|_| {
PermissionAdmissionError::HumanReviewUnavailable {
message: "human permission review response was closed".to_owned(),
}
})?,
};
if response.approval_id != approval_id {
return Err(PermissionAdmissionError::StaleReviewResponse {
expected: approval_id,
actual: response.approval_id,
});
}
if response.fingerprint != fingerprint {
return Err(PermissionAdmissionError::StaleReviewResponse {
expected: fingerprint,
actual: response.fingerprint,
});
}
validate_optional_reason(&response.rationale)?;
let user_note = response
.user_note
.map(|note| note.trim().to_owned())
.filter(|note| !note.is_empty());
if let Some(note) = user_note.as_deref() {
validate_optional_user_note(note)?;
}
let decision = match response.decision {
PermissionReviewResponseDecision::Allow => {
PermissionAdmissionDecision::approved_with_scope_and_note(
response.scope,
response.rationale,
user_note,
)
}
PermissionReviewResponseDecision::Deny => {
PermissionAdmissionDecision::denied_with_note(
response.rationale,
user_note,
)
}
};
Ok(decision)
}
}
})
}
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum PermissionReviewResponseError {
#[error("permission review request is already resolved")]
AlreadyResolved,
#[error("permission review response channel is closed")]
Closed,
}