openlatch-provider 0.2.1

Self-service onboarding CLI + runtime daemon for OpenLatch Editors and Providers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! `register` — load the active manifest, diff against live state, create/update.
//!
//! Flow per `phase-1-editor-cli.md` task P1.T6:
//!
//! ```text
//! 1. Load + validate the active manifest (`<provider_dir>/<slug>.yaml`)
//! 2. Resolve auth + build ApiClient
//! 3. Pre-flight probe all bindings (client-side)
//!    - Aggregate failures; report with field paths
//!    - All fail -> exit 1
//!    - Some fail -> exit 5 (partial), prompt with --yes
//! 4. Diff against live state (GET tools/providers/bindings)
//!    - Compute create / update / no-op per resource
//! 5. If --dry-run: print plan + would-be HTTP calls; exit 0/5
//! 6. Execute create/update sequentially:
//!    - editor profile (PATCH)
//!    - tools (POST upsert per slug)
//!    - providers (POST upsert per slug)
//!    - bindings (POST upsert per binding)
//! 7. Capture freshly-issued whsec_live_… secrets
//! 8. Print summary
//! 9. Telemetry
//! ```

use std::collections::BTreeSet;
use std::path::PathBuf;

use clap::Args;
use secrecy::SecretString;

use crate::api::client::ApiClient;
use crate::api::editor;
use crate::api::probe;
use crate::auth::binding_secrets::{
    default_file_dir, BindingSecretStore, FileBindingSecretStore, KeyringBindingSecretStore,
};
use crate::cli::commands::shared::make_client;
use crate::cli::GlobalArgs;
use crate::config;
use crate::error::{
    OlError, OL_4210_SCHEMA_MISMATCH, OL_4244_SYNTHETIC_PROBE_FAILED,
    OL_4280_PLATFORM_DUPLICATE_TOOL_SLUG, OL_4281_PLATFORM_DUPLICATE_PROVIDER_SLUG,
    OL_4283_PLATFORM_DUPLICATE_BINDING, OL_4284_PREFLIGHT_VALIDATION_FAILED,
};
use crate::manifest::{self, Manifest};
use crate::ui::output::OutputConfig;

#[derive(Args, Debug)]
pub struct RegisterArgs {
    /// Path to a manifest file (default: resolved from `[profiles.<profile>]
    /// manifest_slug` in `~/.openlatch/provider/config.toml`). v2 provider
    /// manifests (`kind: Provider`) are auto-detected. `--provider` is the
    /// canonical v2 spelling.
    #[arg(long, alias = "provider", value_name = "PATH")]
    pub manifest: Option<String>,

    /// Permit binding endpoints that resolve to non-public IPs (loopback /
    /// private / cloud-metadata / IPv4-mapped). Intended for local
    /// development against a tool server on `localhost`. The platform's
    /// authoritative probe still enforces public-IP-only in production —
    /// never use this flag for live registrations.
    #[arg(long)]
    pub allow_local_endpoints: bool,

    /// Skip every pre-flight check that runs before the platform mutations:
    /// the client-side endpoint probe AND the whole-manifest `:validate`
    /// pass. Exists as an escape hatch when you know a partial write needs
    /// to be reconciled (e.g. tool #1 already created on the platform,
    /// retrying after a transient failure) or when an endpoint deliberately
    /// can't be reached from the developer's host (e.g. RFC 6761 reserved
    /// placeholders in fixtures). The platform's authoritative server-side
    /// probe still runs at provider-upsert time, so SSRF posture is
    /// preserved. Default off.
    #[arg(long)]
    pub skip_preflight: bool,
}

