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