merry_runtime/permission/
channel.rs1use super::{
11 HostFallbackReason, PermissionActor, PermissionAdmissionContext, PermissionAdmissionDecision,
12 PermissionAdmissionError, PermissionAdmissionFuture, PermissionAdmissionSource,
13 PermissionRequest, validate_optional_reason, validate_optional_user_note,
14};
15use merry_core::ApprovalScope;
16use thiserror::Error;
17use tokio::sync::{mpsc, oneshot};
18use tokio_util::sync::CancellationToken;
19
20pub struct PermissionReviewRequest {
22 request: PermissionRequest,
23 host_fallback_reason: Option<HostFallbackReason>,
24 actor: PermissionActor,
25 cancellation_token: CancellationToken,
26 response_sender: Option<oneshot::Sender<PermissionReviewResponse>>,
27}
28
29impl std::fmt::Debug for PermissionReviewRequest {
30 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 formatter
32 .debug_struct("PermissionReviewRequest")
33 .field("approval_id", &self.approval_id())
34 .field("fingerprint", &self.fingerprint())
35 .field("actor", &self.actor)
36 .field("request", &self.request)
37 .finish_non_exhaustive()
38 }
39}
40
41impl PermissionReviewRequest {
42 #[must_use]
44 pub fn request(&self) -> &PermissionRequest {
45 &self.request
46 }
47
48 #[must_use]
50 pub const fn actor(&self) -> &PermissionActor {
51 &self.actor
52 }
53
54 #[must_use]
56 pub fn approval_id(&self) -> String {
57 self.request.approval_id()
58 }
59
60 #[must_use]
62 pub fn fingerprint(&self) -> String {
63 self.request.fingerprint()
64 }
65
66 #[must_use]
68 pub const fn host_fallback_reason(&self) -> Option<&HostFallbackReason> {
69 self.host_fallback_reason.as_ref()
70 }
71
72 #[must_use]
74 pub fn is_cancelled(&self) -> bool {
75 self.cancellation_token.is_cancelled()
76 }
77
78 pub fn approve(
80 self,
81 rationale: impl Into<String>,
82 ) -> Result<(), PermissionReviewResponseError> {
83 self.approve_with_scope(ApprovalScope::Once, rationale)
84 }
85
86 pub fn approve_with_scope(
88 self,
89 scope: ApprovalScope,
90 rationale: impl Into<String>,
91 ) -> Result<(), PermissionReviewResponseError> {
92 self.approve_with_scope_and_note(scope, rationale, None)
93 }
94
95 pub fn approve_with_scope_and_note(
98 self,
99 scope: ApprovalScope,
100 rationale: impl Into<String>,
101 user_note: Option<String>,
102 ) -> Result<(), PermissionReviewResponseError> {
103 let approval_id = self.approval_id();
104 let fingerprint = self.fingerprint();
105 self.respond(
106 PermissionReviewResponse::allow_with_scope(approval_id, fingerprint, scope, rationale)
107 .with_user_note(user_note),
108 )
109 }
110
111 pub fn deny(self, rationale: impl Into<String>) -> Result<(), PermissionReviewResponseError> {
113 self.deny_with_note(rationale, None)
114 }
115
116 pub fn deny_with_note(
119 self,
120 rationale: impl Into<String>,
121 user_note: Option<String>,
122 ) -> Result<(), PermissionReviewResponseError> {
123 let approval_id = self.approval_id();
124 let fingerprint = self.fingerprint();
125 self.respond(
126 PermissionReviewResponse::deny(approval_id, fingerprint, rationale)
127 .with_user_note(user_note),
128 )
129 }
130
131 pub fn respond(
136 mut self,
137 response: PermissionReviewResponse,
138 ) -> Result<(), PermissionReviewResponseError> {
139 let Some(sender) = self.response_sender.take() else {
140 return Err(PermissionReviewResponseError::AlreadyResolved);
141 };
142 sender
143 .send(response)
144 .map_err(|_| PermissionReviewResponseError::Closed)
145 }
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct PermissionReviewResponse {
151 approval_id: String,
152 fingerprint: String,
153 decision: PermissionReviewResponseDecision,
154 scope: ApprovalScope,
155 rationale: String,
156 user_note: Option<String>,
157}
158
159impl PermissionReviewResponse {
160 #[must_use]
162 pub fn allow(
163 approval_id: impl Into<String>,
164 fingerprint: impl Into<String>,
165 rationale: impl Into<String>,
166 ) -> Self {
167 Self::allow_with_scope(approval_id, fingerprint, ApprovalScope::Once, rationale)
168 }
169
170 #[must_use]
172 pub fn allow_with_scope(
173 approval_id: impl Into<String>,
174 fingerprint: impl Into<String>,
175 scope: ApprovalScope,
176 rationale: impl Into<String>,
177 ) -> Self {
178 Self {
179 approval_id: approval_id.into(),
180 fingerprint: fingerprint.into(),
181 decision: PermissionReviewResponseDecision::Allow,
182 scope,
183 rationale: rationale.into(),
184 user_note: None,
185 }
186 }
187
188 #[must_use]
190 pub fn deny(
191 approval_id: impl Into<String>,
192 fingerprint: impl Into<String>,
193 rationale: impl Into<String>,
194 ) -> Self {
195 Self {
196 approval_id: approval_id.into(),
197 fingerprint: fingerprint.into(),
198 decision: PermissionReviewResponseDecision::Deny,
199 scope: ApprovalScope::Once,
200 rationale: rationale.into(),
201 user_note: None,
202 }
203 }
204
205 #[must_use]
209 pub fn with_user_note(mut self, user_note: Option<String>) -> Self {
210 self.user_note = user_note
211 .map(|note| note.trim().to_owned())
212 .filter(|note| !note.is_empty());
213 self
214 }
215
216 #[must_use]
218 pub fn user_note(&self) -> Option<&str> {
219 self.user_note.as_deref()
220 }
221}
222
223#[derive(Debug, Clone, Copy, PartialEq, Eq)]
224enum PermissionReviewResponseDecision {
225 Allow,
226 Deny,
227}
228
229#[derive(Debug, Clone)]
231pub struct ChannelPermissionAdmissionSource {
232 sender: mpsc::Sender<PermissionReviewRequest>,
233}
234
235impl ChannelPermissionAdmissionSource {
236 pub fn channel(capacity: usize) -> (Self, mpsc::Receiver<PermissionReviewRequest>) {
238 let (sender, receiver) = mpsc::channel(capacity.max(1));
239 (Self { sender }, receiver)
240 }
241}
242
243impl PermissionAdmissionSource for ChannelPermissionAdmissionSource {
244 fn review<'a>(
245 &'a self,
246 request: PermissionRequest,
247 context: PermissionAdmissionContext,
248 ) -> PermissionAdmissionFuture<'a> {
249 Box::pin(async move {
250 let approval_id = request.approval_id();
251 let fingerprint = request.fingerprint();
252 let (response_sender, response_receiver) = oneshot::channel();
253 let pending = PermissionReviewRequest {
254 request: request.clone(),
255 host_fallback_reason: context.host_fallback_reason().cloned(),
256 actor: context.actor().clone(),
257 cancellation_token: context.cancellation_token().clone(),
258 response_sender: Some(response_sender),
259 };
260 tokio::select! {
261 biased;
262 () = context.cancellation_token().cancelled() => {
263 Err(PermissionAdmissionError::Cancelled)
264 }
265 result = self.sender.send(pending) => {
266 result.map_err(|_| PermissionAdmissionError::HumanReviewUnavailable {
267 message: "human permission review channel is closed".to_owned(),
268 })?;
269 let response = tokio::select! {
270 biased;
271 () = context.cancellation_token().cancelled() => {
272 return Err(PermissionAdmissionError::Cancelled);
273 }
274 response = response_receiver => response.map_err(|_| {
275 PermissionAdmissionError::HumanReviewUnavailable {
276 message: "human permission review response was closed".to_owned(),
277 }
278 })?,
279 };
280 if response.approval_id != approval_id {
281 return Err(PermissionAdmissionError::StaleReviewResponse {
282 expected: approval_id,
283 actual: response.approval_id,
284 });
285 }
286 if response.fingerprint != fingerprint {
287 return Err(PermissionAdmissionError::StaleReviewResponse {
288 expected: fingerprint,
289 actual: response.fingerprint,
290 });
291 }
292 validate_optional_reason(&response.rationale)?;
293 let user_note = response
294 .user_note
295 .map(|note| note.trim().to_owned())
296 .filter(|note| !note.is_empty());
297 if let Some(note) = user_note.as_deref() {
298 validate_optional_user_note(note)?;
299 }
300 let decision = match response.decision {
301 PermissionReviewResponseDecision::Allow => {
302 PermissionAdmissionDecision::approved_with_scope_and_note(
303 response.scope,
304 response.rationale,
305 user_note,
306 )
307 }
308 PermissionReviewResponseDecision::Deny => {
309 PermissionAdmissionDecision::denied_with_note(
310 response.rationale,
311 user_note,
312 )
313 }
314 };
315 Ok(decision)
316 }
317 }
318 })
319 }
320}
321
322#[derive(Debug, Error, Clone, PartialEq, Eq)]
324pub enum PermissionReviewResponseError {
325 #[error("permission review request is already resolved")]
327 AlreadyResolved,
328 #[error("permission review response channel is closed")]
330 Closed,
331}