Skip to main content

adk_server/
approvals.rs

1//! Approval inbox endpoints, a background ticker, and a signed webhook notifier for an
2//! [`ApprovalService`].
3//!
4//! Mount the endpoints with [`ServerBuilder::with_approval_service`](crate::ServerBuilder::with_approval_service),
5//! which places them behind the server's auth middleware. Every route needs an
6//! authenticated caller: without a `RequestContextExtractor`, or without a request
7//! context, they answer `401`. The caller is the approver: by default the person named
8//! by `RequestContext::user_id`, a member of the groups in `RequestContext::scopes`
9//! ([`ApprovalEndpoints::with_identity`] changes the mapping).
10//!
11//! | Route | Effect |
12//! |-------|--------|
13//! | `GET /api/approvals` | The caller's inbox. Query: `state` (repeatable via comma list), `group`, `app`, `user`, `session` (with `app`; one session of `user`, the caller by default), `cursor`, `limit` |
14//! | `GET /api/approvals/{id}` | One request the caller may decide, cancel, or asked for |
15//! | `POST /api/approvals/{id}/decide` | Body `{"expectedVersion": 3, "action": "approve" \| "edit" \| "reject" \| "respond", "editedArgs": {...}, "reason": "...", "via": {"kind": "human", "id": "ana"}}` |
16//! | `POST /api/approvals/{id}/cancel` | Body `{"reason": "..."}`; the requester or an approver |
17//! | `POST /api/approvals/delegations` | Body `{"to": {"kind": "human", "id": "bo"}, "notBefore": "...", "notAfter": "...", "scope": {...}}`; delegates the caller's authority |
18//! | `DELETE /api/approvals/delegations/{id}?toKind=human&toId=bo` | Revokes a delegation the caller granted or holds |
19//!
20//! Errors are problem documents with the service's error code: `409` for
21//! `approval.version_conflict` (re-read and decide again), `403` for self-approval or a
22//! caller who is not an approver, `404` for an unknown request. Request bodies omit the
23//! call's fingerprint, which carries the unredacted arguments, and add `showsCallArgs`:
24//! whether `argsRedacted` are the call's own arguments, which an edit starting from them
25//! needs. A resolution authorizes only
26//! the call the request describes: the fingerprint names its acting agent and its tool's
27//! [`ToolOrigin`](adk_core::ToolOrigin), shown on the request.
28//!
29//! A host that knows more about a decision than its approval policy — which surface may give
30//! which answer (spec 3.3 §7.2) — installs a [`DecideGuard`] with
31//! [`ApprovalEndpoints::with_decide_guard`]: it checks every decision on
32//! `POST /api/approvals/{id}/decide` before the service records it, refusing with its own
33//! problem document, and hears of each one the service recorded.
34
35use std::sync::Arc;
36use std::time::Duration;
37
38use adk_core::principal::{SubjectKind, SubjectRef};
39use adk_core::{
40    AdkError, ApprovalAction, ApprovalDecision, ApprovalDelegation, ApprovalNotification,
41    ApprovalNotifier, ApprovalRequest, ApprovalService, ApprovalState, DelegationScope,
42    DelegationWindow, ErrorCategory, ErrorComponent, InboxQuery, RequestContext,
43};
44use async_trait::async_trait;
45use axum::extract::{Path, Query, State};
46use axum::http::{Extensions, StatusCode};
47use axum::response::{IntoResponse, Response};
48use axum::routing::{delete, get, post};
49use axum::{Extension, Json, Router};
50use chrono::{DateTime, Utc};
51use serde::Deserialize;
52use serde_json::Value;
53
54/// Maps an authenticated request to the approver it acts as: a subject and its groups.
55pub type ApproverIdentity = Arc<dyn Fn(&RequestContext) -> (SubjectRef, Vec<String>) + Send + Sync>;
56
57/// One decision on `POST /api/approvals/{id}/decide`, as a [`DecideGuard`] sees it: who
58/// sends it, how the request reached the server, the request it answers and the answer.
59#[derive(Debug)]
60#[non_exhaustive]
61pub struct DecideCall<'a> {
62    /// The authenticated caller.
63    pub caller: &'a RequestContext,
64    /// The HTTP request's extensions, where a host's own middleware leaves what it
65    /// established about the request, such as the transport it came on.
66    pub extensions: &'a Extensions,
67    /// The request being answered, as it is before the answer.
68    pub request: &'a ApprovalRequest,
69    /// The answer.
70    pub action: ApprovalAction,
71}
72
73/// A host's check of every decision the approval endpoints receive (spec 3.3 §7.2, §11): it
74/// runs after the caller is authenticated and before the service records the decision, and
75/// hears of each decision the service recorded.
76///
77/// # Example
78///
79/// ```rust
80/// use std::sync::Arc;
81/// use adk_core::{
82///     AdkError, ApprovalAction, ErrorCategory, ErrorComponent, InMemoryApprovalStore,
83///     StoreApprovalService,
84/// };
85/// use adk_server::approvals::{ApprovalEndpoints, DecideCall, DecideGuard, approvals_router};
86///
87/// struct NoEdits;
88///
89/// #[async_trait::async_trait]
90/// impl DecideGuard for NoEdits {
91///     async fn check(&self, call: &DecideCall<'_>) -> Result<(), AdkError> {
92///         match call.action {
93///             ApprovalAction::Edit => Err(AdkError::new(
94///                 ErrorComponent::Server,
95///                 ErrorCategory::Forbidden,
96///                 "example.no_edits",
97///                 "edit it in the home",
98///             )),
99///             _ => Ok(()),
100///         }
101///     }
102/// }
103///
104/// let service = Arc::new(StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new())));
105/// let router = approvals_router(ApprovalEndpoints::new(service).with_decide_guard(Arc::new(NoEdits)));
106/// # let _ = router;
107/// ```
108#[async_trait]
109pub trait DecideGuard: Send + Sync {
110    /// Refuses `call` with the error the caller gets, or admits it.
111    ///
112    /// # Errors
113    ///
114    /// The refusal, answered as a problem document with its status.
115    async fn check(&self, call: &DecideCall<'_>) -> Result<(), AdkError>;
116
117    /// Hears that the service recorded `call` and answered `decided`. Nothing it does
118    /// changes the response.
119    async fn decided(&self, call: &DecideCall<'_>, decided: &ApprovalRequest) {
120        let _ = (call, decided);
121    }
122}
123
124/// State for the approval endpoints.
125///
126/// # Example
127///
128/// ```rust
129/// use std::sync::Arc;
130/// use adk_core::{InMemoryApprovalStore, StoreApprovalService};
131/// use adk_server::approvals::{ApprovalEndpoints, approvals_router};
132///
133/// let service = Arc::new(StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new())));
134/// let router = approvals_router(ApprovalEndpoints::new(service));
135/// # let _ = router;
136/// ```
137#[derive(Clone)]
138pub struct ApprovalEndpoints {
139    service: Arc<dyn ApprovalService>,
140    identity: ApproverIdentity,
141    guard: Option<Arc<dyn DecideGuard>>,
142}
143
144impl ApprovalEndpoints {
145    /// Endpoints over `service`, with callers mapped to `human(user_id)` in the groups
146    /// named by their scopes.
147    pub fn new(service: Arc<dyn ApprovalService>) -> Self {
148        Self {
149            service,
150            identity: Arc::new(|caller: &RequestContext| {
151                (SubjectRef::human(caller.user_id.clone()), caller.scopes.clone())
152            }),
153            guard: None,
154        }
155    }
156
157    /// Checks every decision with `guard` before the service records it (spec 3.3 §7.2).
158    #[must_use]
159    pub fn with_decide_guard(mut self, guard: Arc<dyn DecideGuard>) -> Self {
160        self.guard = Some(guard);
161        self
162    }
163
164    /// The approval service the endpoints serve, which
165    /// [`ServerBuilder::with_approval_endpoints`](crate::ServerBuilder::with_approval_endpoints)
166    /// also hands its runtime routes (spec 3.3 §7.2).
167    pub fn service(&self) -> &Arc<dyn ApprovalService> {
168        &self.service
169    }
170
171    /// Maps callers to approvers with `identity`.
172    #[must_use]
173    pub fn with_identity(
174        mut self,
175        identity: impl Fn(&RequestContext) -> (SubjectRef, Vec<String>) + Send + Sync + 'static,
176    ) -> Self {
177        self.identity = Arc::new(identity);
178        self
179    }
180
181    fn caller(
182        &self,
183        context: Option<RequestContext>,
184    ) -> Result<(SubjectRef, Vec<String>), Response> {
185        match context {
186            Some(context) => Ok((self.identity)(&context)),
187            None => Err((
188                StatusCode::UNAUTHORIZED,
189                Json(serde_json::json!({
190                    "error": "approval endpoints need an authenticated caller; configure a \
191                              RequestContextExtractor"
192                })),
193            )
194                .into_response()),
195        }
196    }
197
198    /// Whether `subject` in `groups` may see `request`: an approver now, directly or by
199    /// a live delegation, or the requester.
200    async fn may_see(
201        &self,
202        request: &ApprovalRequest,
203        subject: &SubjectRef,
204        groups: &[String],
205    ) -> Result<bool, AdkError> {
206        if request.is_eligible(subject, groups) || request.is_self(subject) {
207            return Ok(true);
208        }
209        let now = Utc::now();
210        Ok(self
211            .service
212            .delegations_to(subject)
213            .await?
214            .iter()
215            .any(|delegation| delegation.applies_to(request, now)))
216    }
217}
218
219impl std::fmt::Debug for ApprovalEndpoints {
220    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221        f.debug_struct("ApprovalEndpoints").field("service", &self.service).finish_non_exhaustive()
222    }
223}
224
225/// The approval routes, relative to `/api`. Mount them behind the auth middleware, as
226/// [`ServerBuilder::with_approval_service`](crate::ServerBuilder::with_approval_service)
227/// does.
228pub fn approvals_router(endpoints: ApprovalEndpoints) -> Router {
229    Router::new()
230        .route("/approvals", get(inbox))
231        .route("/approvals/delegations", post(create_delegation))
232        .route("/approvals/delegations/{id}", delete(revoke_delegation))
233        .route("/approvals/{id}", get(get_request))
234        .route("/approvals/{id}/decide", post(decide))
235        .route("/approvals/{id}/cancel", post(cancel))
236        .with_state(endpoints)
237}
238
239/// Runs [`ApprovalService::tick`] every `interval` until the task is aborted, so
240/// requests expire and escalate on time. Safe to run on every replica.
241///
242/// # Example
243///
244/// ```rust,no_run
245/// use std::sync::Arc;
246/// use std::time::Duration;
247/// use adk_core::{InMemoryApprovalStore, StoreApprovalService};
248///
249/// # async fn demo() {
250/// let service = Arc::new(StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new())));
251/// let ticker = adk_server::approvals::spawn_approval_ticker(service, Duration::from_secs(30));
252/// # ticker.abort();
253/// # }
254/// ```
255pub fn spawn_approval_ticker(
256    service: Arc<dyn ApprovalService>,
257    interval: Duration,
258) -> tokio::task::JoinHandle<()> {
259    tokio::spawn(async move {
260        let mut timer = tokio::time::interval(interval);
261        timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
262        loop {
263            timer.tick().await;
264            match service.tick(Utc::now()).await {
265                Ok(report) if report.expired.is_empty() && report.escalated.is_empty() => {}
266                Ok(report) => tracing::info!(
267                    approvals.expired = report.expired.len(),
268                    approvals.escalated = report.escalated.len(),
269                    "approval tick"
270                ),
271                Err(error) => tracing::warn!(error = %error, "approval tick failed"),
272            }
273        }
274    })
275}
276
277fn problem(error: &AdkError) -> Response {
278    let status =
279        StatusCode::from_u16(error.http_status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
280    (status, Json(error.to_problem_json())).into_response()
281}
282
283fn not_found(id: &str) -> Response {
284    problem(&AdkError::new(
285        ErrorComponent::Server,
286        ErrorCategory::NotFound,
287        "approval.not_found",
288        format!("no approval request '{id}'"),
289    ))
290}
291
292/// A request as shown to callers: without its fingerprint, which holds the raw
293/// arguments, and with `showsCallArgs`, whether `argsRedacted` are the call's own, so a
294/// client knows an edit that starts from them changes nothing else (spec 3.3 §7.2).
295fn view(request: &ApprovalRequest) -> Value {
296    let mut value = serde_json::to_value(request).unwrap_or(Value::Null);
297    if let Some(object) = value.as_object_mut() {
298        object.remove("fingerprint");
299        object.insert("showsCallArgs".into(), Value::Bool(request.shows_call_args()));
300    }
301    value
302}
303
304/// `GET /api/approvals` query.
305#[derive(Debug, Default, Deserialize)]
306#[serde(rename_all = "camelCase")]
307pub struct InboxParams {
308    /// Comma-separated states; defaults to pending.
309    #[serde(default)]
310    pub state: Option<String>,
311    /// List one of the caller's groups' queue instead of the caller's inbox.
312    #[serde(default)]
313    pub group: Option<String>,
314    /// Only one application.
315    #[serde(default)]
316    pub app: Option<String>,
317    /// Only requests of this user.
318    #[serde(default)]
319    pub user: Option<String>,
320    /// Only one session: the session with this ID of `user` (the caller when `user` is
321    /// unset) in `app`, which it needs (spec 3.3 §10 C1). It narrows the caller's inbox and
322    /// never widens it.
323    #[serde(default)]
324    pub session: Option<String>,
325    /// Page token.
326    #[serde(default)]
327    pub cursor: Option<String>,
328    /// Page size, at most 200.
329    #[serde(default)]
330    pub limit: Option<usize>,
331}
332
333async fn inbox(
334    State(endpoints): State<ApprovalEndpoints>,
335    Extension(caller): Extension<Option<RequestContext>>,
336    Query(params): Query<InboxParams>,
337) -> Response {
338    let caller_user = caller.as_ref().map(|context| context.user_id.clone());
339    let (subject, groups) = match endpoints.caller(caller) {
340        Ok(caller) => caller,
341        Err(response) => return response,
342    };
343    if params.session.is_some() && params.app.is_none() {
344        return problem(&AdkError::new(
345            ErrorComponent::Server,
346            ErrorCategory::InvalidInput,
347            "approval.session_needs_app",
348            "a session is named by its application, user and ID: pass `app` with `session`",
349        ));
350    }
351    let mut states = Vec::new();
352    for name in params.state.iter().flat_map(|states| states.split(',')) {
353        match serde_json::from_value::<ApprovalState>(Value::String(name.trim().to_string())) {
354            Ok(state) => states.push(state),
355            Err(_) => {
356                return problem(&AdkError::new(
357                    ErrorComponent::Server,
358                    ErrorCategory::InvalidInput,
359                    "approval.invalid_state",
360                    format!("unknown approval state '{name}'"),
361                ));
362            }
363        }
364    }
365    let mut query = match &params.group {
366        // A group's queue is visible only to its members.
367        Some(group) if groups.contains(group) => InboxQuery::for_group(group.clone()),
368        Some(group) => {
369            return problem(&AdkError::new(
370                ErrorComponent::Server,
371                ErrorCategory::Forbidden,
372                "approval.not_a_member",
373                format!("the caller is not a member of '{group}'"),
374            ));
375        }
376        None => InboxQuery::for_approver(subject, groups),
377    }
378    .with_states(states)
379    .with_cursor(params.cursor)
380    .with_limit(params.limit.unwrap_or(50).clamp(1, 200));
381    if let Some(app) = params.app {
382        query = query.with_app_name(app);
383    }
384    let user = match (&params.session, params.user) {
385        (Some(_), None) => caller_user,
386        (_, user) => user,
387    };
388    if let Some(user) = user {
389        query = query.with_user_id(user);
390    }
391    if let Some(session) = params.session {
392        query = query.with_session_id(session);
393    }
394    match endpoints.service.inbox(query).await {
395        Ok(page) => Json(serde_json::json!({
396            "items": page.items.iter().map(view).collect::<Vec<_>>(),
397            "nextCursor": page.next_cursor,
398        }))
399        .into_response(),
400        Err(error) => problem(&error),
401    }
402}
403
404async fn get_request(
405    State(endpoints): State<ApprovalEndpoints>,
406    Extension(caller): Extension<Option<RequestContext>>,
407    Path(id): Path<String>,
408) -> Response {
409    let (subject, groups) = match endpoints.caller(caller) {
410        Ok(caller) => caller,
411        Err(response) => return response,
412    };
413    match endpoints.service.get(&id).await {
414        Ok(Some(request)) => match endpoints.may_see(&request, &subject, &groups).await {
415            Ok(true) => Json(view(&request)).into_response(),
416            Ok(false) => not_found(&id),
417            Err(error) => problem(&error),
418        },
419        Ok(None) => not_found(&id),
420        Err(error) => problem(&error),
421    }
422}
423
424/// `POST /api/approvals/{id}/decide` body.
425#[derive(Debug, Deserialize)]
426#[serde(rename_all = "camelCase")]
427pub struct DecideBody {
428    /// The version the caller read; a stale one answers `409`.
429    pub expected_version: u64,
430    /// What the caller does.
431    pub action: ApprovalAction,
432    /// Replacement arguments for `edit`.
433    #[serde(default)]
434    pub edited_args: Option<Value>,
435    /// Rejection reason, or the text of `respond`.
436    #[serde(default)]
437    pub reason: Option<String>,
438    /// Act under the delegation from this subject.
439    #[serde(default)]
440    pub via: Option<SubjectRef>,
441}
442
443async fn decide(
444    State(endpoints): State<ApprovalEndpoints>,
445    Extension(caller): Extension<Option<RequestContext>>,
446    extensions: Extensions,
447    Path(id): Path<String>,
448    Json(body): Json<DecideBody>,
449) -> Response {
450    let context = caller.clone();
451    let (subject, groups) = match endpoints.caller(caller) {
452        Ok(caller) => caller,
453        Err(response) => return response,
454    };
455    // The host's check sees the request as it is now; a request the caller may not see is
456    // answered as the service answers it.
457    let guarded = match (&endpoints.guard, &context) {
458        (Some(guard), Some(context)) => match endpoints.service.get(&id).await {
459            Ok(Some(request)) => {
460                let call = DecideCall {
461                    caller: context,
462                    extensions: &extensions,
463                    request: &request,
464                    action: body.action,
465                };
466                if let Err(error) = guard.check(&call).await {
467                    return problem(&error);
468                }
469                Some((guard.clone(), request))
470            }
471            Ok(None) => None,
472            Err(error) => return problem(&error),
473        },
474        _ => None,
475    };
476    let mut decision = match body.action {
477        ApprovalAction::Approve => ApprovalDecision::approve(subject),
478        ApprovalAction::Edit => {
479            ApprovalDecision::edit(subject, body.edited_args.unwrap_or(Value::Null))
480        }
481        ApprovalAction::Reject => {
482            ApprovalDecision::reject(subject, body.reason.clone().unwrap_or_default())
483        }
484        ApprovalAction::Respond => {
485            ApprovalDecision::respond(subject, body.reason.clone().unwrap_or_default())
486        }
487    }
488    .with_groups(groups);
489    if matches!(body.action, ApprovalAction::Edit) && decision.edited_args == Some(Value::Null) {
490        decision.edited_args = None;
491    }
492    if matches!(body.action, ApprovalAction::Reject)
493        && body.reason.as_deref().is_none_or(str::is_empty)
494    {
495        decision.reason = None;
496    }
497    if let Some(via) = body.via {
498        decision = decision.via(via);
499    }
500    match endpoints.service.decide(&id, body.expected_version, decision).await {
501        Ok(decided) => {
502            if let (Some((guard, request)), Some(context)) = (&guarded, &context) {
503                let call = DecideCall {
504                    caller: context,
505                    extensions: &extensions,
506                    request,
507                    action: body.action,
508                };
509                guard.decided(&call, &decided).await;
510            }
511            Json(view(&decided)).into_response()
512        }
513        Err(error) => problem(&error),
514    }
515}
516
517/// `POST /api/approvals/{id}/cancel` body.
518#[derive(Debug, Default, Deserialize)]
519#[serde(rename_all = "camelCase")]
520pub struct CancelBody {
521    /// Why; reported to the model as part of the denial.
522    #[serde(default)]
523    pub reason: Option<String>,
524}
525
526async fn cancel(
527    State(endpoints): State<ApprovalEndpoints>,
528    Extension(caller): Extension<Option<RequestContext>>,
529    Path(id): Path<String>,
530    body: Option<Json<CancelBody>>,
531) -> Response {
532    let (subject, groups) = match endpoints.caller(caller) {
533        Ok(caller) => caller,
534        Err(response) => return response,
535    };
536    let request = match endpoints.service.get(&id).await {
537        Ok(Some(request)) => request,
538        Ok(None) => return not_found(&id),
539        Err(error) => return problem(&error),
540    };
541    match endpoints.may_see(&request, &subject, &groups).await {
542        Ok(true) => {}
543        Ok(false) => return not_found(&id),
544        Err(error) => return problem(&error),
545    }
546    let reason = body.and_then(|Json(body)| body.reason);
547    match endpoints.service.cancel(&id, reason).await {
548        Ok(request) => Json(view(&request)).into_response(),
549        Err(error) => problem(&error),
550    }
551}
552
553/// `POST /api/approvals/delegations` body.
554#[derive(Debug, Deserialize)]
555#[serde(rename_all = "camelCase")]
556pub struct DelegateBody {
557    /// The delegate.
558    pub to: SubjectRef,
559    /// When the delegation starts; defaults to now.
560    #[serde(default)]
561    pub not_before: Option<DateTime<Utc>>,
562    /// When it ends.
563    pub not_after: DateTime<Utc>,
564    /// Which requests it covers; defaults to all.
565    #[serde(default)]
566    pub scope: Option<DelegationScope>,
567}
568
569async fn create_delegation(
570    State(endpoints): State<ApprovalEndpoints>,
571    Extension(caller): Extension<Option<RequestContext>>,
572    Json(body): Json<DelegateBody>,
573) -> Response {
574    let (subject, groups) = match endpoints.caller(caller) {
575        Ok(caller) => caller,
576        Err(response) => return response,
577    };
578    let window = DelegationWindow::new(body.not_before.unwrap_or_else(Utc::now), body.not_after);
579    let delegation = ApprovalDelegation::new(subject, body.to, window)
580        .with_from_groups(groups)
581        .with_scope(body.scope.unwrap_or_default());
582    match endpoints.service.delegate(delegation).await {
583        Ok(delegation) => (StatusCode::CREATED, Json(delegation)).into_response(),
584        Err(error) => problem(&error),
585    }
586}
587
588/// `DELETE /api/approvals/delegations/{id}` query: the delegate, so the delegation can
589/// be found.
590#[derive(Debug, Deserialize)]
591#[serde(rename_all = "camelCase")]
592pub struct RevokeParams {
593    /// The delegate's kind.
594    pub to_kind: SubjectKind,
595    /// The delegate's ID.
596    pub to_id: String,
597}
598
599async fn revoke_delegation(
600    State(endpoints): State<ApprovalEndpoints>,
601    Extension(caller): Extension<Option<RequestContext>>,
602    Path(id): Path<String>,
603    Query(params): Query<RevokeParams>,
604) -> Response {
605    let (subject, _) = match endpoints.caller(caller) {
606        Ok(caller) => caller,
607        Err(response) => return response,
608    };
609    let to = SubjectRef::new(params.to_kind, params.to_id);
610    let held = match endpoints.service.delegations_to(&to).await {
611        Ok(held) => held,
612        Err(error) => return problem(&error),
613    };
614    let Some(delegation) = held.into_iter().find(|delegation| delegation.id == id) else {
615        return StatusCode::NOT_FOUND.into_response();
616    };
617    if delegation.from != subject && delegation.to != subject {
618        return StatusCode::NOT_FOUND.into_response();
619    }
620    match endpoints.service.revoke_delegation(&id).await {
621        Ok(_) => StatusCode::NO_CONTENT.into_response(),
622        Err(error) => problem(&error),
623    }
624}
625
626// ---------------------------------------------------------------------------
627// Webhook notifier
628// ---------------------------------------------------------------------------
629
630/// Delivers [`ApprovalNotification`]s as signed webhooks in the Standard Webhooks
631/// format, through the shared [`WebhookDelivery`](adk_core::webhook_delivery::WebhookDelivery).
632///
633/// Each delivery is a `POST` of the notification as JSON with `webhook-id` (the
634/// notification ID, stable across retries), `webhook-timestamp` (Unix seconds), and
635/// `webhook-signature` ([`adk_core::webhook`]). Deliveries run in the background with
636/// retries, exponential backoff, and jitter, so a slow receiver never holds up a decision;
637/// the last failure is dead-lettered. The default egress policy allows HTTPS to public
638/// addresses only; [`with_delivery`](Self::with_delivery) changes it.
639///
640/// # Example
641///
642/// ```rust
643/// use adk_server::approvals::WebhookApprovalNotifier;
644///
645/// let notifier = WebhookApprovalNotifier::new(
646///     "https://hooks.example.com/approvals",
647///     "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw",
648/// )?;
649/// # Ok::<(), adk_core::AdkError>(())
650/// ```
651#[derive(Clone)]
652pub struct WebhookApprovalNotifier {
653    endpoint: adk_core::webhook_delivery::WebhookEndpoint,
654    secret: adk_core::webhook::WebhookSecret,
655    delivery: Arc<adk_core::webhook_delivery::WebhookDelivery>,
656}
657
658impl std::fmt::Debug for WebhookApprovalNotifier {
659    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
660        f.debug_struct("WebhookApprovalNotifier")
661            .field("url", &self.endpoint.url)
662            .finish_non_exhaustive()
663    }
664}
665
666impl WebhookApprovalNotifier {
667    /// Delivers to `url`, signing with `secret`: base64, optionally `whsec_`-prefixed.
668    ///
669    /// # Errors
670    ///
671    /// Returns `approval.webhook_secret` when the secret is not base64.
672    pub fn new(url: impl Into<String>, secret: &str) -> Result<Self, AdkError> {
673        let secret = adk_core::webhook::WebhookSecret::from_base64(secret).map_err(|e| {
674            AdkError::new(
675                ErrorComponent::Server,
676                ErrorCategory::InvalidInput,
677                "approval.webhook_secret",
678                format!("{e}"),
679            )
680        })?;
681        Ok(Self {
682            endpoint: adk_core::webhook_delivery::WebhookEndpoint::new(url, secret.clone()),
683            secret,
684            delivery: Arc::new(adk_core::webhook_delivery::WebhookDelivery::new()),
685        })
686    }
687
688    /// Delivers through `delivery`, for a custom retry policy, dead-letter sink, or egress
689    /// policy (for example `EgressPolicy::allow_private_networks()` for an in-cluster receiver).
690    pub fn with_delivery(mut self, delivery: adk_core::webhook_delivery::WebhookDelivery) -> Self {
691        self.delivery = Arc::new(delivery);
692        self
693    }
694
695    /// The `webhook-signature` header for `body` sent as `id` at `timestamp`.
696    pub fn signature(&self, id: &str, timestamp: i64, body: &str) -> String {
697        self.secret.signature(id, timestamp, body.as_bytes())
698    }
699}
700
701#[async_trait::async_trait]
702impl ApprovalNotifier for WebhookApprovalNotifier {
703    async fn notify(&self, notification: &ApprovalNotification) -> adk_core::Result<()> {
704        let message =
705            adk_core::webhook_delivery::WebhookMessage::json(notification.id.clone(), notification)
706                .map_err(|e| {
707                    AdkError::new(
708                        ErrorComponent::Server,
709                        ErrorCategory::Internal,
710                        "approval.webhook_encode",
711                        format!("could not encode the approval notification: {e}"),
712                    )
713                })?;
714        let delivery = Arc::clone(&self.delivery);
715        let endpoint = self.endpoint.clone();
716        tokio::spawn(async move {
717            let report = delivery.deliver(&endpoint, &message).await;
718            tracing::debug!(
719                webhook.id = %message.id,
720                delivered = report.is_delivered(),
721                "approval notification delivery finished"
722            );
723        });
724        Ok(())
725    }
726}