pub async fn run(g: &GlobalArgs, args: RegisterArgs) -> Result<(), OlError> {
    let out = OutputConfig::resolve(g);
    let manifest_path: PathBuf = match args.manifest {
        Some(p) => PathBuf::from(p),
        None => config::active_manifest_path(g.profile.as_deref())?,
    };
    out.print_step(&format!(
        "Loading manifest from {}",
        manifest_path.display()
    ));
    let m = manifest::load(&manifest_path)?;

    let probe_opts = probe::ProbeOpts {
        allow_local: args.allow_local_endpoints,
    };
    if args.allow_local_endpoints {
        out.print_info(
            "⚠  --allow-local-endpoints enabled: skipping public-IP / cloud-metadata \
             checks. Never use this flag for production registrations.",
        );
    }

    // --- Pre-flight probe ------------------------------------------------
    // Probe each provider's public ingress once, recording the failed
    // `endpoint_url` set so the binding upsert loop can skip bindings whose
    // provider failed without re-probing the network. Gated behind
    // `--skip-preflight` so users with intentionally-unreachable fixture
    // URLs (RFC 6761 .invalid placeholders, deliberately air-gapped dev
    // environments) can still register; the platform's server-side probe
    // remains the SSRF authority either way.
    let mut failed_probes: BTreeSet<String> = BTreeSet::new();
    if args.skip_preflight {
        out.print_info(
            "⚠  --skip-preflight set: bypassing client-side endpoint probe. The platform's \
             server-side probe still validates SSRF posture at upsert time.",
        );
    } else if !m.providers.is_empty() {
        out.print_step(&format!(
            "Probing {} provider endpoint(s) (client-side)",
            m.providers.len()
        ));
        for p in &m.providers {
            match probe::probe_with_opts(&p.endpoint_url, probe_opts) {
                Ok(report) => {
                    out.print_substep(&format!(
                        "{} ({})",
                        p.endpoint_url,
                        report.resolved_ips.join(",")
                    ));
                }
                Err(e) => {
                    failed_probes.insert(p.endpoint_url.clone());
                    out.print_substep(&format!(
                        "{} — [{}] {}",
                        p.endpoint_url, e.code.code, e.message
                    ));
                }
            }
        }
        if failed_probes.len() == m.providers.len() {
            return Err(OlError::new(
                OL_4244_SYNTHETIC_PROBE_FAILED,
                format!(
                    "all {} provider probe(s) failed; aborting before contacting the platform",
                    m.providers.len()
                ),
            ));
        }
        if !failed_probes.is_empty() && !g.yes {
            return Err(OlError::new(
                OL_4244_SYNTHETIC_PROBE_FAILED,
                format!(
                    "{}/{} provider probe(s) failed; re-run with --yes to proceed with the \
                     remaining providers (exit code 5)",
                    failed_probes.len(),
                    m.providers.len()
                ),
            ));
        }
    }
    let probe_failures = failed_probes.len();

    // --- Build client + fetch live state once ---------------------------
    // The live state feeds both pre-flight (skip-if-owned) and the diff phase.
    let client = make_client().await?;
    let (live_tools, live_providers, live_bindings) = tokio::try_join!(
        editor::list_tools(&client),
        editor::list_providers(&client),
        editor::list_bindings(&client),
    )
    .unwrap_or_default();

    let live_tool_slugs: BTreeSet<String> = live_tools.iter().map(|t| t.slug.clone()).collect();
    let live_provider_slugs: BTreeSet<String> =
        live_providers.iter().map(|p| p.slug.clone()).collect();
    let live_binding_keys: BTreeSet<(String, String)> = live_bindings
        .iter()
        .map(|b| (b.tool.clone(), b.provider.clone()))
        .collect();

    // --- Pre-flight :validate pass (fail-fast, all-or-nothing) ----------
    if !args.skip_preflight {
        out.print_step("Pre-flight: validating manifest against platform");
        preflight_validate(
            &client,
            &m,
            &live_tool_slugs,
            &live_provider_slugs,
            &live_binding_keys,
        )
        .await?;
        out.print_substep("✓ pre-flight passed");
    } else {
        out.print_info(
            "⚠  --skip-preflight set: bypassing platform :validate. Slug conflicts will surface mid-upsert.",
        );
    }

    let mut plan: Vec<String> = Vec::new();
    plan.push(format!(
        "PATCH /api/v1/editor/profile  (editor `{}`)",
        *m.editor.slug
    ));
    for t in &m.tools {
        let kind = if live_tool_slugs.contains(&*t.slug) {
            "update"
        } else {
            "create"
        };
        plan.push(format!(
            "POST /api/v1/editor/tools  (tool `{}` v{}, {kind})",
            *t.slug, *t.version
        ));
    }
    for p in &m.providers {
        let kind = if live_provider_slugs.contains(&*p.slug) {
            "update"
        } else {
            "create"
        };
        plan.push(format!(
            "POST /api/v1/editor/providers  (provider `{}`, {kind})",
            *p.slug
        ));
    }
    for b in &m.bindings {
        let kind = if live_binding_keys.contains(&(b.tool.clone(), b.provider.clone())) {
            "update"
        } else {
            "create"
        };
        plan.push(format!(
            "POST /api/v1/editor/bindings  (binding {}/{}, {kind})",
            b.tool, b.provider
        ));
    }

    if g.dry_run {
        out.print_step("Dry run — would execute:");
        for line in &plan {
            out.print_substep(line);
        }
        return Ok(());
    }

    // --- Execute mutations ----------------------------------------------
    out.print_step("Updating editor profile");
    let editor_patch = editor::EditorProfilePatch {
        display_name: Some(m.editor.display_name.to_string()),
        description: m.editor.description.as_ref().map(|d| d.to_string()),
        homepage_url: m.editor.homepage_url.clone(),
        docs_url: m.editor.docs_url.clone(),
    };
    editor::update_profile(&client, &editor_patch).await?;

    if !m.tools.is_empty() {
        out.print_step(&format!("Upserting {} tool(s)", m.tools.len()));
        for t in &m.tools {
            let body = serde_json::to_value(t).map_err(|e| {
                OlError::new(
                    OL_4210_SCHEMA_MISMATCH,
                    format!("serialise tool `{}`: {e}", *t.slug),
                )
            })?;
            editor::upsert_tool(&client, &body).await?;
            out.print_substep(&format!("✓ tool `{}`", *t.slug));
        }
    }

    let mut binding_count = 0u32;
    if !m.providers.is_empty() {
        out.print_step(&format!("Upserting {} provider(s)", m.providers.len()));
        for p in &m.providers {
            let body = serde_json::to_value(p).map_err(|e| {
                OlError::new(
                    OL_4210_SCHEMA_MISMATCH,
                    format!("serialise provider `{}`: {e}", *p.slug),
                )
            })?;
            editor::upsert_provider(&client, &body).await?;
            out.print_substep(&format!("✓ provider `{}`", *p.slug));
        }
    }

    if !m.bindings.is_empty() {
        // Build a binding-provider -> endpoint_url lookup so we can skip
        // bindings whose provider's probe failed earlier (--yes path).
        let provider_endpoint_by_slug: std::collections::BTreeMap<String, String> = m
            .providers
            .iter()
            .map(|p| (p.slug.to_string(), p.endpoint_url.clone()))
            .collect();
        out.print_step(&format!(
            "Upserting {} binding(s) (probes already passed)",
            m.bindings.len()
        ));
        for b in &m.bindings {
            // Skip bindings whose provider probe-failed earlier (--yes path) —
            // using the cached failure set instead of re-issuing the probe.
            let provider_url = provider_endpoint_by_slug
                .get(&*b.provider)
                .cloned()
                .unwrap_or_default();
            if !provider_url.is_empty() && failed_probes.contains(&provider_url) {
                out.print_substep(&format!(
                    "skipping {}/{} (provider probe failed earlier)",
                    b.tool, b.provider
                ));
                continue;
            }
            let mut body = serde_json::to_value(b).map_err(|e| {
                OlError::new(
                    OL_4210_SCHEMA_MISMATCH,
                    format!("serialise binding {}/{}: {e}", b.tool, b.provider),
                )
            })?;
            manifest::strip_local_only_binding_fields(&mut body);
            let resp = editor::upsert_binding(&client, &body).await?;
            binding_count += 1;
            out.print_substep(&format!(
                "✓ binding {} ({}/{}) state={}",
                resp.id,
                b.tool,
                b.provider,
                resp.state.as_deref().unwrap_or("active")
            ));
            if let Some(secret) = resp.secret {
                println!();
                out.print_substep(&format!(
                    "🔑 {} ← STORE THIS — will not be shown again",
                    secret
                ));
                if let Err(e) = persist_secret(&resp.id, &secret) {
                    tracing::warn!(
                        binding_id = %resp.id,
                        error = %e,
                        "could not persist binding secret locally"
                    );
                }
            }
        }
    }

    let region = m
        .providers
        .first()
        .map(|p| p.region.to_string())
        .unwrap_or_default();
    crate::telemetry::capture_global(crate::telemetry::Event::provider_registered(
        &region,
        binding_count,
        false,
    ));

    let exit_code = if probe_failures > 0 {
        out.print_info(&format!(
            "{} provider probe(s) skipped — exit code 5 (partial success)",
            probe_failures
        ));
        Err(OlError::new(
            OL_4244_SYNTHETIC_PROBE_FAILED,
            "partial success — some bindings were skipped because their provider's probe failed",
        ))
    } else {
        out.print_step("Registration complete.");
        Ok(())
    };
    exit_code
}

