Skip to main content

ignition_core/client/
mod.rs

1//! The gateway HTTP seam: a coarse [`GatewayApi`] trait so actions never
2//! touch reqwest types, plus the production [`ReqwestGatewayApi`].
3//!
4//! LOCKED: the trait uses `async_trait` (research Open Question 2,
5//! resolved) — dyn-compatible today, ubiquitous. The trait stays COARSE —
6//! one method per capability, not per endpoint — so Phase 2 grows it
7//! without churn.
8//!
9//! Auth-header rule (verified against a live 8.3.6 gateway, 02-RESEARCH
10//! §Auth Model): a token credential sends `X-Ignition-API-Token`; a basic
11//! credential sends `Authorization: Basic <b64>`; NEVER both — enforced by
12//! a match in [`ReqwestGatewayApi::apply_auth`], the ONE place
13//! [`Secret::expose`] is called outside the secret module (the
14//! grep-auditable redaction boundary; CORE-02).
15//!
16//! Basic is loudly demoted there: valid Basic credentials → 401 on every
17//! 8.3 `/data` route (verified), so each use warns — never silently
18//! retried. Note gateway-info itself DOES require auth under 8.3 default
19//! security (header-less → 401, re-verified live 2026-08-21 — the 83-api
20//! collection's `auth: none` tag does not hold); a `None` credential
21//! proceeds header-less and classifies the answer.
22//!
23//! Redirects are never followed (`Policy::none()`): an uncommissioned
24//! gateway 302s EVERYTHING to `/welcome` and the default follow would
25//! render the wizard's HTML as a 200 (02-RESEARCH Pitfall 6). The 3xx is
26//! classified by [`classify`] instead.
27//!
28//! Every request runs the pipeline: build URL → apply auth (opt-in) →
29//! send (transport error → `Network`) → [`classify`] → parse the body.
30//! Nothing ever calls `.json()` on a response that skipped `classify()`.
31
32use std::path::Path;
33use std::time::Duration;
34
35pub mod adopt;
36pub mod apicall;
37pub mod backup;
38mod classify;
39pub mod config_resources;
40pub mod connections;
41pub mod deploy_api;
42pub mod diagnostics;
43pub mod eam;
44pub mod gan;
45pub mod idp;
46pub mod license;
47pub mod logs;
48pub mod metrics;
49pub mod mode;
50pub mod projects;
51pub mod query;
52pub mod redundancy;
53pub mod resources;
54pub mod restart;
55pub mod scan;
56pub mod scripts_codec;
57pub mod sessions;
58pub mod status;
59pub mod tags;
60pub mod threads;
61pub mod trial;
62pub mod version;
63pub mod webdev;
64pub mod workspace;
65
66/// The deploy-facing scan-lock and scan calls (a trait of their own, so
67/// [`GatewayApi`] and its test doubles stay untouched).
68pub use deploy_api::DeployApi;
69
70use crate::client::connections::GatewayConnection;
71use crate::client::diagnostics::BundleStatusWire;
72use crate::client::eam::{
73    DeleteOutcome, EamHistoryItem, EamScheduledTask, EamTaskRecord, ModifyOutcome,
74};
75use crate::client::gan::GanStatusWire;
76use crate::client::license::LicenseStatusWire;
77use crate::client::logs::{LogDownload, LogEntry, LogQuery, LoggerInfo};
78use crate::client::metrics::{CurrentGauges, PerformanceCharts, ThreadCounts};
79use crate::client::projects::{
80    ExportMeta, ImportOutcome, ProjectCopy, ProjectCreate, ProjectModify, ProjectRecord,
81    ProjectRenameBody,
82};
83use crate::client::query::ListEnvelope;
84use crate::client::redundancy::RedundancyStatusWire;
85use crate::client::restart::SecurityProperties;
86use crate::client::sessions::{DesignerInfo, PerspectiveSession, VisionClient};
87use crate::client::status::{ModuleInfo, Overview, StatusPing};
88use crate::client::tags::{TagProviderCreate, TagProviderRecord};
89use crate::client::trial::{BannerSet, TrialWire};
90use crate::client::version::GatewayInfo;
91use crate::client::webdev::{RouteBody, RouteProbe};
92use crate::config::{Credential, Profile};
93use crate::error::CoreError;
94
95/// GET path of the gateway-info capability.
96const GATEWAY_INFO_PATH: &str = "/data/api/v1/gateway-info";
97
98/// One capability per method — coarse on purpose. Phase 2 adds status,
99/// modules, metrics, … as methods here; actions never see reqwest types.
100///
101/// (All impl bodies live in the ONE `impl GatewayApi for
102/// ReqwestGatewayApi` block below: Rust rejects a second impl block of
103/// the same trait for the same type, so the per-capability files own the
104/// models + verified path constants and this block owns the delegation.)
105#[async_trait::async_trait]
106pub trait GatewayApi: Send + Sync {
107    /// Fetch `/data/api/v1/gateway-info`.
108    async fn gateway_info(&self) -> Result<GatewayInfo, CoreError>;
109    /// Fetch `/data/api/v1/overview` (authed) — platform + runtime.
110    async fn overview(&self) -> Result<Overview, CoreError>;
111    /// Fetch `/StatusPing` **header-less** (auth=false) — the
112    /// unauthenticated readiness anchor: it must keep answering when
113    /// credentials are broken or absent and mid-restart (02-02).
114    async fn status_ping(&self) -> Result<StatusPing, CoreError>;
115    /// Fetch `/data/api/v1/modules/healthy` (`quarantined = false`) or
116    /// `/modules/quarantined` (`true`) with the standard list params.
117    async fn modules(
118        &self,
119        quarantined: bool,
120        query: &query::ListQuery,
121    ) -> Result<ListEnvelope<ModuleInfo>, CoreError>;
122    /// DELETE `/data/api/v1/modules/uninstall` (Phase 19,
123    /// D-19-03/D-19-04) — uninstalls ONE module by its GATEWAY id.
124    /// **Denial rides HTTP 200**: the gateway always answers 200, so
125    /// the verdict comes from the body's `success`/`failedUninstalls`,
126    /// never the status alone (live-verified: a stock module, a bogus
127    /// id, and a still-mounted module all answer 200 with
128    /// `success:false`). Never batches — exactly one id per call
129    /// (D-19-04 sidesteps the never-observed mixed-batch shape
130    /// entirely). `module_id` is the REGISTRY slug (never sent on the
131    /// wire) so a denial can name both ids without a reverse lookup.
132    async fn uninstall_module(
133        &self,
134        gateway_module_id: &str,
135        module_id: &str,
136    ) -> Result<(), CoreError>;
137    /// Fetch `/data/api/v1/systemPerformance/currentGauges` (authed) —
138    /// cpu in PERCENT (contrast [`Overview::cpu`], a 0–1 fraction).
139    async fn metrics_current(&self) -> Result<CurrentGauges, CoreError>;
140    /// Fetch `/data/api/v1/systemPerformance/charts` (authed) — historic
141    /// cpu/heap/non-heap datapoints (epoch-ms timestamps).
142    async fn metrics_historic(&self) -> Result<PerformanceCharts, CoreError>;
143    /// Fetch `/data/api/v1/systemPerformance/threads` (authed) — thread
144    /// execution counts (running/waiting/timedWaiting/blocked).
145    async fn metrics_threads(&self) -> Result<ThreadCounts, CoreError>;
146    /// Fetch `/data/api/v1/diagnostics/threads/dump/formatted` (authed)
147    /// — the Gateway web UI's Diagnostics→Threads page data: one entry
148    /// per JVM thread (state, daemon, cpuUsage, stacktrace, monitors).
149    /// Every field tolerant — the spec's own "not all fields
150    /// guaranteed" caveat.
151    async fn thread_dump(&self) -> Result<threads::FormattedThreadDump, CoreError>;
152    /// Fetch `/data/api/v1/diagnostics/threads/deadlocks` (authed) —
153    /// the JVM-reported deadlocked thread ids (empty = healthy).
154    async fn thread_deadlocks(&self) -> Result<threads::DeadlocksWire, CoreError>;
155    /// Fetch `/data/api/v1/designers` (authed) — active Designer
156    /// sessions (02-03, HLTH-08).
157    async fn designers(
158        &self,
159        query: &query::ListQuery,
160    ) -> Result<ListEnvelope<DesignerInfo>, CoreError>;
161    /// Fetch `/data/perspective/api/v1/sessions/` (authed) — the EXACT
162    /// trailing slash is the contract (Pitfall 8; module-scoped prefix).
163    async fn perspective_sessions(
164        &self,
165        query: &query::ListQuery,
166    ) -> Result<ListEnvelope<PerspectiveSession>, CoreError>;
167    /// Fetch `/data/vision/api/v1/clients` (authed) — active Vision
168    /// clients (designer shape + `tagCount`).
169    async fn vision_clients(
170        &self,
171        query: &query::ListQuery,
172    ) -> Result<ListEnvelope<VisionClient>, CoreError>;
173    /// DELETE `/data/perspective/api/v1/sessions?sessionId=<id>` (+ an
174    /// optional `message` shown to the session's user) — NO trailing
175    /// slash on the DELETE (spec). Audit-logged server-side.
176    async fn terminate_perspective_session(
177        &self,
178        id: &str,
179        message: Option<&str>,
180    ) -> Result<(), CoreError>;
181    /// DELETE `/data/vision/api/v1/client/{id}` — terminate a Vision
182    /// client. Audit-logged server-side.
183    async fn terminate_vision_client(&self, id: &str) -> Result<(), CoreError>;
184    /// DELETE `/data/api/v1/designer/{id}` — prune a Designer session.
185    /// Audit-logged server-side.
186    async fn prune_designer(&self, id: &str) -> Result<(), CoreError>;
187    /// Fetch `/data/api/v1/resources/list/ignition/database-connection`
188    /// (authed) — the web UI's Connections→Databases poll (HLTH-05).
189    /// `healthchecks` is raw passthrough (LOW-confidence populated
190    /// shape, research Open Question 1).
191    async fn database_connections(&self) -> Result<ListEnvelope<GatewayConnection>, CoreError>;
192    /// Fetch `/data/api/v1/resources/list/ignition/opc-connection`
193    /// (authed) — the Connections→OPC poll (HLTH-06), same family.
194    async fn opc_connections(&self) -> Result<ListEnvelope<GatewayConnection>, CoreError>;
195    /// Fetch `/data/api/v1/logs` (authed) with [`LogQuery`] — the tail
196    /// primitive: `startTime` (epoch ms) is the cursor, no server push
197    /// exists (02-04, HLTH-03). The query ALWAYS carries an explicit
198    /// `limit` (Pitfall 9 — the server default is unlimited).
199    async fn logs(&self, filter: &LogQuery) -> Result<ListEnvelope<LogEntry>, CoreError>;
200    /// GET `/data/api/v1/logs/download` (authed, per-request 120 s
201    /// timeout) — a SQLite `.idb` archive, returned byte-for-byte with
202    /// the `Content-Disposition` filename and `Content-Type`. NEVER
203    /// zipped/extracted (Pitfall 7; Don't-Hand-Roll table).
204    async fn logs_download(&self) -> Result<LogDownload, CoreError>;
205    /// Fetch `/data/api/v1/logs/loggers` (authed) — the logger registry
206    /// (HLTH-04; ~1250 loggers on a fresh gateway).
207    async fn loggers(
208        &self,
209        query: &query::ListQuery,
210    ) -> Result<ListEnvelope<LoggerInfo>, CoreError>;
211    /// POST `/data/api/v1/logs/loggers/{loggerName}?level=X` (authed,
212    /// empty body, NO CSRF — verified: token mutations need none).
213    /// Logger names are Java identifiers `[A-Za-z0-9._]` — URL-safe,
214    /// embedded as-is. Audit-logged server-side.
215    async fn set_logger_level(&self, logger: &str, level: &str) -> Result<(), CoreError>;
216    /// POST `/data/api/v1/logs/levelreset` (authed, empty body) — reset
217    /// all custom logger levels to defaults. Audit-logged server-side.
218    async fn reset_logger_levels(&self) -> Result<(), CoreError>;
219    /// POST `/data/api/v1/restart-tasks/restart?confirm=true` (authed,
220    /// empty body, NO CSRF — token mutations need none) — the one big
221    /// red button. The gateway answers 200 with the literal body `true`
222    /// almost immediately; the ~40 s wait is poller-side (02-05's
223    /// `restart --wait` owns it). Audit-logged server-side.
224    async fn restart(&self) -> Result<(), CoreError>;
225    /// POST `/data/api/v1/scan/projects` (authed) — the harmless
226    /// project-rescan write probe (`ign doctor --check-write`; 2xx =
227    /// write permission, 403 = read-only token).
228    async fn scan_projects(&self) -> Result<(), CoreError>;
229    /// GET `/data/api/v1/resources/ignition/security-properties`
230    /// (authed) — the security config singleton; the doctor's
231    /// permissions deep-dive surfaces `readPermissions`/
232    /// `writePermissions` verbatim (passthrough shape).
233    async fn security_properties(&self) -> Result<SecurityProperties, CoreError>;
234    /// GET `/system/webdev/<route>` (authed) reporting the RAW HTTP
235    /// status — the doctor's route-presence probe (404 = absent;
236    /// 200/401/403 = exists). Deliberately NOT classified: presence
237    /// IS the answer; only transport failures are errors.
238    async fn webdev_route_status(&self, route: &str) -> Result<u16, CoreError>;
239    /// POST `/system/webdev/{project}/cli/{route}` (authed + any
240    /// caller headers — scriptExec's secret gate) with the action
241    /// JSON. classify() runs for transport/status errors, BUT the
242    /// 200 BODY is the route envelope `{ok, data|error}` — WebDev
243    /// IGNORES `status`, so denials ride HTTP 200: `ok:false` maps
244    /// `error.code` onto the taxonomy (05-03), `ok:true` returns
245    /// `data`. HTTP 200 alone is NEVER a success verdict.
246    async fn webdev_route_call(
247        &self,
248        project: &str,
249        route: &str,
250        body: &serde_json::Value,
251        extra_headers: &[(&str, &str)],
252    ) -> Result<serde_json::Value, CoreError>;
253    /// POST the route action with a PER-REQUEST timeout override —
254    /// the large-payload escape hatch (the `get_bytes`
255    /// `RequestBuilder::timeout` pattern, 02-04/09-05): the 30 s
256    /// client default would truncate the Phase-11 bulk exportTags
257    /// transfer (research Pitfall 6), so the bulk arms override with
258    /// [`crate::client::tags::TAGS_EXPORT_TIMEOUT`]. Default body =
259    /// the plain call — test doubles and any impl without an
260    /// override path ride the client default (the override only
261    /// lengthens the ceiling; request/response semantics are the
262    /// same classify + envelope parse).
263    async fn webdev_route_call_with_timeout(
264        &self,
265        project: &str,
266        route: &str,
267        body: &serde_json::Value,
268        extra_headers: &[(&str, &str)],
269        _timeout: Duration,
270    ) -> Result<serde_json::Value, CoreError> {
271        self.webdev_route_call(project, route, body, extra_headers)
272            .await
273    }
274    /// POST the route's `{"action":"version"}` handshake and
275    /// discriminate ([`webdev::RouteProbe`]): 200-body-ok →
276    /// `Present{route_version}`, 405 → `Absent` (the live-proven 8.3
277    /// marker — NOT 404), 402 → `Unlicensed`, 401/403 → `AuthGated`,
278    /// 200-body-denial → `Denied{code,message}`. Deliberately NOT
279    /// classified — the status code IS the answer (the
280    /// `webdev_route_status` precedent); only transport failures and
281    /// shapes the enum has no variant for (wizard redirects, 503
282    /// restarts, foreign 404s) are errors.
283    async fn webdev_route_probe(
284        &self,
285        project: &str,
286        route: &str,
287        extra_headers: &[(&str, &str)],
288    ) -> Result<RouteProbe, CoreError>;
289    /// GET `/data/api/v1/projects/list` (authed) — every RUNNABLE
290    /// project with inheritance info from the items themselves
291    /// (PROJ-01; standard list params, `limit=-1` UI convention).
292    async fn projects(
293        &self,
294        query: &query::ListQuery,
295    ) -> Result<ListEnvelope<ProjectRecord>, CoreError>;
296    /// GET `/data/api/v1/projects/find/{name}` (authed, name
297    /// percent-encoded per segment) — one project's full record; 404 →
298    /// `NotFound` via classify (this doubles as 03-02's collision
299    /// pre-check).
300    async fn project_find(&self, name: &str) -> Result<ProjectRecord, CoreError>;
301    /// POST `/data/api/v1/projects` (authed, JSON body) — create. Ok
302    /// classification IS the success contract (create's response body
303    /// is unverified LOW — the restart `literal true` precedent;
304    /// callers that want data re-`find`). Audit-logged server-side.
305    async fn project_create(&self, body: &ProjectCreate) -> Result<(), CoreError>;
306    /// POST `/data/api/v1/projects/copy` (authed, body exactly
307    /// `{"fromName":…,"toName":…}`) — an exact copy of all resources.
308    /// Audit-logged server-side.
309    async fn project_copy(&self, from: &str, to: &str) -> Result<(), CoreError>;
310    /// POST `/data/api/v1/projects/rename/{name}` (authed, body
311    /// `{"name": "<new>"}`) — native rename, NOT copy+delete.
312    /// Audit-logged server-side.
313    async fn project_rename(&self, name: &str, new_name: &str) -> Result<(), CoreError>;
314    /// PUT `/data/api/v1/projects/{name}` (authed, JSON body WITHOUT
315    /// `name`) — modify/reparent (`set --parent` IS the inheritance
316    /// move). Audit-logged server-side.
317    async fn project_modify(&self, name: &str, body: &ProjectModify) -> Result<(), CoreError>;
318    /// DELETE `/data/api/v1/projects/{name}?confirm=true` (authed,
319    /// empty body) — the server's own confirmation guard rides the
320    /// QUERY string (Pitfall 8: BOTH layers, always — the CLI's
321    /// `--yes` and the wire's `confirm=true`). Audit-logged
322    /// server-side.
323    async fn project_delete(&self, name: &str) -> Result<(), CoreError>;
324    /// GET `/data/api/v1/projects/export/{name}` (authed, per-request
325    /// [`projects::PROJECT_EXPORT_TIMEOUT`] = 120 s) — the project ZIP
326    /// STREAMED to `out` chunk-by-chunk via `bytes_stream` (Pitfall 2:
327    /// NO `Vec<u8>` accumulation anywhere), with the disposition
328    /// filename + byte count in the meta. Audit-relevant only as a
329    /// read (exports never mutate).
330    async fn project_export_to_file(&self, name: &str, out: &Path)
331    -> Result<ExportMeta, CoreError>;
332    /// POST `/data/api/v1/projects/import/{name}?overwrite=<bool>`
333    /// (authed, per-request [`projects::PROJECT_IMPORT_TIMEOUT`] =
334    /// 300 s) — the ZIP as the RAW body with `Content-Type:
335    /// application/zip` and a known `Content-Length` (a `Vec<u8>`
336    /// sidesteps the chunked-encoding question entirely — Pitfall 3's
337    /// timeout is handled by the override). Synchronous, no job IDs
338    /// (verified). Audit-logged server-side.
339    async fn project_import(
340        &self,
341        name: &str,
342        zip: Vec<u8>,
343        overwrite: bool,
344    ) -> Result<ImportOutcome, CoreError>;
345    /// GET `/data/api/v1/resources/list/ignition/tag-provider`
346    /// (authed) — the tag-provider resource list: full records
347    /// incl. `config`, `metrics.tagCount`, `healthchecks.status`
348    /// (05-04, TAGS-01 — the NATIVE provider seam; no deployed
349    /// route involved). Standard list params (limit=-1, the UI
350    /// convention).
351    async fn tag_provider_list(
352        &self,
353        query: &query::ListQuery,
354    ) -> Result<ListEnvelope<TagProviderRecord>, CoreError>;
355    /// GET `/data/api/v1/tags/export?provider=<P>&type=json` (authed,
356    /// per-request [`tags::TAGS_EXPORT_TIMEOUT`] = 300 s) — the native
357    /// export of one provider's whole tag tree, as the gateway's own
358    /// bytes. Read-only; `provider` rides the query, never the path.
359    /// The default body goes through [`Self::api_call`] (the
360    /// `webdev_route_call_with_timeout` precedent: test doubles and any
361    /// impl without an override ride the client default); the real
362    /// client overrides it with the 300 s ceiling.
363    async fn tags_export_provider(&self, provider: &str) -> Result<Vec<u8>, CoreError> {
364        let call = apicall::ApiCallRequest {
365            method: "GET".to_string(),
366            path: tags::TAGS_EXPORT_PATH.to_string(),
367            body: None,
368            headers: Vec::new(),
369            query: vec![
370                ("provider".to_string(), provider.to_string()),
371                ("type".to_string(), "json".to_string()),
372            ],
373        };
374        let data = self.api_call(&call).await?;
375        Ok(data.data.get().as_bytes().to_vec())
376    }
377    /// GET `/data/api/v1/resources/find/ignition/tag-provider/{name}`
378    /// (authed, name percent-encoded per segment) — one provider's
379    /// full record incl. the `signature` the chained delete needs.
380    /// 404 → `NotFound` via classify.
381    async fn tag_provider_find(&self, name: &str) -> Result<TagProviderRecord, CoreError>;
382    /// POST `/data/api/v1/resources/ignition/tag-provider` (authed)
383    /// with a JSON **ARRAY** body of create records — the
384    /// live-proven create shape (05-RESEARCH provider table).
385    /// Audit-logged server-side.
386    async fn tag_provider_create(&self, body: &[TagProviderCreate]) -> Result<(), CoreError>;
387    /// DELETE `/data/api/v1/resources/ignition/tag-provider/{name}/{signature}`
388    /// (authed, both segments percent-encoded) — delete-by-signature;
389    /// the signature comes from find. Audit-logged server-side.
390    async fn tag_provider_delete(&self, name: &str, signature: &str) -> Result<(), CoreError>;
391    /// GET `/data/api/v1/trial` — the trial state, live-verified
392    /// UNAUTHENTICATED on 8.3.3 + 8.3.6 (both trial states): auth
393    /// headers ride ONLY when the client carries a credential (fresh
394    /// rigs have none — the version-command degradation precedent,
395    /// rig-family edition).
396    async fn trial_status_wire(&self) -> Result<TrialWire, CoreError>;
397    /// GET `/data/api/v1/overview/banners` — the trial cross-check
398    /// (severity/expireTime semantics, Pitfall 7). Same conditional
399    /// auth as [`Self::trial_status_wire`].
400    async fn banners(&self) -> Result<BannerSet, CoreError>;
401    /// POST `/data/api/v1/trial` (authed, empty body) — the trial
402    /// RESET, tier 0 of the ladder: a token credential plausibly
403    /// satisfies it without CSRF (token mutations need none — the
404    /// restart/set-logger precedent). The 2xx body IS the fresh
405    /// [`TrialWire`] (live-observed). NOTE (live-discovered state
406    /// gate): the gateway 403s resets on a NON-expired trial — the
407    /// action layer pre-checks expiry.
408    async fn trial_reset_wire(&self) -> Result<TrialWire, CoreError>;
409    /// GET `/data/api/v1/backup?type={roaming|all}` (authed,
410    /// [`backup::BACKUP_TIMEOUT`] = 300 s, `Accept:
411    /// application/octet-stream`) — the portable gwbk STREAMED to
412    /// `out` chunk-by-chunk through the 03-02 `download_to_file`
413    /// pipeline (the ONE streaming body-consumption site — never a
414    /// `Vec<u8>`, Pitfall 2). Byte count + metadata ride out in
415    /// [`ExportMeta`] (04-04, RIG-04; 07-02 param-ized the type —
416    /// `Roaming` stays the caller default).
417    async fn backup_download(
418        &self,
419        out: &Path,
420        backup_type: backup::BackupType,
421    ) -> Result<ExportMeta, CoreError>;
422    /// POST `/data/api/v1/backup` (authed, [`backup::BACKUP_TIMEOUT`]
423    /// = 300 s) — the RESTORE: the gwbk bytes as a RAW
424    /// `application/octet-stream` body (NOT multipart — the postman
425    /// collection's exact shape) with the four scope params EXPLICIT
426    /// on the query string. Synchronous AND followed by a gateway
427    /// restart (Pitfall 6): the 2xx means the restore was ACCEPTED —
428    /// the actions layer owns the post-restore RUNNING wait. The
429    /// upload direction buffers by design (the import precedent).
430    async fn backup_restore(&self, gwbk: &Path) -> Result<(), CoreError>;
431    /// GET `/data/eam/api/v1/eam-tasks/history` (authed) — task run
432    /// history, the standard `{items, metadata}` envelope. `limit`
433    /// defaults to [`eam::EAM_HISTORY_DEFAULT_LIMIT`] (200 — EAM
434    /// history grows unboundedly; an explicit limit ALWAYS rides the
435    /// wire, the logs discipline). A stock (non-controller) gateway
436    /// 403s → [`CoreError::EamNotController`] via classify
437    /// (path-scoped message classification — never a misleading
438    /// `auth_rejected`).
439    async fn eam_task_history(
440        &self,
441        limit: Option<u32>,
442        search: Option<&str>,
443    ) -> Result<ListEnvelope<EamHistoryItem>, CoreError>;
444    /// GET `/data/api/v1/resources/list/com.inductiveautomation.eam/
445    /// eam-tasks` (authed) — task DEFINITIONS through the standard
446    /// config-resource family (the tag-provider pattern; available
447    /// on stock gateways — no controller needed for definitions).
448    async fn eam_task_definitions(&self) -> Result<ListEnvelope<EamTaskRecord>, CoreError>;
449    /// GET `/data/api/v1/resources/find/com.inductiveautomation.eam/
450    /// eam-tasks/{name}` (authed) — one definition's full record
451    /// incl. the `scheduledTaskState` healthcheck
452    /// (`currentState`/`nextScheduled`/`owner` under `details`) and
453    /// the mutation `signature`. 404 → `NotFound` via classify.
454    async fn eam_task_find(&self, name: &str) -> Result<EamTaskRecord, CoreError>;
455    /// POST `/data/api/v1/resources/com.inductiveautomation.eam/
456    /// eam-tasks` (authed) with a JSON **ARRAY** body of one
457    /// definition record — the config-resource create shape (the
458    /// tag-provider precedent). Ok classification IS the success
459    /// contract (create's response body is unverified — the
460    /// project-create precedent; callers that want data re-find).
461    /// Audit-logged server-side.
462    async fn eam_task_create(&self, definition: &serde_json::Value) -> Result<(), CoreError>;
463    /// POST `/data/eam/api/v1/eam-tasks/force/{owner}/{name}` (authed,
464    /// empty body) — dispatch a task NOW. Live-proven success shape:
465    /// **204** (any 2xx is done — the route-status style; execution
466    /// OUTCOMES surface later in history as data, never on this
467    /// response). Runtime seam: the controller gate classifies.
468    async fn eam_task_force(&self, owner: &str, name: &str) -> Result<(), CoreError>;
469    /// POST `/data/eam/api/v1/eam-tasks/suspend/{name}` (authed,
470    /// empty body) — suspend the task's scheduler trigger.
471    /// Live-proven success shape: **204**; the flag PERSISTS into
472    /// `config.profile.isSuspended` (10-LIVE-CAPTURES §1c/Decision 1).
473    /// Requires a live scheduler trigger — an OnDemand/untriggered
474    /// (or unknown-named, §7) task answers 500 Jetty HTML, which
475    /// classifies as `Internal` with the page's own message (no
476    /// honest 404 exists on this seam).
477    async fn eam_task_suspend(&self, name: &str) -> Result<(), CoreError>;
478    /// POST `/data/eam/api/v1/eam-tasks/resume/{name}` (authed,
479    /// empty body) — the inverse of [`Self::eam_task_suspend`]:
480    /// **204** success, `isSuspended` back to `false` (§1d). Unknown
481    /// names answer 500 HTML naming the task (§7).
482    async fn eam_task_resume(&self, name: &str) -> Result<(), CoreError>;
483    /// POST `/data/eam/api/v1/eam-tasks/cancel/{name}` (authed,
484    /// empty body) — cancel a PENDING execution. Always **204** on
485    /// the captured shapes: nothing-pending AND unknown-name are
486    /// silent successes (§7) — cancel is never a name-validation
487    /// tool (the actions layer owns find-before-write).
488    async fn eam_task_cancel(&self, name: &str) -> Result<(), CoreError>;
489    /// GET `/data/eam/api/v1/eam-tasks/scheduled/{running}` (authed)
490    /// — the pending-execution read; `{running}` is the LITERAL word
491    /// `true`/`false` (§2). Answers the standard
492    /// `{items, metadata}` envelope; this method unwraps it to the
493    /// items ([`EamScheduledTask`] — 13 capture-locked keys,
494    /// `taskState` String vocabulary). A stock gateway 403s →
495    /// [`CoreError::EamNotController`] via the same path-scoped arm
496    /// as every runtime seam call.
497    async fn eam_tasks_scheduled(&self, running: bool) -> Result<Vec<EamScheduledTask>, CoreError>;
498    /// PUT `/data/api/v1/resources/com.inductiveautomation.eam/
499    /// eam-tasks` (authed) with a single-element JSON **ARRAY**
500    /// carrying the FULL find record (settings included — omitting
501    /// `config.settings` ⇒ 422, the create trap) and the ORIGINAL
502    /// `signature`. The 200 body is the captured
503    /// [`ModifyOutcome`] `{success, changes[], problem}`
504    /// (§6a); `None` = a 2xx with an empty body (lenient). Rename via
505    /// PUT is NOT supported (§5: changed name + original signature ⇒
506    /// 404 — the actions layer must compose create-new + delete-old).
507    async fn eam_task_modify(
508        &self,
509        definition: &serde_json::Value,
510    ) -> Result<Option<ModifyOutcome>, CoreError>;
511    /// DELETE `/data/api/v1/resources/com.inductiveautomation.eam/
512    /// eam-tasks/{name}/{signature}` (authed, both segments
513    /// percent-encoded) with `?collection=core` ALWAYS (the
514    /// collection VALUE — `collection=eam-tasks` 404s, §3c) and
515    /// `confirm=true` only when the caller opts in: a lone-resource
516    /// delete SUCCEEDS without it (§3b) and the confirm-demand shape
517    /// is UNOBSERVED (§3d) — never hard-coded. The 200 body is the
518    /// captured [`DeleteOutcome`] (adds `references`). A signature
519    /// mismatch answers HTTP 500 + `problem` — see the
520    /// [`eam`] module docs for the recorded FINDING (not classified
521    /// here; slug decision belongs to 10-03/10-04).
522    async fn eam_task_delete(
523        &self,
524        name: &str,
525        signature: &str,
526        confirm: bool,
527    ) -> Result<DeleteOutcome, CoreError>;
528    /// The raw passthrough (09-03, EXT-01): send `call` with its
529    /// arbitrary method, caller headers, query pairs, and optional raw
530    /// body (ANY method — GET/DELETE bodies allowed, curl parity).
531    /// Auth rides [`ReqwestGatewayApi::apply_auth`] (the ONE
532    /// `Secret::expose` site — user auth-pattern headers are refused
533    /// by [`apicall::refuse_auth_headers`] at the CLI/action layer,
534    /// never stripped); classification rides the api-call pipeline
535    /// ([`ReqwestGatewayApi::send_and_classify_for_api`]), so an
536    /// unclassified gateway 4xx is `GatewayClientError` (exit 2,
537    /// verbatim capped body). The 2xx body returns VERBATIM
538    /// ([`apicall::ApiCallData`] — `RawValue` passthrough: no field
539    /// dropped, no value coerced, key order preserved); a non-JSON
540    /// 2xx body is the honest internal-class refusal. The usage
541    /// guards live in [`apicall`] and the action layer — BOTH run
542    /// them, so in-process callers cannot skip the checks.
543    async fn api_call(
544        &self,
545        call: &apicall::ApiCallRequest,
546    ) -> Result<apicall::ApiCallData, CoreError>;
547    /// GET `/data/api/v1/licenses` (authed) — the license inventory
548    /// (09-04). The wire model is PARTIAL-CURATED: the morning-check
549    /// skeleton typed, array elements + `details` passthrough (the
550    /// fresh-rig captures answered empty arrays — element shapes are
551    /// not capture-proven).
552    async fn license_status(&self) -> Result<LicenseStatusWire, CoreError>;
553    /// GET `/data/api/v1/redundancy` (authed) — the flat 11-field
554    /// redundancy status (09-04). Units are capture-locked at the
555    /// model (`uptime` ms-since-start wall-clock-proven; the
556    /// `lastSyncTimestamp` `-1` sentinel normalized via
557    /// [`redundancy::RedundancyStatusWire::last_sync_epoch_ms`]).
558    async fn redundancy_status(&self) -> Result<RedundancyStatusWire, CoreError>;
559    /// GET `/data/api/v1/overview/gan` (authed) — the 5-field GAN
560    /// summary (09-04); a non-GAN gateway's zero-connection body IS
561    /// the canonical capture.
562    async fn gan_status(&self) -> Result<GanStatusWire, CoreError>;
563    /// POST `/data/api/v1/diagnostics/bundle/generate` (authed, no
564    /// body) — start bundle generation (09-05). The 200 body IS the
565    /// fresh [`BundleStatusWire`] (live capture:
566    /// `{"state":"Generating"}`). Audit-logged server-side.
567    async fn bundle_generate(&self) -> Result<BundleStatusWire, CoreError>;
568    /// GET `/data/api/v1/diagnostics/bundle/status` (authed) — the
569    /// status poll: captured state vocabulary + `fileSize` (bytes,
570    /// absent while generating — 09-LIVE-CAPTURES §5).
571    async fn bundle_status(&self) -> Result<BundleStatusWire, CoreError>;
572    /// GET `/data/api/v1/diagnostics/bundle/download` (authed,
573    /// per-request [`diagnostics::BUNDLE_DOWNLOAD_TIMEOUT`] = 300 s —
574    /// Pitfall 8: the 30 s client default would truncate MB-sized
575    /// bundles) — the ZIP STREAMED to `out` chunk-by-chunk through the
576    /// `download_to_file` pipeline (classify-first; NO `Vec<u8>`
577    /// anywhere). The `Content-Disposition` filename + `Content-Type`
578    /// ride the pipeline's [`ExportMeta`].
579    async fn bundle_download(&self, out: &Path) -> Result<ExportMeta, CoreError>;
580}
581
582/// Production [`GatewayApi`] over reqwest.
583pub struct ReqwestGatewayApi {
584    base: url::Url,
585    credential: Option<Credential>,
586    client: reqwest::Client,
587}
588
589impl ReqwestGatewayApi {
590    /// Build from a resolved profile (post env-overlay — the dispatch site
591    /// owns that precedence) and an optional credential (`None` = proceed
592    /// header-less; the gateway's answer is then classified — 401 under
593    /// 8.3 default security).
594    ///
595    /// Timeouts: 10s connect / 30s overall (per-class refinements land in
596    /// Phase 2). `ssl_verify = false` accepts invalid certs — dev-rig
597    /// only, per-profile, never global.
598    pub fn new(profile: &Profile, credential: Option<Credential>) -> Result<Self, CoreError> {
599        let client = build_client(profile.ssl_verify)?;
600        Ok(Self {
601            base: profile.url.clone(),
602            credential,
603            client,
604        })
605    }
606
607    /// Test constructor: base URL + credential, no profile needed.
608    pub fn for_tests(base_url: &str, credential: Option<Credential>) -> Self {
609        Self {
610            base: url::Url::parse(base_url).expect("test base URL parses"),
611            credential,
612            client: build_client(true).expect("test client builds"),
613        }
614    }
615
616    /// The full request URL for `path` (bases are normalized to a trailing
617    /// slash; an absolute path replaces from root).
618    fn url_for(&self, path: &str) -> url::Url {
619        self.base.join(path).expect("base joins an absolute path")
620    }
621
622    /// The auth-header rule in ONE place: token XOR basic XOR neither — a
623    /// match, not if/if-else chains. [`Secret::expose`] is called at
624    /// exactly this site (the redaction boundary MOVED here in 02-01, not
625    /// duplicated).
626    ///
627    /// Basic carries a loud demotion warning: it cannot authenticate 8.3
628    /// `/data` routes (verified: valid commissioned credentials → 401) —
629    /// warn once per call, never silently retry (02-RESEARCH Auth §2).
630    fn apply_auth(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
631        let mut request = request;
632        match &self.credential {
633            Some(Credential::Token(token)) => {
634                request = request.header("X-Ignition-API-Token", token.expose());
635            }
636            Some(Credential::Basic(user, password)) => {
637                tracing::warn!(
638                    "Basic auth does not authenticate Ignition 8.3 /data routes \
639                     (verified: valid credentials → 401); use an API token"
640                );
641                request = request.basic_auth(user.expose(), Some(password.expose()));
642            }
643            None => {}
644        }
645        request
646    }
647
648    /// GET `path` (with pre-built query `pairs` when given) → classify →
649    /// deserialize into `T`. `auth = false` fetches header-less (the
650    /// `/StatusPing` readiness probe, 02-02 — it must work with broken
651    /// credentials). Callers build pairs via `to_query_pairs()` so the
652    /// param-name mapping stays in the capability files.
653    async fn get_json<T: serde::de::DeserializeOwned>(
654        &self,
655        path: &str,
656        pairs: Option<&[(String, String)]>,
657        auth: bool,
658    ) -> Result<T, CoreError> {
659        let url = self.url_for(path);
660        let mut request = self.client.get(url.clone());
661        if let Some(pairs) = pairs {
662            request = request.query(&pairs);
663        }
664        if auth {
665            request = self.apply_auth(request);
666        }
667        let response = self.send_and_classify(request, &url).await?;
668        response.json::<T>().await.map_err(|err| {
669            CoreError::Internal(format!(
670                "response from {url} did not match the expected shape: {err}"
671            ))
672        })
673    }
674
675    /// GET `path` → classify → read the response as BYTES plus the
676    /// `Content-Disposition` filename and `Content-Type` — the
677    /// archive-download pipeline (02-04). `timeout` overrides the 30 s
678    /// client default PER REQUEST (a large `.idb` archive must not be
679    /// truncated) — `RequestBuilder::timeout`, not a second client.
680    async fn get_bytes(&self, path: &str, timeout: Duration) -> Result<LogDownload, CoreError> {
681        let url = self.url_for(path);
682        let request = self.client.get(url.clone()).timeout(timeout);
683        let request = self.apply_auth(request);
684        let response = self.send_and_classify(request, &url).await?;
685        let filename = response
686            .headers()
687            .get(reqwest::header::CONTENT_DISPOSITION)
688            .and_then(|value| value.to_str().ok())
689            .and_then(logs::filename_from_content_disposition);
690        let content_type = response
691            .headers()
692            .get(reqwest::header::CONTENT_TYPE)
693            .and_then(|value| value.to_str().ok())
694            .map(str::to_string);
695        let bytes = response.bytes().await.map_err(|err| CoreError::Network {
696            url: url.to_string(),
697            source: Some(err),
698            observation: None,
699        })?;
700        Ok(LogDownload {
701            bytes: bytes.to_vec(),
702            filename,
703            content_type,
704        })
705    }
706
707    /// GET `path` → classify → STREAM the body to `out` chunk-by-chunk
708    /// — the file-download pipeline (03-02). The response body is
709    /// consumed HERE, at a pipeline site, classify-first like every
710    /// other: an error answer must classify (never stream), and on
711    /// success each `bytes_stream()` chunk goes straight through
712    /// `AsyncWriteExt::write_all` into a `tokio::fs::File` — NO
713    /// `Vec<u8>` accumulation anywhere (Pitfall 2: a multi-hundred-MB
714    /// export ZIP must not buffer in memory). The response metadata
715    /// (`Content-Disposition` filename, `Content-Type`) and the
716    /// chunk-counted byte total ride out in [`ExportMeta`]. Requires
717    /// the workspace `reqwest` `stream` + `tokio` `fs` features (the
718    /// research-flagged dep gap this plan closed).
719    ///
720    /// `accept` adds an OPTIONAL `Accept` header for the callers whose
721    /// server contract names one (04-04's gwbk download sends
722    /// `application/octet-stream`; the 03-02 export sends none) — a
723    /// minimal parameterization that keeps THIS the one streaming
724    /// site instead of forking a second copy of the chunk loop.
725    async fn download_to_file(
726        &self,
727        path: &str,
728        out: &Path,
729        timeout: Duration,
730        accept: Option<&str>,
731    ) -> Result<ExportMeta, CoreError> {
732        use futures_util::StreamExt;
733        use tokio::io::AsyncWriteExt;
734
735        let url = self.url_for(path);
736        let mut request = self.client.get(url.clone()).timeout(timeout);
737        if let Some(accept) = accept {
738            request = request.header(reqwest::header::ACCEPT, accept);
739        }
740        let request = self.apply_auth(request);
741        let response = self.send_and_classify(request, &url).await?;
742        let filename = response
743            .headers()
744            .get(reqwest::header::CONTENT_DISPOSITION)
745            .and_then(|value| value.to_str().ok())
746            .and_then(logs::filename_from_content_disposition);
747        let content_type = response
748            .headers()
749            .get(reqwest::header::CONTENT_TYPE)
750            .and_then(|value| value.to_str().ok())
751            .map(str::to_string);
752
753        let mut file = tokio::fs::File::create(out).await.map_err(|err| {
754            CoreError::Internal(format!("cannot create {}: {err}", out.display()))
755        })?;
756        let mut stream = response.bytes_stream();
757        let mut bytes: u64 = 0;
758        while let Some(chunk) = stream.next().await {
759            let chunk = chunk.map_err(|err| CoreError::Network {
760                url: url.to_string(),
761                source: Some(err),
762                observation: None,
763            })?;
764            file.write_all(&chunk).await.map_err(|err| {
765                CoreError::Internal(format!("cannot write {}: {err}", out.display()))
766            })?;
767            bytes += chunk.len() as u64;
768        }
769        file.flush()
770            .await
771            .map_err(|err| CoreError::Internal(format!("cannot flush {}: {err}", out.display())))?;
772        Ok(ExportMeta {
773            filename,
774            bytes,
775            content_type,
776        })
777    }
778
779    /// POST `path` with `pairs` as QUERY params and an empty body →
780    /// classify → hand back the response (callers read `true`/JSON as
781    /// their capability needs). Production callers since 02-04:
782    /// `set_logger_level`, `reset_logger_levels` (and 02-05's restart
783    /// with `confirm=true`). Token-auth POSTs need NO CSRF (verified
784    /// 02-RESEARCH §Auth Model).
785    async fn post_empty(
786        &self,
787        path: &str,
788        pairs: &[(&str, String)],
789        auth: bool,
790    ) -> Result<reqwest::Response, CoreError> {
791        let url = self.url_for(path);
792        let mut request = self.client.post(url.clone()).query(pairs);
793        if auth {
794            request = self.apply_auth(request);
795        }
796        self.send_and_classify(request, &url).await
797    }
798
799    /// DELETE `path` with `pairs` as QUERY params (empty body) →
800    /// classify → `Ok(())` on any classified success. Token-auth DELETEs
801    /// need NO CSRF (verified 02-RESEARCH §Auth Model: CSRF is only for
802    /// cookie/session auth); the classified bodies (`{terminated: N}`,
803    /// `{message: …}`) are advisory — Ok classification IS the success
804    /// contract.
805    async fn delete_with_query(
806        &self,
807        path: &str,
808        pairs: &[(&str, String)],
809    ) -> Result<(), CoreError> {
810        let url = self.url_for(path);
811        let mut request = self.client.delete(url.clone()).query(pairs);
812        request = self.apply_auth(request);
813        self.send_and_classify(request, &url).await.map(|_| ())
814    }
815
816    /// DELETE `path` with a JSON body → classify → hand back the
817    /// response — [`Self::delete_with_query`] cannot carry a body (it
818    /// sends an EMPTY one). Mirrors [`Self::post_json`] exactly (Phase
819    /// 19: the module-uninstall DELETE is the first DELETE-with-body
820    /// caller). Token-auth DELETEs need NO CSRF (verified 02-RESEARCH
821    /// §Auth Model).
822    async fn delete_json<T: serde::Serialize + ?Sized>(
823        &self,
824        path: &str,
825        body: &T,
826    ) -> Result<reqwest::Response, CoreError> {
827        let url = self.url_for(path);
828        let request = self.apply_auth(self.client.delete(url.clone()).json(body));
829        self.send_and_classify(request, &url).await
830    }
831
832    /// POST `path` with a JSON body → classify → hand back the response
833    /// (callers read the body as their capability needs; the project
834    /// mutations treat Ok classification AS the success contract —
835    /// those bodies are unverified LOW, the restart `literal true`
836    /// precedent). Token-auth POSTs need NO CSRF (verified
837    /// 02-RESEARCH §Auth Model). One of the two body-carrying pipeline
838    /// helpers (03-01); serde serializes struct fields in declaration order, so
839    /// recorded bodies are deterministic for the wiremock pins.
840    async fn post_json<T: serde::Serialize + ?Sized>(
841        &self,
842        path: &str,
843        body: &T,
844    ) -> Result<reqwest::Response, CoreError> {
845        let url = self.url_for(path);
846        let request = self.apply_auth(self.client.post(url.clone()).json(body));
847        self.send_and_classify(request, &url).await
848    }
849
850    /// POST the action JSON to a webdev route with caller headers +
851    /// auth applied, returning `(full URL, response)` — the shared
852    /// head of the two webdev seam methods (05-03). NO classify here:
853    /// `webdev_route_probe` reads the raw status (the code IS the
854    /// answer); `webdev_route_call` classifies downstream. Transport
855    /// failures map to `Network` like every pipeline.
856    async fn webdev_post_raw(
857        &self,
858        project: &str,
859        route: &str,
860        body: &serde_json::Value,
861        extra_headers: &[(&str, &str)],
862        timeout: Option<Duration>,
863    ) -> Result<(String, reqwest::Response), CoreError> {
864        let path = webdev::route_url(project, route);
865        let url = self.url_for(&path);
866        let mut request = self.client.post(url.clone()).json(body);
867        if let Some(t) = timeout {
868            // Per-request override WITHOUT a second client — the
869            // RequestBuilder::timeout pattern (02-04/09-05).
870            request = request.timeout(t);
871        }
872        for (name, value) in extra_headers {
873            request = request.header(*name, *value);
874        }
875        let request = self.apply_auth(request);
876        let response = request.send().await.map_err(|err| CoreError::Network {
877            url: url.to_string(),
878            source: Some(err),
879            observation: None,
880        })?;
881        Ok((url.to_string(), response))
882    }
883
884    /// POST the JSON body to a TESTING-bundle route
885    /// (`/system/webdev/{project}/testing/{route}`) RAW — the
886    /// `webdev_post_raw` twin for the sibling URL space (QUICK-p0g).
887    ///
888    /// NO classify, deliberately (the `webdev_route_probe`
889    /// precedent): the testing bundle's presence discrimination
890    /// needs the raw status, because [`classify`] collapses
891    /// 405/500/501 into `Internal` (exit 1) and would make an
892    /// undeployed bundle indistinguishable from a CLI bug. Transport
893    /// failures map to `Network` like every pipeline.
894    ///
895    /// The classified siblings ([`webdev::testing_discover`],
896    /// [`webdev::testing_run`]) are untouched — `ign adopt --testing`
897    /// keeps its exact behavior.
898    pub(crate) async fn testing_post_raw(
899        &self,
900        project: &str,
901        route: &str,
902        body: &serde_json::Value,
903    ) -> Result<(String, reqwest::Response), CoreError> {
904        let path = webdev::testing_route_url(project, route);
905        let url = self.url_for(&path);
906        let request = self.apply_auth(self.client.post(url.clone()).json(body));
907        let response = request.send().await.map_err(|err| CoreError::Network {
908            url: url.to_string(),
909            source: Some(err),
910            observation: None,
911        })?;
912        Ok((url.to_string(), response))
913    }
914
915    /// PUT `path` with a JSON body → classify → `Ok(())` (modify/
916    /// reparent; resource puts in 03-03). Token-auth PUTs need NO
917    /// CSRF. The classify-first rule holds: nothing consumes a body
918    /// that skipped classify.
919    async fn put_json<T: serde::Serialize + ?Sized>(
920        &self,
921        path: &str,
922        body: &T,
923    ) -> Result<(), CoreError> {
924        let url = self.url_for(path);
925        let request = self.apply_auth(self.client.put(url.clone()).json(body));
926        self.send_and_classify(request, &url).await.map(|_| ())
927    }
928
929    /// Send + transport-error mapping + [`classify`] — the shared tail of
930    /// every pipeline helper. Transport failures (connect/timeout/TLS) →
931    /// `Network` (exit 4); everything the gateway ANSWERED goes through
932    /// the classifier. Curated traffic: `api_call = false` — the
933    /// catch-all cannot fire without the parameter (09-01 Pitfall 1).
934    async fn send_and_classify(
935        &self,
936        request: reqwest::RequestBuilder,
937        url: &url::Url,
938    ) -> Result<reqwest::Response, CoreError> {
939        let response = request.send().await.map_err(|err| CoreError::Network {
940            url: url.to_string(),
941            source: Some(err),
942            observation: None,
943        })?;
944        classify::classify(response, url.as_ref(), false).await
945    }
946
947    /// The api-call-scoped pipeline entry (09-01): identical
948    /// transport-error → `Network` mapping, then [`classify`] with
949    /// `api_call = true` so an unclassified gateway 4xx maps to
950    /// `GatewayClientError` (exit 2, verbatim capped body) instead of
951    /// `Internal`. Public because `ign api call`'s action layer (09-03)
952    /// is the production consumer and the contract tests
953    /// (tests/api_classify_contract.rs) pin the full exit partition
954    /// through it — nothing in the curated pipeline switches to it.
955    pub async fn send_and_classify_for_api(
956        &self,
957        request: reqwest::RequestBuilder,
958        url: &url::Url,
959    ) -> Result<reqwest::Response, CoreError> {
960        let response = request.send().await.map_err(|err| CoreError::Network {
961            url: url.to_string(),
962            source: Some(err),
963            observation: None,
964        })?;
965        classify::classify(response, url.as_ref(), true).await
966    }
967}
968
969/// Install the process-wide TLS crypto provider (ring). reqwest is built
970/// with `rustls-no-provider` (workspace Cargo.toml) so the provider is the
971/// app's responsibility — this is the single install point for the binary,
972/// and it is `pub` so the e2e tests' raw `reqwest::Client` constructions
973/// can install it too. Safe to call any number of times.
974pub fn install_crypto_provider() {
975    // ring is the process-wide TLS provider (workspace Cargo.toml: reqwest
976    // rides rustls-no-provider). install_default() errors on a second call —
977    // the Once makes every later construction a no-op instead.
978    static ONCE: std::sync::Once = std::sync::Once::new();
979    ONCE.call_once(|| {
980        let _ = rustls::crypto::ring::default_provider().install_default();
981    });
982}
983
984fn build_client(ssl_verify: bool) -> Result<reqwest::Client, CoreError> {
985    install_crypto_provider();
986    let mut builder = reqwest::Client::builder()
987        // Never follow redirects: an uncommissioned gateway 302s everything
988        // to /welcome and the follow would render the wizard HTML as a 200
989        // (02-RESEARCH Pitfall 6). classify() maps the 3xx instead.
990        .redirect(reqwest::redirect::Policy::none())
991        .connect_timeout(Duration::from_secs(10))
992        .timeout(Duration::from_secs(30));
993    if !ssl_verify {
994        builder = builder.danger_accept_invalid_certs(true);
995    }
996    builder
997        .build()
998        .map_err(|err| CoreError::Internal(format!("cannot build HTTP client: {err}")))
999}
1000
1001#[async_trait::async_trait]
1002impl GatewayApi for ReqwestGatewayApi {
1003    async fn gateway_info(&self) -> Result<GatewayInfo, CoreError> {
1004        let mut info: GatewayInfo = self.get_json(GATEWAY_INFO_PATH, None, true).await?;
1005        info.endpoint = Some(self.url_for(GATEWAY_INFO_PATH).to_string());
1006        Ok(info)
1007    }
1008
1009    async fn overview(&self) -> Result<Overview, CoreError> {
1010        self.get_json(status::OVERVIEW_PATH, None, true).await
1011    }
1012
1013    async fn status_ping(&self) -> Result<StatusPing, CoreError> {
1014        // auth = false — the whole point: the readiness anchor must not
1015        // depend on credentials (pinned by the wiremock header-absence
1016        // proof in tests/status_contract.rs).
1017        self.get_json(status::STATUS_PING_PATH, None, false).await
1018    }
1019
1020    async fn modules(
1021        &self,
1022        quarantined: bool,
1023        query: &query::ListQuery,
1024    ) -> Result<ListEnvelope<ModuleInfo>, CoreError> {
1025        let path = if quarantined {
1026            status::MODULES_QUARANTINED_PATH
1027        } else {
1028            status::MODULES_HEALTHY_PATH
1029        };
1030        self.get_json(path, Some(&query.to_query_pairs()), true)
1031            .await
1032    }
1033
1034    async fn uninstall_module(
1035        &self,
1036        gateway_module_id: &str,
1037        module_id: &str,
1038    ) -> Result<(), CoreError> {
1039        let url = self.url_for(status::MODULES_UNINSTALL_PATH);
1040        let body = status::ModuleUninstallRequest {
1041            uninstall: vec![gateway_module_id.to_string()],
1042        };
1043        let response = self
1044            .delete_json(status::MODULES_UNINSTALL_PATH, &body)
1045            .await?;
1046        // Denial-rides-200 (D-19-03, live-verified): a stock module, a
1047        // bogus id, and a still-mounted module all answered 200 with
1048        // success:false. An unparseable body, a missing `success`, or
1049        // an absent `failedUninstalls` must NEVER degrade into a
1050        // reported success — every one of those shapes falls through
1051        // to the denial below, never to `Ok`.
1052        let text = response.text().await.unwrap_or_default();
1053        let denial = |failed: Vec<String>| CoreError::ModuleUninstallDenied {
1054            module_id: module_id.to_string(),
1055            gateway_module_id: gateway_module_id.to_string(),
1056            failed,
1057            endpoint: Some(url.to_string()),
1058        };
1059        let Ok(parsed) = serde_json::from_str::<status::ModuleUninstallResponse>(text.trim())
1060        else {
1061            return Err(denial(vec![gateway_module_id.to_string()]));
1062        };
1063        if parsed.success {
1064            return Ok(());
1065        }
1066        let failed = parsed
1067            .failed_uninstalls
1068            .map(|detail| detail.uninstall)
1069            .filter(|ids| !ids.is_empty())
1070            .unwrap_or_else(|| vec![gateway_module_id.to_string()]);
1071        Err(denial(failed))
1072    }
1073
1074    async fn metrics_current(&self) -> Result<CurrentGauges, CoreError> {
1075        self.get_json(metrics::CURRENT_GAUGES_PATH, None, true)
1076            .await
1077    }
1078
1079    async fn metrics_historic(&self) -> Result<PerformanceCharts, CoreError> {
1080        self.get_json(metrics::CHARTS_PATH, None, true).await
1081    }
1082
1083    async fn metrics_threads(&self) -> Result<ThreadCounts, CoreError> {
1084        self.get_json(metrics::THREADS_PATH, None, true).await
1085    }
1086
1087    async fn thread_dump(&self) -> Result<threads::FormattedThreadDump, CoreError> {
1088        self.get_json(threads::THREAD_DUMP_FORMATTED_PATH, None, true)
1089            .await
1090    }
1091
1092    async fn thread_deadlocks(&self) -> Result<threads::DeadlocksWire, CoreError> {
1093        self.get_json(threads::THREAD_DEADLOCKS_PATH, None, true)
1094            .await
1095    }
1096
1097    async fn designers(
1098        &self,
1099        query: &query::ListQuery,
1100    ) -> Result<ListEnvelope<DesignerInfo>, CoreError> {
1101        self.get_json(
1102            sessions::DESIGNERS_PATH,
1103            Some(&query.to_query_pairs()),
1104            true,
1105        )
1106        .await
1107    }
1108
1109    async fn perspective_sessions(
1110        &self,
1111        query: &query::ListQuery,
1112    ) -> Result<ListEnvelope<PerspectiveSession>, CoreError> {
1113        // The trailing slash is PART OF THE PATH (Pitfall 8) — url_for's
1114        // join preserves it; the exact-path wiremock matcher in
1115        // tests/sessions_contract.rs pins it.
1116        self.get_json(
1117            sessions::PERSPECTIVE_SESSIONS_LIST_PATH,
1118            Some(&query.to_query_pairs()),
1119            true,
1120        )
1121        .await
1122    }
1123
1124    async fn vision_clients(
1125        &self,
1126        query: &query::ListQuery,
1127    ) -> Result<ListEnvelope<VisionClient>, CoreError> {
1128        self.get_json(
1129            sessions::VISION_CLIENTS_PATH,
1130            Some(&query.to_query_pairs()),
1131            true,
1132        )
1133        .await
1134    }
1135
1136    async fn terminate_perspective_session(
1137        &self,
1138        id: &str,
1139        message: Option<&str>,
1140    ) -> Result<(), CoreError> {
1141        // sessionId is a QUERY param on the spec's DELETE route — never
1142        // a body (recorded-request proof in tests/sessions_contract.rs).
1143        let mut pairs = vec![("sessionId", id.to_string())];
1144        if let Some(message) = message {
1145            pairs.push(("message", message.to_string()));
1146        }
1147        self.delete_with_query(sessions::PERSPECTIVE_SESSIONS_TERMINATE_PATH, &pairs)
1148            .await
1149    }
1150
1151    async fn terminate_vision_client(&self, id: &str) -> Result<(), CoreError> {
1152        self.delete_with_query(&sessions::vision_client_terminate_path(id), &[])
1153            .await
1154    }
1155
1156    async fn prune_designer(&self, id: &str) -> Result<(), CoreError> {
1157        self.delete_with_query(&sessions::designer_prune_path(id), &[])
1158            .await
1159    }
1160
1161    async fn database_connections(&self) -> Result<ListEnvelope<GatewayConnection>, CoreError> {
1162        // The UI polls the resource list with limit=-1 — same convention
1163        // as every other list capability.
1164        self.get_json(
1165            connections::DATABASE_CONNECTIONS_PATH,
1166            Some(&query::ListQuery::default().to_query_pairs()),
1167            true,
1168        )
1169        .await
1170    }
1171
1172    async fn opc_connections(&self) -> Result<ListEnvelope<GatewayConnection>, CoreError> {
1173        self.get_json(
1174            connections::OPC_CONNECTIONS_PATH,
1175            Some(&query::ListQuery::default().to_query_pairs()),
1176            true,
1177        )
1178        .await
1179    }
1180
1181    async fn logs(&self, filter: &LogQuery) -> Result<ListEnvelope<LogEntry>, CoreError> {
1182        // Explicit limit ALWAYS rides the wire (Pitfall 9) — enforced by
1183        // LogQuery::to_query_pairs, pinned by the contract test.
1184        self.get_json(logs::LOGS_PATH, Some(&filter.to_query_pairs()), true)
1185            .await
1186    }
1187
1188    async fn logs_download(&self) -> Result<LogDownload, CoreError> {
1189        // Per-request timeout override: the 30 s client default would
1190        // truncate large archives (per-class timeout WITHOUT a second
1191        // client — RequestBuilder::timeout, 02-RESEARCH §Architecture).
1192        self.get_bytes(logs::LOGS_DOWNLOAD_PATH, Duration::from_secs(120))
1193            .await
1194    }
1195
1196    async fn loggers(
1197        &self,
1198        query: &query::ListQuery,
1199    ) -> Result<ListEnvelope<LoggerInfo>, CoreError> {
1200        self.get_json(logs::LOGGERS_PATH, Some(&query.to_query_pairs()), true)
1201            .await
1202    }
1203
1204    async fn set_logger_level(&self, logger: &str, level: &str) -> Result<(), CoreError> {
1205        // `level` rides the QUERY string against an EMPTY body (verified
1206        // live: 200 + the level flips; recorded-request proof in
1207        // tests/logs_contract.rs).
1208        self.post_empty(
1209            &logs::logger_set_path(logger),
1210            &[("level", level.to_string())],
1211            true,
1212        )
1213        .await
1214        .map(|_| ())
1215    }
1216
1217    async fn reset_logger_levels(&self) -> Result<(), CoreError> {
1218        self.post_empty(logs::LEVEL_RESET_PATH, &[], true)
1219            .await
1220            .map(|_| ())
1221    }
1222
1223    async fn restart(&self) -> Result<(), CoreError> {
1224        // `confirm=true` rides the QUERY string against an empty body
1225        // (the verified shape; recorded-request proof in
1226        // tests/restart_wait_contract.rs). Token-auth POSTs need no
1227        // CSRF (02-RESEARCH §Auth Model).
1228        let response = self
1229            .post_empty(
1230                restart::RESTART_PATH,
1231                &[("confirm", "true".to_string())],
1232                true,
1233            )
1234            .await?;
1235        // Success-shape drift guard: the verified body is the literal
1236        // `true`. Any other 2xx body still means the POST was accepted
1237        // — warn, don't fail (the wait half reports what happens next).
1238        let body = response.text().await.unwrap_or_default();
1239        if body.trim() != "true" {
1240            tracing::warn!(
1241                body = %body,
1242                "restart POST answered an unexpected 2xx body (expected the literal `true`)"
1243            );
1244        }
1245        Ok(())
1246    }
1247
1248    async fn scan_projects(&self) -> Result<(), CoreError> {
1249        self.post_empty(restart::SCAN_PROJECTS_PATH, &[], true)
1250            .await
1251            .map(|_| ())
1252    }
1253
1254    async fn security_properties(&self) -> Result<SecurityProperties, CoreError> {
1255        // The singleton READ (ADOPT-RESEARCH §2, live-corrected): the
1256        // record nests the permissions under `config` — deserialize
1257        // from there, tolerating a legacy flat record (config absent
1258        // → the record itself parses).
1259        let record: serde_json::Value = self
1260            .get_json(
1261                restart::SECURITY_PROPERTIES_PATH,
1262                Some(&[("defaultIfUndefined".to_string(), "true".to_string())]),
1263                true,
1264            )
1265            .await?;
1266        let config = record.get("config").cloned().unwrap_or(record);
1267        serde_json::from_value(config).map_err(|err| {
1268            CoreError::Internal(format!(
1269                "security-properties did not match the expected shape: {err}"
1270            ))
1271        })
1272    }
1273
1274    async fn webdev_route_status(&self, route: &str) -> Result<u16, CoreError> {
1275        // The raw-status probe: send, surface the status code, never
1276        // classify (404 vs 200/401/403 is the ANSWER, not an error).
1277        // Only transport failures (DNS/refused/timeout) error out.
1278        let path = restart::webdev_route_path(route);
1279        let url = self.url_for(&path);
1280        let request = self.apply_auth(self.client.get(url.clone()));
1281        let response = request.send().await.map_err(|err| CoreError::Network {
1282            url: url.to_string(),
1283            source: Some(err),
1284            observation: None,
1285        })?;
1286        Ok(response.status().as_u16())
1287    }
1288
1289    async fn webdev_route_call(
1290        &self,
1291        project: &str,
1292        route: &str,
1293        body: &serde_json::Value,
1294        extra_headers: &[(&str, &str)],
1295    ) -> Result<serde_json::Value, CoreError> {
1296        // classify() runs normally for transport/status errors; the
1297        // 200 BODY is then the route envelope — WebDev ignores
1298        // `status`, so denials ride HTTP 200 and the body verdict is
1299        // the ONLY success oracle (never the status line alone).
1300        let (url, response) = self
1301            .webdev_post_raw(project, route, body, extra_headers, None)
1302            .await?;
1303        let response = classify::classify(response, &url, false).await?;
1304        let text = response.text().await.unwrap_or_default();
1305        match webdev::parse_route_body(&text)? {
1306            RouteBody::Ok(data) => Ok(data),
1307            RouteBody::Denied {
1308                code,
1309                message,
1310                traceback,
1311            } => Err(webdev::denial_to_error(
1312                &code,
1313                &message,
1314                traceback.as_deref(),
1315                url,
1316            )),
1317        }
1318    }
1319
1320    async fn webdev_route_call_with_timeout(
1321        &self,
1322        project: &str,
1323        route: &str,
1324        body: &serde_json::Value,
1325        extra_headers: &[(&str, &str)],
1326        timeout: Duration,
1327    ) -> Result<serde_json::Value, CoreError> {
1328        // The SAME classify + envelope-parse tail as
1329        // `webdev_route_call` — the ONLY delta is the per-request
1330        // ceiling (behavior-identical request semantics).
1331        let (url, response) = self
1332            .webdev_post_raw(project, route, body, extra_headers, Some(timeout))
1333            .await?;
1334        let response = classify::classify(response, &url, false).await?;
1335        let text = response.text().await.unwrap_or_default();
1336        match webdev::parse_route_body(&text)? {
1337            RouteBody::Ok(data) => Ok(data),
1338            RouteBody::Denied {
1339                code,
1340                message,
1341                traceback,
1342            } => Err(webdev::denial_to_error(
1343                &code,
1344                &message,
1345                traceback.as_deref(),
1346                url,
1347            )),
1348        }
1349    }
1350
1351    async fn webdev_route_probe(
1352        &self,
1353        project: &str,
1354        route: &str,
1355        extra_headers: &[(&str, &str)],
1356    ) -> Result<RouteProbe, CoreError> {
1357        // NOT classified — the status code IS the answer (the
1358        // webdev_route_status precedent): 405/402/401 discriminate
1359        // presence/licensing/gating, and a 200 body carries the
1360        // version handshake or the structured denial.
1361        let (url, response) = self
1362            .webdev_post_raw(
1363                project,
1364                route,
1365                &serde_json::json!({"action": "version"}),
1366                extra_headers,
1367                None,
1368            )
1369            .await?;
1370        let status = response.status();
1371        if status.is_success() {
1372            let text = response.text().await.unwrap_or_default();
1373            return match webdev::parse_route_body(&text)? {
1374                RouteBody::Ok(data) => {
1375                    let route_version = data
1376                        .get("routeVersion")
1377                        .and_then(serde_json::Value::as_str)
1378                        .map(str::to_string)
1379                        .ok_or_else(|| {
1380                            CoreError::Internal(format!(
1381                                "webdev route version action from {url} answered no routeVersion"
1382                            ))
1383                        })?;
1384                    Ok(RouteProbe::Present { route_version })
1385                }
1386                RouteBody::Denied {
1387                    code,
1388                    message,
1389                    traceback,
1390                } => Ok(RouteProbe::Denied {
1391                    code,
1392                    message,
1393                    traceback,
1394                }),
1395            };
1396        }
1397        match status.as_u16() {
1398            401 | 403 => Ok(RouteProbe::AuthGated),
1399            402 => Ok(RouteProbe::Unlicensed),
1400            405 => Ok(RouteProbe::Absent),
1401            // Shapes the enum has no variant for (wizard redirects,
1402            // mid-restart 503s, foreign 404s) — reuse classify's
1403            // status mappings verbatim; every non-success response
1404            // classifies to Err, and the Ok arm is unreachable by
1405            // construction (all 2xx took the body branch above).
1406            _ => match classify::classify(response, &url, false).await {
1407                Err(err) => Err(err),
1408                Ok(_) => Err(CoreError::Internal(format!(
1409                    "unexpected HTTP {status} from webdev route probe at {url}"
1410                ))),
1411            },
1412        }
1413    }
1414
1415    async fn projects(
1416        &self,
1417        query: &query::ListQuery,
1418    ) -> Result<ListEnvelope<ProjectRecord>, CoreError> {
1419        // Standard list params (limit=-1 = the UI's "everything").
1420        self.get_json(
1421            projects::PROJECTS_LIST_PATH,
1422            Some(&query.to_query_pairs()),
1423            true,
1424        )
1425        .await
1426    }
1427
1428    async fn project_find(&self, name: &str) -> Result<ProjectRecord, CoreError> {
1429        // The {name} segment is percent-encoded (Pitfall 6) — the
1430        // spaced-name recorded-request proof in tests/projects_contract.rs.
1431        self.get_json(&projects::project_find_path(name), None, true)
1432            .await
1433    }
1434
1435    async fn project_create(&self, body: &ProjectCreate) -> Result<(), CoreError> {
1436        // Ok classification IS the success contract; callers that want
1437        // data re-`find` (the actions layer's read-back).
1438        self.post_json(projects::PROJECTS_CREATE_PATH, body)
1439            .await
1440            .map(|_| ())
1441    }
1442
1443    async fn project_copy(&self, from: &str, to: &str) -> Result<(), CoreError> {
1444        let body = ProjectCopy {
1445            from_name: from.to_string(),
1446            to_name: to.to_string(),
1447        };
1448        self.post_json(projects::PROJECTS_COPY_PATH, &body)
1449            .await
1450            .map(|_| ())
1451    }
1452
1453    async fn project_rename(&self, name: &str, new_name: &str) -> Result<(), CoreError> {
1454        let body = ProjectRenameBody {
1455            name: new_name.to_string(),
1456        };
1457        self.post_json(&projects::project_rename_path(name), &body)
1458            .await
1459            .map(|_| ())
1460    }
1461
1462    async fn project_modify(&self, name: &str, body: &ProjectModify) -> Result<(), CoreError> {
1463        self.put_json(&projects::project_modify_path(name), body)
1464            .await
1465    }
1466
1467    async fn project_delete(&self, name: &str) -> Result<(), CoreError> {
1468        // BOTH guard layers (Pitfall 8): the CLI already refused
1469        // without --yes (exit 2, pre-resolution) AND the wire request
1470        // always carries the server's own `confirm=true` query param
1471        // (wiremock recorded-request proof).
1472        self.delete_with_query(
1473            &projects::project_delete_path(name),
1474            &[("confirm", "true".to_string())],
1475        )
1476        .await
1477    }
1478
1479    async fn project_export_to_file(
1480        &self,
1481        name: &str,
1482        out: &Path,
1483    ) -> Result<ExportMeta, CoreError> {
1484        // The 120 s per-request override rides the RequestBuilder (the
1485        // logs-download precedent); the streaming itself lives in
1486        // download_to_file (classify FIRST, then chunk loop). No
1487        // `Accept` header — the export contract never named one.
1488        self.download_to_file(
1489            &projects::project_export_path(name),
1490            out,
1491            projects::PROJECT_EXPORT_TIMEOUT,
1492            None,
1493        )
1494        .await
1495    }
1496
1497    async fn project_import(
1498        &self,
1499        name: &str,
1500        zip: Vec<u8>,
1501        overwrite: bool,
1502    ) -> Result<ImportOutcome, CoreError> {
1503        // `overwrite` rides the QUERY string; the ZIP is the RAW body
1504        // with Content-Type application/zip and a known Content-Length
1505        // (Vec<u8> — chunked encoding never enters the picture). The
1506        // 300 s per-request override owns Pitfall 3. Token-auth POSTs
1507        // need no CSRF (02-RESEARCH §Auth Model).
1508        let url = self.url_for(&projects::project_import_path(name));
1509        let request = self
1510            .client
1511            .post(url.clone())
1512            .timeout(projects::PROJECT_IMPORT_TIMEOUT)
1513            .query(&[("overwrite", if overwrite { "true" } else { "false" })])
1514            .header(reqwest::header::CONTENT_TYPE, "application/zip")
1515            .body(zip);
1516        let request = self.apply_auth(request);
1517        let response = self.send_and_classify(request, &url).await?;
1518        // Opaque-success: parse the body when it is a JSON OBJECT,
1519        // else the fallback object (the body is unverified MEDIUM —
1520        // restart's `literal true` is the same family and normalizes
1521        // the same way, so agents always see a stable object shape).
1522        let body = response.text().await.unwrap_or_default();
1523        let parsed = serde_json::from_str::<serde_json::Value>(body.trim())
1524            .ok()
1525            .filter(|value| value.is_object())
1526            .unwrap_or_else(|| serde_json::json!({"status": "success"}));
1527        // Denial honesty (05-07, UAT Gap 1): the gateway refuses
1528        // imports over HTTP 200 with {success:false, problem} —
1529        // live-witnessed while NOTHING landed. ONE seam here fixes
1530        // every import caller at once (resource put/delete, project
1531        // import, webdev deploy) — per-caller checks are forbidden;
1532        // this IS the contract (the WebDev 200-denial precedent
1533        // applied to the import family).
1534        if let Some(problem) = projects::import_denied(&parsed) {
1535            return Err(CoreError::ImportDenied {
1536                project: name.to_string(),
1537                problem,
1538                endpoint: Some(url.to_string()),
1539            });
1540        }
1541        Ok(ImportOutcome { response: parsed })
1542    }
1543
1544    async fn tag_provider_list(
1545        &self,
1546        query: &query::ListQuery,
1547    ) -> Result<ListEnvelope<TagProviderRecord>, CoreError> {
1548        // Standard list params (limit=-1 = the UI's "everything") —
1549        // the connections-family resource lists' exact shape.
1550        self.get_json(
1551            tags::TAG_PROVIDERS_LIST_PATH,
1552            Some(&query.to_query_pairs()),
1553            true,
1554        )
1555        .await
1556    }
1557
1558    async fn tags_export_provider(&self, provider: &str) -> Result<Vec<u8>, CoreError> {
1559        // The `get_bytes` pipeline with the provider on the QUERY (a name
1560        // holding a space is percent-encoded by `.query`, never spliced into
1561        // the path) and the 300 s bulk-transfer ceiling.
1562        let url = self.url_for(tags::TAGS_EXPORT_PATH);
1563        let request = self
1564            .client
1565            .get(url.clone())
1566            .query(&[("provider", provider), ("type", "json")])
1567            .timeout(tags::TAGS_EXPORT_TIMEOUT);
1568        let request = self.apply_auth(request);
1569        let response = self.send_and_classify(request, &url).await?;
1570        let bytes = response.bytes().await.map_err(|err| CoreError::Network {
1571            url: url.to_string(),
1572            source: Some(err),
1573            observation: None,
1574        })?;
1575        Ok(bytes.to_vec())
1576    }
1577
1578    async fn tag_provider_find(&self, name: &str) -> Result<TagProviderRecord, CoreError> {
1579        self.get_json(&tags::tag_provider_find_path(name), None, true)
1580            .await
1581    }
1582
1583    async fn tag_provider_create(&self, body: &[TagProviderCreate]) -> Result<(), CoreError> {
1584        // The ARRAY body is the wire contract (a bare object 400s);
1585        // serde serializes elements in declaration order so the
1586        // recorded body is deterministic. Ok classification IS the
1587        // success contract (the project-create precedent).
1588        self.post_json(tags::TAG_PROVIDERS_CREATE_PATH, body)
1589            .await
1590            .map(|_| ())
1591    }
1592
1593    async fn tag_provider_delete(&self, name: &str, signature: &str) -> Result<(), CoreError> {
1594        // The signature rides the PATH (from find) — the
1595        // live-proven delete-by-signature chain; both segments
1596        // percent-encoded through the ONE locked encoder.
1597        self.delete_with_query(&tags::tag_provider_delete_path(name, signature), &[])
1598            .await
1599    }
1600
1601    async fn trial_status_wire(&self) -> Result<TrialWire, CoreError> {
1602        // Conditional auth: the endpoints answer unauthenticated
1603        // (live-verified both rigs), so a header-less client degrades
1604        // cleanly — but a carried credential rides along harmlessly
1605        // (future-proofing if a gateway version starts gating them).
1606        let auth = self.credential.is_some();
1607        self.get_json(trial::TRIAL_PATH, None, auth).await
1608    }
1609
1610    async fn banners(&self) -> Result<BannerSet, CoreError> {
1611        let auth = self.credential.is_some();
1612        self.get_json(trial::BANNERS_PATH, None, auth).await
1613    }
1614
1615    async fn trial_reset_wire(&self) -> Result<TrialWire, CoreError> {
1616        // Empty body, authed POST (the UI mutation's exact shape —
1617        // decompiled ia-gateway.js: {method:"POST",
1618        // url:"/data/api/v1/trial"}). Token-auth POSTs need no CSRF
1619        // (02-RESEARCH §Auth Model); on 403 the tier-1 session+CSRF
1620        // flow takes over (actions layer owns the ladder).
1621        let response = self.post_empty(trial::TRIAL_PATH, &[], true).await?;
1622        let body = response.text().await.unwrap_or_default();
1623        serde_json::from_str(&body).map_err(|err| {
1624            CoreError::Internal(format!(
1625                "trial reset response did not match the trial shape: {err}"
1626            ))
1627        })
1628    }
1629
1630    async fn backup_download(
1631        &self,
1632        out: &Path,
1633        backup_type: backup::BackupType,
1634    ) -> Result<ExportMeta, CoreError> {
1635        // Pure reuse: the type query rides the path builder, the
1636        // Accept header rides the helper's optional param, and the
1637        // 300 s class rides the RequestBuilder — the 03-02 chunk loop
1638        // stays THE one streaming body-consumption site (04-04).
1639        self.download_to_file(
1640            &backup::backup_download_path(backup_type),
1641            out,
1642            backup::BACKUP_TIMEOUT,
1643            Some(backup::BACKUP_ACCEPT),
1644        )
1645        .await
1646    }
1647
1648    async fn backup_restore(&self, gwbk: &Path) -> Result<(), CoreError> {
1649        // The upload direction buffers BY DESIGN (the import
1650        // precedent: a known Content-Length raw body sidesteps the
1651        // chunked-encoding question entirely). Token-auth POSTs need
1652        // no CSRF (02-RESEARCH §Auth Model). Ok classification IS the
1653        // acceptance contract — the actions layer owns the
1654        // post-restore RUNNING wait (Pitfall 6: the gateway restarts
1655        // after answering).
1656        let body = tokio::fs::read(gwbk)
1657            .await
1658            .map_err(|err| CoreError::InvalidInput {
1659                reason: format!("cannot read {}: {err}", gwbk.display()),
1660            })?;
1661        let url = self.url_for(backup::BACKUP_PATH);
1662        let request = self
1663            .client
1664            .post(url.clone())
1665            .timeout(backup::BACKUP_TIMEOUT)
1666            .query(&backup::restore_query())
1667            .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
1668            .body(body);
1669        let request = self.apply_auth(request);
1670        self.send_and_classify(request, &url).await.map(|_| ())
1671    }
1672
1673    async fn eam_task_history(
1674        &self,
1675        limit: Option<u32>,
1676        search: Option<&str>,
1677    ) -> Result<ListEnvelope<EamHistoryItem>, CoreError> {
1678        let query = query::ListQuery {
1679            limit: limit
1680                .map(i64::from)
1681                .unwrap_or(eam::EAM_HISTORY_DEFAULT_LIMIT),
1682            search: search.map(str::to_string),
1683            ..query::ListQuery::default()
1684        };
1685        self.get_json(eam::EAM_HISTORY_PATH, Some(&query.to_query_pairs()), true)
1686            .await
1687    }
1688
1689    async fn eam_task_definitions(&self) -> Result<ListEnvelope<EamTaskRecord>, CoreError> {
1690        // Standard list params (limit=-1 = the UI's "everything") —
1691        // definition counts are small; the connections-family
1692        // resource lists' exact shape.
1693        self.get_json(
1694            &eam::eam_tasks_list_path(),
1695            Some(&query::ListQuery::default().to_query_pairs()),
1696            true,
1697        )
1698        .await
1699    }
1700
1701    async fn eam_task_find(&self, name: &str) -> Result<EamTaskRecord, CoreError> {
1702        self.get_json(&eam::eam_task_find_path(name), None, true)
1703            .await
1704    }
1705
1706    async fn eam_task_create(&self, definition: &serde_json::Value) -> Result<(), CoreError> {
1707        // The ARRAY body is the wire contract (a bare object 400s —
1708        // the tag-provider create precedent); the caller's composed
1709        // definition rides as the single element. Ok classification
1710        // IS the success contract.
1711        self.post_json(&eam::eam_tasks_create_path(), &[definition])
1712            .await
1713            .map(|_| ())
1714    }
1715
1716    async fn eam_task_force(&self, owner: &str, name: &str) -> Result<(), CoreError> {
1717        // Empty body, authed POST — 204 is the live-proven success
1718        // shape; classify()'s 2xx pass-through IS the oracle (any
1719        // 2xx = dispatched; outcomes land in history as data).
1720        self.post_empty(&eam::eam_force_path(owner, name), &[], true)
1721            .await
1722            .map(|_| ())
1723    }
1724
1725    async fn eam_task_suspend(&self, name: &str) -> Result<(), CoreError> {
1726        // Empty body, authed POST — 204 is the captured success shape
1727        // (10-LIVE-CAPTURES §1b/§1c); the suspend/resume failure
1728        // modes are 500 HTML (classify → Internal with the page's
1729        // message — the module-doc finding; no 404 exists here).
1730        self.post_empty(&eam::eam_task_suspend_path(name), &[], true)
1731            .await
1732            .map(|_| ())
1733    }
1734
1735    async fn eam_task_resume(&self, name: &str) -> Result<(), CoreError> {
1736        // Same shape as suspend: 204 success (§1b/§1d — resume of a
1737        // never-suspended task is ALSO a 204; idempotent wire).
1738        self.post_empty(&eam::eam_task_resume_path(name), &[], true)
1739            .await
1740            .map(|_| ())
1741    }
1742
1743    async fn eam_task_cancel(&self, name: &str) -> Result<(), CoreError> {
1744        // 204 whether a pending execution existed, the task has
1745        // nothing pending, or the name is unknown (§7) — cancel is
1746        // wire-idempotent; name validation is the actions layer's
1747        // find-before-write job.
1748        self.post_empty(&eam::eam_task_cancel_path(name), &[], true)
1749            .await
1750            .map(|_| ())
1751    }
1752
1753    async fn eam_tasks_scheduled(&self, running: bool) -> Result<Vec<EamScheduledTask>, CoreError> {
1754        // The standard {items, metadata} envelope (§2 — byte-identical
1755        // shape across both rigs, incl. the empty-list quiet body);
1756        // this method unwraps the envelope to the items.
1757        let envelope: query::ListEnvelope<EamScheduledTask> = self
1758            .get_json(&eam::eam_tasks_scheduled_path(running), None, true)
1759            .await?;
1760        Ok(envelope.items)
1761    }
1762
1763    async fn eam_task_modify(
1764        &self,
1765        definition: &serde_json::Value,
1766    ) -> Result<Option<ModifyOutcome>, CoreError> {
1767        // The ARRAY body is the wire contract (single element — the
1768        // §6a capture; a bare object is not the shape the resource
1769        // PUT family speaks). The classify-first rule holds, then the
1770        // captured 200 body parses into ModifyOutcome (None = a 2xx
1771        // that carried no body — the lenient `Option` per the plan).
1772        let url = self.url_for(&eam::eam_tasks_modify_path());
1773        let request = self.apply_auth(self.client.put(url.clone()).json(&[definition]));
1774        let response = self.send_and_classify(request, &url).await?;
1775        let text = response.text().await.unwrap_or_default();
1776        if text.trim().is_empty() {
1777            return Ok(None);
1778        }
1779        serde_json::from_str(&text).map(Some).map_err(|err| {
1780            CoreError::Internal(format!(
1781                "response from {url} did not match the expected shape: {err}"
1782            ))
1783        })
1784    }
1785
1786    async fn eam_task_delete(
1787        &self,
1788        name: &str,
1789        signature: &str,
1790        confirm: bool,
1791    ) -> Result<DeleteOutcome, CoreError> {
1792        // `collection=core` ALWAYS (the captured success value — the
1793        // type token 404s, §3c); `confirm=true` rides ONLY on
1794        // explicit opt-in (a lone-resource delete succeeds without
1795        // it, §3b; the confirm-demand shape is unobserved, §3d —
1796        // never hard-coded). The 200 body is the captured
1797        // DeleteOutcome; classify-first as everywhere.
1798        let url = self.url_for(&eam::eam_task_delete_path(name, signature));
1799        let mut pairs: Vec<(&str, String)> = vec![("collection", "core".to_string())];
1800        if confirm {
1801            pairs.push(("confirm", "true".to_string()));
1802        }
1803        let request = self.apply_auth(self.client.delete(url.clone()).query(&pairs));
1804        let response = self.send_and_classify(request, &url).await?;
1805        let text = response.text().await.unwrap_or_default();
1806        serde_json::from_str(&text).map_err(|err| {
1807            CoreError::Internal(format!(
1808                "response from {url} did not match the expected shape: {err}"
1809            ))
1810        })
1811    }
1812
1813    async fn api_call(
1814        &self,
1815        call: &apicall::ApiCallRequest,
1816    ) -> Result<apicall::ApiCallData, CoreError> {
1817        let url = self.url_for(&call.path);
1818        // Any RFC verb (lowercase input normalized); an unparseable
1819        // method is a usage-class refusal BEFORE the wire — reqwest's
1820        // own `Method` parse is the validator (no hand-rolled list).
1821        let method =
1822            reqwest::Method::from_bytes(call.method.to_uppercase().as_bytes()).map_err(|_| {
1823                CoreError::InvalidInput {
1824                    reason: format!(
1825                        "{:?} is not a valid HTTP method — use an RFC verb \
1826                     (GET/POST/PUT/DELETE/PATCH/HEAD, …)",
1827                        call.method
1828                    ),
1829                }
1830            })?;
1831        let mut request = self.client.request(method, url.clone());
1832        for (name, value) in &call.headers {
1833            // reqwest's `.header()` PANICS on an invalid name/value —
1834            // these strings are user-supplied, so they are validated
1835            // HERE: a bad header is an exit-2 refusal, never a crash
1836            // (the webdev extra_headers loop never carried raw user
1837            // input; this one does).
1838            let name =
1839                reqwest::header::HeaderName::from_bytes(name.trim().as_bytes()).map_err(|_| {
1840                    CoreError::InvalidInput {
1841                        reason: format!("{name:?} is not a valid HTTP header name"),
1842                    }
1843                })?;
1844            let value = reqwest::header::HeaderValue::from_str(value).map_err(|_| {
1845                CoreError::InvalidInput {
1846                    reason: format!("{value:?} is not a valid HTTP header value"),
1847                }
1848            })?;
1849            request = request.header(name, value);
1850        }
1851        // The ONE query mechanism: reqwest's own serializer (the same
1852        // `.query(&pairs)` shape every other capability uses) — never
1853        // a `?` smuggled through the path (validate_path refuses it).
1854        if !call.query.is_empty() {
1855            request = request.query(&call.query);
1856        }
1857        if let Some(body) = &call.body {
1858            // Raw TEXT on ANY method — GET/DELETE body passthrough is
1859            // allowed (curl parity; the gateway's answer classifies).
1860            request = request.body(body.clone());
1861        }
1862        // THE auth site: profile credentials only (the redaction
1863        // boundary); the pipeline tail is the api-call-scoped
1864        // classifier so unclassified gateway 4xx ride
1865        // GatewayClientError instead of Internal.
1866        let request = self.apply_auth(request);
1867        let response = self.send_and_classify_for_api(request, &url).await?;
1868        let status = response.status().as_u16();
1869        let text = response.text().await.map_err(|err| CoreError::Network {
1870            url: url.to_string(),
1871            source: Some(err),
1872            observation: None,
1873        })?;
1874        // THE verbatim decision (research OQ1): `from_string` both
1875        // preserves the gateway's bytes (key order, unknown fields)
1876        // AND validates JSON in one call — no parse-re-serialize. A
1877        // non-JSON 2xx body is the documented internal-class honesty
1878        // refusal (binary endpoints ride the download pipelines).
1879        let data = serde_json::value::RawValue::from_string(text).map_err(|err| {
1880            CoreError::Internal(format!(
1881                "the gateway answered 2xx with a non-JSON body — api call returns \
1882                 JSON; use logs/backup downloads for binary endpoints ({err})"
1883            ))
1884        })?;
1885        Ok(apicall::ApiCallData { status, data })
1886    }
1887
1888    async fn license_status(&self) -> Result<LicenseStatusWire, CoreError> {
1889        // auth = true — a /data route under 8.3 default security (the
1890        // gateway-info rule); the capture session rode a token header.
1891        self.get_json(license::LICENSES_PATH, None, true).await
1892    }
1893
1894    async fn redundancy_status(&self) -> Result<RedundancyStatusWire, CoreError> {
1895        self.get_json(redundancy::REDUNDANCY_PATH, None, true).await
1896    }
1897
1898    async fn gan_status(&self) -> Result<GanStatusWire, CoreError> {
1899        self.get_json(gan::GAN_OVERVIEW_PATH, None, true).await
1900    }
1901
1902    async fn bundle_generate(&self) -> Result<BundleStatusWire, CoreError> {
1903        // Empty body, authed POST (the restart/set-logger precedent;
1904        // token mutations need no CSRF). The 200 body IS the status
1905        // wire per capture ({"state":"Generating"}) — classify-first
1906        // through the shared pipeline, then parse.
1907        let url = self.url_for(diagnostics::DIAGNOSTICS_GENERATE_PATH);
1908        let response = self
1909            .send_and_classify(self.apply_auth(self.client.post(url.clone())), &url)
1910            .await?;
1911        response.json::<BundleStatusWire>().await.map_err(|err| {
1912            CoreError::Internal(format!(
1913                "response from {url} did not match the expected shape: {err}"
1914            ))
1915        })
1916    }
1917
1918    async fn bundle_status(&self) -> Result<BundleStatusWire, CoreError> {
1919        // auth = true — a /data route under 8.3 default security; the
1920        // capture session rode a token header.
1921        self.get_json(diagnostics::DIAGNOSTICS_STATUS_PATH, None, true)
1922            .await
1923    }
1924
1925    async fn bundle_download(&self, out: &Path) -> Result<ExportMeta, CoreError> {
1926        // The 300 s per-request override rides the RequestBuilder
1927        // inside download_to_file (Pitfall 8: the 30 s client default
1928        // would truncate MB-sized bundles); the chunk loop stays THE
1929        // one streaming body-consumption site. No Accept header — the
1930        // capture named none (Content-Type: application/zip is the
1931        // answer). Disposition filename + content type ride ExportMeta.
1932        self.download_to_file(
1933            diagnostics::DIAGNOSTICS_DOWNLOAD_PATH,
1934            out,
1935            diagnostics::BUNDLE_DOWNLOAD_TIMEOUT,
1936            None,
1937        )
1938        .await
1939    }
1940}
1941
1942#[cfg(test)]
1943mod tests {
1944    use super::{GatewayApi, ReqwestGatewayApi};
1945
1946    /// Exercises `post_empty` end-to-end with the shape 02-04's
1947    /// set-logger-level route uses (query param + empty body): the
1948    /// verified restart shape is a 200 with literal body `true`,
1949    /// classified Ok — and the query param rides the request.
1950    #[tokio::test]
1951    async fn post_empty_sends_query_param_and_empty_body() {
1952        let server = wiremock::MockServer::start().await;
1953        let guard = wiremock::Mock::given(wiremock::matchers::method("POST"))
1954            .and(wiremock::matchers::path(
1955                "/data/api/v1/restart-tasks/restart",
1956            ))
1957            .and(wiremock::matchers::query_param("confirm", "true"))
1958            .respond_with(wiremock::ResponseTemplate::new(200).set_body_string("true"))
1959            .expect(1)
1960            .mount_as_scoped(&server)
1961            .await;
1962
1963        let api = ReqwestGatewayApi::for_tests(&server.uri(), None);
1964        let response = api
1965            .post_empty(
1966                "/data/api/v1/restart-tasks/restart",
1967                &[("confirm", "true".to_string())],
1968                true,
1969            )
1970            .await
1971            .expect("200 classifies Ok");
1972        assert_eq!(response.status(), reqwest::StatusCode::OK);
1973
1974        let requests = guard.received_requests().await;
1975        assert_eq!(requests.len(), 1);
1976        assert!(
1977            requests[0].body.is_empty(),
1978            "the POST carries NO body — params ride the query string"
1979        );
1980    }
1981
1982    /// The formatted thread dump rides its EXACT path
1983    /// (`/data/api/v1/diagnostics/threads/dump/formatted` — the
1984    /// Gateway web UI's Diagnostics→Threads endpoint, live-spec
1985    /// pinned) and parses into the tolerant model.
1986    #[tokio::test]
1987    async fn thread_dump_rides_the_formatted_dump_path() {
1988        let server = wiremock::MockServer::start().await;
1989        let guard = wiremock::Mock::given(wiremock::matchers::method("GET"))
1990            .and(wiremock::matchers::path(
1991                "/data/api/v1/diagnostics/threads/dump/formatted",
1992            ))
1993            .respond_with(
1994                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
1995                    "version": "dump-version-1",
1996                    "threads": [
1997                        {"name": "Perspective-Worker-3", "id": 42, "state": "RUNNABLE",
1998                         "daemon": true, "cpuUsage": 3.75, "stacktrace": ["frame-0"]}
1999                    ]
2000                })),
2001            )
2002            .expect(1)
2003            .mount_as_scoped(&server)
2004            .await;
2005
2006        let api = ReqwestGatewayApi::for_tests(&server.uri(), None);
2007        let dump = api.thread_dump().await.expect("200 + spec shape parses");
2008        assert_eq!(dump.threads.len(), 1);
2009        assert_eq!(dump.threads[0].id, Some(42));
2010        assert_eq!(dump.threads[0].state, "RUNNABLE");
2011        assert_eq!(guard.received_requests().await.len(), 1);
2012    }
2013
2014    /// The deadlocked-id list rides its EXACT path
2015    /// (`/data/api/v1/diagnostics/threads/deadlocks`) and the healthy
2016    /// empty-list body parses.
2017    #[tokio::test]
2018    async fn thread_deadlocks_rides_the_deadlocks_path() {
2019        let server = wiremock::MockServer::start().await;
2020        let guard = wiremock::Mock::given(wiremock::matchers::method("GET"))
2021            .and(wiremock::matchers::path(
2022                "/data/api/v1/diagnostics/threads/deadlocks",
2023            ))
2024            .respond_with(
2025                wiremock::ResponseTemplate::new(200)
2026                    .set_body_json(serde_json::json!({"deadlocks": [7, 42]})),
2027            )
2028            .expect(1)
2029            .mount_as_scoped(&server)
2030            .await;
2031
2032        let api = ReqwestGatewayApi::for_tests(&server.uri(), None);
2033        let wire = api
2034            .thread_deadlocks()
2035            .await
2036            .expect("200 + the deadlocks shape parses");
2037        assert_eq!(wire.deadlocks, vec![7, 42]);
2038        assert_eq!(guard.received_requests().await.len(), 1);
2039    }
2040}