Skip to main content

greentic_runner_host/runner/approval_http/
mod.rs

1//! The HTTP approval rail: human approvals on lanes that have no NATS broker.
2//!
3//! Design: greentic-designer
4//! `docs/superpowers/specs/2026-09-29-approval-rail-http-design.md` §4 (and
5//! its §13 amendments, which override the body). Wire contract: [`wire`].
6//!
7//! An `approval.call` node that needs a human is a REMOTE DISPATCH. Where no
8//! broker is configured (the designer's env-canvas Cloud Run and k8s lanes),
9//! [`HttpApprovalDispatcher`]:
10//!
11//! 1. **Sends** the request to the admin's ingest door with the `decision_token`
12//!    STRIPPED — the token never leaves the worker on this transport — and
13//!    keeps it in memory, keyed by the nonced correlation id. A send that the
14//!    admin did not record fails the node rather than parking a gate nobody
15//!    will ever see.
16//! 2. **Polls** for the decision from one task per runtime (5 s for the first
17//!    minute, then 15 s; 60 s after a transient failure).
18//! 3. **Resumes exactly once.** The first `200` ends polling for that id,
19//!    whatever happens next. The resume goes through a STRICT
20//!    [`RuntimeSessionResumer`](crate::runner::runtime_session_resumer::RuntimeSessionResumer::strict):
21//!    a decision for a gate that is no longer parked under exactly this nonced
22//!    id is dropped, and NEVER starts a fresh run from the flow's entrypoint.
23//!    The worker's own held token is injected at `output.decision_token`, so
24//!    the gate's usual token check runs unchanged and spends it.
25//! 4. **Watches the deadline** locally: at the node's `deadline_ms` (a default
26//!    of 7 days when the node sets none, and never more than 7 days), it stops
27//!    polling, withdraws the request, and resumes with the same `timeout` body
28//!    the NATS watchdog publishes. One task, one outcome — a real decision
29//!    cancels the timeout and vice versa.
30//!
31//! It goes into the engine's own `approval_dispatch_handler` slot, never the
32//! shared `remote_dispatch_handler` one, so `sorla.call` keeps failing with
33//! `sorla_route_missing` on these lanes (spec §4.1).
34//!
35//! # Lifetime
36//!
37//! The poller, every held token and the resumer are released by
38//! [`HttpApprovalDispatcher::shutdown`], which the owning `TenantRuntime`
39//! calls on drop: a superseded revision stops polling and cannot resume into a
40//! session store it no longer owns. Shutdown also drops the resumer, which
41//! breaks the `resumer → runtime → engine → dispatcher` reference cycle.
42//!
43//! # Not solved here
44//!
45//! Held tokens live in memory: a restart of the process loses the poller even
46//! when the park itself survives in a durable session store (spec §12).
47//!
48//! Neither token — the worker-usage bearer nor a `decision_token` — is ever
49//! logged, at any level.
50
51pub mod wire;
52
53mod poller;
54#[cfg(test)]
55mod tests;
56
57use std::collections::HashMap;
58use std::sync::Arc;
59use std::time::Duration;
60
61use anyhow::{Result, anyhow, bail};
62use async_trait::async_trait;
63use greentic_types::{DispatchMode, EnvId, TenantCtx, TenantId};
64use parking_lot::Mutex;
65use secrecy::{ExposeSecret, SecretString};
66use tokio::sync::Notify;
67use tokio::time::Instant;
68use tokio_util::sync::CancellationToken;
69
70use super::dispatch_listener::SessionResumer;
71use super::remote_dispatch::{RemoteDispatch, RemoteDispatchAction, RemoteDispatchHandler};
72
73pub use wire::{
74    APPROVAL_RAIL_HEADER, APPROVAL_RAIL_USER_AGENT, APPROVAL_RAIL_VERSION, ApprovalDecisionBody,
75    ApprovalDecisionKind, ApprovalRequestBody, ApprovalWithdrawBody, WithdrawReason,
76};
77
78/// The longest any approval waits on this rail, and the deadline applied to
79/// one whose node sets none (spec §4.3).
80pub const MAX_APPROVAL_WAIT: Duration = Duration::from_secs(7 * 24 * 60 * 60);
81
82/// Budget for DNS + connect + TLS handshake.
83const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
84/// Budget for one whole request.
85const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
86
87/// Where and as whom one unit's approvals are filed and fetched. Every field
88/// is the value the embedding host (greentic-start) resolved for ONE unit from
89/// its staged `metering` block.
90#[derive(Clone)]
91pub struct ApprovalInboxTarget {
92    /// `{admin}/api/v1/ingest/approval-request`.
93    pub request_url: String,
94    /// `{admin}/api/v1/ingest/approval-decision`.
95    pub decision_url: String,
96    /// `{admin}/api/v1/ingest/approval-withdraw`.
97    pub withdraw_url: String,
98    /// The unit's `gtm_` worker-usage bearer (with the `approvals` purpose).
99    /// Only ever sent as a header; never logged.
100    pub token: String,
101    /// The workspace tenant the token belongs to.
102    pub tenant_slug: String,
103}
104
105impl std::fmt::Debug for ApprovalInboxTarget {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        f.debug_struct("ApprovalInboxTarget")
108            .field("request_url", &self.request_url)
109            .field("decision_url", &self.decision_url)
110            .field("withdraw_url", &self.withdraw_url)
111            .field("token", &"<redacted>")
112            .field("tenant_slug", &self.tenant_slug)
113            .finish()
114    }
115}
116
117/// Why an [`ApprovalInboxTarget`] could not configure an inbox. Never names
118/// the token.
119#[derive(Debug, thiserror::Error)]
120pub enum ApprovalInboxError {
121    #[error("approval inbox needs a non-blank `{0}`")]
122    Blank(&'static str),
123    #[error(
124        "approval inbox `{0}` is not https and not loopback http; refusing to send a bearer \
125         token in cleartext"
126    )]
127    UnsafeUrl(String),
128    #[error("approval inbox has no HTTP client: {0}")]
129    Client(String),
130}
131
132/// Poll and retry cadence. Production uses [`Timing::default`]; tests shrink it.
133#[derive(Clone, Debug)]
134pub(crate) struct Timing {
135    /// Delays before each RETRY of a send (the first send is immediate).
136    pub(crate) send_retry_delays: Vec<Duration>,
137    /// Poll interval while an approval is younger than `fast_window`.
138    pub(crate) fast_interval: Duration,
139    /// How long an approval is polled at `fast_interval`.
140    pub(crate) fast_window: Duration,
141    /// Poll interval afterwards.
142    pub(crate) slow_interval: Duration,
143    /// Poll interval after a transient failure.
144    pub(crate) backoff: Duration,
145    /// Deadline applied when the node sets none, and the hard cap.
146    pub(crate) max_wait: Duration,
147}
148
149impl Default for Timing {
150    fn default() -> Self {
151        Self {
152            send_retry_delays: vec![
153                Duration::from_secs(1),
154                Duration::from_secs(4),
155                Duration::from_secs(10),
156            ],
157            fast_interval: Duration::from_secs(5),
158            fast_window: Duration::from_secs(60),
159            slow_interval: Duration::from_secs(15),
160            backoff: Duration::from_secs(60),
161            max_wait: MAX_APPROVAL_WAIT,
162        }
163    }
164}
165
166/// One approval this worker is waiting on.
167pub(crate) struct Pending {
168    /// The dispatch's own tenant context — the resume runs under it.
169    pub(crate) tenant: TenantCtx,
170    pub(crate) env: String,
171    /// The token this gate was issued, held until the one resume.
172    pub(crate) decision_token: Option<SecretString>,
173    pub(crate) registered_at: Instant,
174    pub(crate) deadline_at: Instant,
175    /// The deadline as the node sees it, for the `timeout` message.
176    pub(crate) deadline_ms: u64,
177    /// What the withdrawal at `deadline_at` says.
178    pub(crate) deadline_reason: WithdrawReason,
179    pub(crate) next_poll_at: Instant,
180}
181
182pub(crate) struct Inner {
183    pub(crate) request_url: String,
184    pub(crate) decision_url: url::Url,
185    pub(crate) withdraw_url: String,
186    pub(crate) token: SecretString,
187    pub(crate) tenant_slug: String,
188    pub(crate) http: reqwest::Client,
189    pub(crate) timing: Timing,
190    pub(crate) pending: Mutex<HashMap<String, Pending>>,
191    pub(crate) resumer: Mutex<Option<Arc<dyn SessionResumer>>>,
192    pub(crate) cancel: CancellationToken,
193    pub(crate) wake: Notify,
194    pub(crate) poller_started: Mutex<bool>,
195}
196
197/// The HTTP approval inbox, as a [`RemoteDispatchHandler`] for the engine's
198/// approval slot. Cheap to clone; clones share one poller and one set of held
199/// tokens.
200#[derive(Clone)]
201pub struct HttpApprovalDispatcher {
202    pub(crate) inner: Arc<Inner>,
203}
204
205impl std::fmt::Debug for HttpApprovalDispatcher {
206    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207        f.debug_struct("HttpApprovalDispatcher")
208            .field("request_url", &self.inner.request_url)
209            .field("token", &"<redacted>")
210            .field("tenant_slug", &self.inner.tenant_slug)
211            .field("pending", &self.inner.pending.lock().len())
212            .finish()
213    }
214}
215
216fn required(field: &'static str, value: &str) -> Result<String, ApprovalInboxError> {
217    let trimmed = value.trim();
218    if trimmed.is_empty() {
219        return Err(ApprovalInboxError::Blank(field));
220    }
221    Ok(trimmed.to_string())
222}
223
224/// `https` anywhere, or `http` to a loopback host.
225fn safe_url(field: &'static str, value: &str) -> Result<url::Url, ApprovalInboxError> {
226    let value = required(field, value)?;
227    let unsafe_url = || ApprovalInboxError::UnsafeUrl(value.clone());
228    let url = url::Url::parse(&value).map_err(|_| unsafe_url())?;
229    let safe = match url.scheme() {
230        "https" => url.host().is_some(),
231        "http" => match url.host() {
232            Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
233            Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
234            Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
235            None => false,
236        },
237        _ => false,
238    };
239    if safe { Ok(url) } else { Err(unsafe_url()) }
240}
241
242impl HttpApprovalDispatcher {
243    /// Build an inbox for one unit. Refuses a blank field and any URL that
244    /// would carry the token in cleartext off this host. Nothing is sent and
245    /// no task is spawned until the first approval is dispatched.
246    pub fn new(target: ApprovalInboxTarget) -> Result<Self, ApprovalInboxError> {
247        Self::with_timing(target, Timing::default())
248    }
249
250    pub(crate) fn with_timing(
251        target: ApprovalInboxTarget,
252        timing: Timing,
253    ) -> Result<Self, ApprovalInboxError> {
254        let request_url = safe_url("request_url", &target.request_url)?;
255        let decision_url = safe_url("decision_url", &target.decision_url)?;
256        let withdraw_url = safe_url("withdraw_url", &target.withdraw_url)?;
257        let token = required("token", &target.token)?;
258        let tenant_slug = required("tenant_slug", &target.tenant_slug)?;
259        let http = reqwest::Client::builder()
260            .timeout(REQUEST_TIMEOUT)
261            .connect_timeout(CONNECT_TIMEOUT)
262            .user_agent(APPROVAL_RAIL_USER_AGENT)
263            .build()
264            .map_err(|err| ApprovalInboxError::Client(err.to_string()))?;
265        Ok(Self {
266            inner: Arc::new(Inner {
267                request_url: request_url.to_string(),
268                decision_url,
269                withdraw_url: withdraw_url.to_string(),
270                token: SecretString::from(token),
271                tenant_slug,
272                http,
273                timing,
274                pending: Mutex::new(HashMap::new()),
275                resumer: Mutex::new(None),
276                cancel: CancellationToken::new(),
277                wake: Notify::new(),
278                poller_started: Mutex::new(false),
279            }),
280        })
281    }
282
283    /// Hand the inbox the resumer its decisions are delivered through. The
284    /// runtime installs a STRICT `RuntimeSessionResumer` here right after the
285    /// state machine exists. Ignored once [`Self::shutdown`] has run.
286    pub fn attach_resumer(&self, resumer: Arc<dyn SessionResumer>) {
287        if self.inner.cancel.is_cancelled() {
288            return;
289        }
290        *self.inner.resumer.lock() = Some(resumer);
291    }
292
293    /// Stop polling, forget every held token and drop the resumer. Called by
294    /// the owning `TenantRuntime` on drop. Idempotent. Pending approvals are
295    /// NOT withdrawn: the admin console refuses a row whose worker stopped
296    /// polling (spec §6.1.5).
297    pub fn shutdown(&self) {
298        self.inner.cancel.cancel();
299        self.inner.pending.lock().clear();
300        self.inner.resumer.lock().take();
301    }
302
303    /// A clone of the token that [`Self::shutdown`] cancels.
304    pub fn cancellation_token(&self) -> CancellationToken {
305        self.inner.cancel.clone()
306    }
307
308    /// How many approvals are being polled for.
309    pub fn pending_count(&self) -> usize {
310        self.inner.pending.lock().len()
311    }
312
313    fn authed(&self, builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
314        builder
315            .bearer_auth(self.inner.token.expose_secret())
316            .header(APPROVAL_RAIL_HEADER, APPROVAL_RAIL_VERSION)
317    }
318
319    /// POST the request, retrying transport errors, `5xx` and any `429` but
320    /// the pending cap. `Ok` only when the admin recorded it.
321    async fn send(&self, body: &ApprovalRequestBody) -> Result<()> {
322        let delays = self.inner.timing.send_retry_delays.clone();
323        let mut last = String::new();
324        for attempt in 0..=delays.len() {
325            if attempt > 0 {
326                tokio::time::sleep(delays[attempt - 1]).await;
327            }
328            let sent = self
329                .authed(self.inner.http.post(&self.inner.request_url))
330                .json(body)
331                .send()
332                .await;
333            let response = match sent {
334                Ok(response) => response,
335                Err(error) => {
336                    last = format!("transport error: {}", error.without_url());
337                    continue;
338                }
339            };
340            let status = response.status();
341            if status.is_success() {
342                return Ok(());
343            }
344            let text = response.text().await.unwrap_or_default();
345            if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
346                if text.contains(wire::PENDING_CAP_CODE) {
347                    bail!(
348                        "approval inbox refused the request: this worker already has the maximum \
349                         number of pending approvals ({})",
350                        wire::PENDING_CAP_CODE
351                    );
352                }
353                last = format!("HTTP {status}");
354                continue;
355            }
356            if status.is_server_error() {
357                last = format!("HTTP {status}");
358                continue;
359            }
360            bail!("approval inbox refused the request with HTTP {status}");
361        }
362        Err(anyhow!(
363            "approval inbox did not record the request after {} attempts ({last})",
364            delays.len() + 1
365        ))
366    }
367
368    fn register(&self, correlation_id: String, pending: Pending) {
369        self.inner.pending.lock().insert(correlation_id, pending);
370        self.ensure_poller();
371        self.inner.wake.notify_one();
372    }
373
374    fn ensure_poller(&self) {
375        let mut started = self.inner.poller_started.lock();
376        if *started || self.inner.cancel.is_cancelled() {
377            return;
378        }
379        *started = true;
380        tokio::spawn(poller::run(Arc::clone(&self.inner)));
381    }
382}
383
384/// The effective deadline and what its expiry is called (spec §4.3): the
385/// node's own `deadline_ms` when it is within the cap (`timeout`), else the
386/// cap (`poll_cap`).
387fn effective_deadline(node_deadline_ms: Option<u64>, cap: Duration) -> (u64, WithdrawReason) {
388    let cap_ms = u64::try_from(cap.as_millis()).unwrap_or(u64::MAX);
389    match node_deadline_ms {
390        Some(ms) if ms <= cap_ms => (ms, WithdrawReason::Timeout),
391        _ => (cap_ms, WithdrawReason::PollCap),
392    }
393}
394
395#[async_trait]
396impl RemoteDispatchHandler for HttpApprovalDispatcher {
397    async fn dispatch(&self, request: RemoteDispatch) -> Result<RemoteDispatchAction> {
398        if request.runtime != crate::runner::engine::APPROVAL_RUNTIME {
399            bail!(
400                "{}.call dispatched to the approval inbox, which serves only approval.call",
401                request.runtime
402            );
403        }
404        if self.inner.cancel.is_cancelled() {
405            bail!("approval inbox is shut down; this revision is no longer serving");
406        }
407        let tenant = TenantCtx::new(
408            EnvId::try_from(request.env.as_str())
409                .map_err(|error| anyhow!("invalid env for approval dispatch: {error}"))?,
410            TenantId::try_from(request.tenant.as_str())
411                .map_err(|error| anyhow!("invalid tenant for approval dispatch: {error}"))?,
412        );
413        let (deadline_ms, deadline_reason) =
414            effective_deadline(request.deadline_ms, self.inner.timing.max_wait);
415        let body = wire::request_body(
416            &self.inner.tenant_slug,
417            &request.correlation_id,
418            &request.target,
419            &request.operation,
420            request.mode,
421            request.input,
422            deadline_ms,
423        );
424        self.send(&body).await?;
425
426        match request.mode {
427            DispatchMode::FireAndForget => Ok(RemoteDispatchAction::Dispatched),
428            DispatchMode::Await => {
429                let now = Instant::now();
430                self.register(
431                    request.correlation_id.clone(),
432                    Pending {
433                        tenant,
434                        env: request.env,
435                        decision_token: request.decision_token.map(SecretString::from),
436                        registered_at: now,
437                        deadline_at: now + Duration::from_millis(deadline_ms),
438                        deadline_ms,
439                        deadline_reason,
440                        next_poll_at: now + self.inner.timing.fast_interval,
441                    },
442                );
443                Ok(RemoteDispatchAction::AwaitingResponse {
444                    correlation_id: request.correlation_id,
445                })
446            }
447        }
448    }
449}
450
451/// Whether a runtime should install the HTTP approval inbox: only when a
452/// target was handed over AND no NATS broker connected. NATS stays
453/// authoritative where configured (spec §2.5, §4.6).
454pub(crate) fn inbox_to_install(
455    nats_connected: bool,
456    target: Option<ApprovalInboxTarget>,
457) -> Option<ApprovalInboxTarget> {
458    if nats_connected { None } else { target }
459}