/// All-or-nothing pre-flight: validate every tool / provider / binding pair
/// against the platform's `:validate` endpoints before any mutation. Skips
/// slugs the editor already owns (callers pass the live-state sets — they
/// were fetched once for the diff phase). On any 409 collision, aggregates
/// the errors and returns a single composite `OL-4284` so the user sees
/// every conflict at once.
async fn preflight_validate(
    client: &ApiClient,
    m: &Manifest,
    owned_tools: &BTreeSet<String>,
    owned_providers: &BTreeSet<String>,
    owned_bindings: &BTreeSet<(String, String)>,
) -> Result<(), OlError> {
    let mut conflicts: Vec<serde_json::Value> = Vec::new();

    for t in &m.tools {
        let slug = (*t.slug).to_string();
        if owned_tools.contains(&slug) {
            continue;
        }
        let body = serde_json::to_value(t).map_err(|e| {
            OlError::new(
                OL_4210_SCHEMA_MISMATCH,
                format!("serialise tool `{slug}`: {e}"),
            )
        })?;
        if let Err(e) = editor::validate_tool(client, &body).await {
            if e.is(OL_4280_PLATFORM_DUPLICATE_TOOL_SLUG) {
                conflicts.push(serde_json::json!({
                    "kind": "tool",
                    "slug": slug,
                    "message": e.message,
                }));
            } else {
                return Err(e);
            }
        }
    }

    for p in &m.providers {
        let slug = (*p.slug).to_string();
        if owned_providers.contains(&slug) {
            continue;
        }
        let body = serde_json::to_value(p).map_err(|e| {
            OlError::new(
                OL_4210_SCHEMA_MISMATCH,
                format!("serialise provider `{slug}`: {e}"),
            )
        })?;
        if let Err(e) = editor::validate_provider(client, &body).await {
            if e.is(OL_4281_PLATFORM_DUPLICATE_PROVIDER_SLUG) {
                conflicts.push(serde_json::json!({
                    "kind": "provider",
                    "slug": slug,
                    "message": e.message,
                }));
            } else {
                return Err(e);
            }
        }
    }

    for b in &m.bindings {
        let key = (b.tool.clone(), b.provider.clone());
        if owned_bindings.contains(&key) {
            continue;
        }
        if let Err(e) = editor::validate_binding(client, &b.tool, &b.provider).await {
            if e.is(OL_4283_PLATFORM_DUPLICATE_BINDING) {
                conflicts.push(serde_json::json!({
                    "kind": "binding",
                    "tool": b.tool,
                    "provider": b.provider,
                    "message": e.message,
                }));
            } else {
                return Err(e);
            }
        }
    }

    if conflicts.is_empty() {
        return Ok(());
    }

    let summary = conflicts
        .iter()
        .map(|c| {
            let kind = c.get("kind").and_then(|v| v.as_str()).unwrap_or("?");
            if let Some(slug) = c.get("slug").and_then(|v| v.as_str()) {
                format!("{kind} `{slug}`")
            } else {
                let tool = c.get("tool").and_then(|v| v.as_str()).unwrap_or("?");
                let prov = c.get("provider").and_then(|v| v.as_str()).unwrap_or("?");
                format!("{kind} {tool}/{prov}")
            }
        })
        .collect::<Vec<_>>()
        .join(", ");

    Err(OlError::new(
        OL_4284_PREFLIGHT_VALIDATION_FAILED,
        format!(
            "pre-flight validation found {} conflict(s): {}",
            conflicts.len(),
            summary
        ),
    )
    .with_context(serde_json::json!({ "conflicts": conflicts }))
    .with_suggestion(
        "Pick different slugs in the manifest, or pass --skip-preflight to retry an in-progress register.",
    ))
}

fn persist_secret(binding_id: &str, secret: &str) -> Result<(), OlError> {
    let secret = SecretString::from(secret.to_string());
    let keyring = KeyringBindingSecretStore::new();
    if keyring.store(binding_id, secret.clone()).is_ok() {
        return Ok(());
    }
    let dir = default_file_dir(&config::provider_dir());
    let machine_id = config::machine_id_or_init().unwrap_or_else(|_| "unknown".into());
    FileBindingSecretStore::new(dir, machine_id).store(binding_id, secret)
}