Skip to main content

lean_ctx/core/context_package/
remote.rs

1//! Client for the hosted ctxpkg registry (GL #406) — publish, resolve, fetch.
2//!
3//! Trust model: the registry is the authenticity gate, this client is the
4//! integrity gate. Every download is verified locally — artifact SHA-256
5//! against the package index AND the embedded ed25519 manifest signature —
6//! so a compromised registry cannot hand us altered content undetected.
7
8use sha2::{Digest, Sha256};
9
10use super::manifest::PackageManifest;
11
12/// Default public registry, served via ctxpkg.com (nginx → control plane).
13pub const DEFAULT_REGISTRY: &str = "https://ctxpkg.com/api";
14
15/// Resolve the registry base URL: explicit flag > `CTXPKG_REGISTRY` env >
16/// the public default. Trailing slashes are trimmed for clean joins.
17pub fn registry_base(flag: Option<&str>) -> String {
18    flag.map(str::to_string)
19        .or_else(|| std::env::var("CTXPKG_REGISTRY").ok())
20        .filter(|s| !s.trim().is_empty())
21        .unwrap_or_else(|| DEFAULT_REGISTRY.to_string())
22        .trim_end_matches('/')
23        .to_string()
24}
25
26/// Resolve the registry token: explicit flag > `CTXPKG_TOKEN` env. Used for
27/// publish (`ctxp_…`) and for installing private packages (`ctxp_…` or the
28/// read-only `ctxr_…`, GL #524).
29pub fn publish_token(flag: Option<&str>) -> Option<String> {
30    flag.map(str::to_string)
31        .or_else(|| std::env::var("CTXPKG_TOKEN").ok())
32        .filter(|s| !s.trim().is_empty())
33}
34
35/// A remote package reference: `@ns/name` or `ns/name`, optional `@version`
36/// pin after the name (`acme/auth-context@1.2.0`).
37#[derive(Debug, PartialEq, Eq)]
38pub struct RemoteRef {
39    pub namespace: String,
40    pub name: String,
41    pub version: Option<String>,
42}
43
44/// Parse a remote reference. Returns `None` for plain local names (no `/`).
45pub fn parse_remote_ref(input: &str) -> Option<RemoteRef> {
46    let trimmed = input.strip_prefix('@').unwrap_or(input);
47    let (ns, rest) = trimmed.split_once('/')?;
48    let (name, version) = match rest.split_once('@') {
49        Some((n, v)) => (n, Some(v.to_string())),
50        None => (rest, None),
51    };
52    if ns.is_empty() || name.is_empty() {
53        return None;
54    }
55    Some(RemoteRef {
56        namespace: ns.to_string(),
57        name: name.to_string(),
58        version,
59    })
60}
61
62/// One version entry from the package index.
63#[derive(Debug)]
64pub struct VersionInfo {
65    pub version: String,
66    pub artifact_sha256: String,
67    pub yanked: bool,
68}
69
70/// `GET {base}/v1/packages/{ns}/{name}/index.json` → all versions.
71/// `token` unlocks private packages; public ones need none.
72pub fn fetch_versions(
73    base: &str,
74    ns: &str,
75    name: &str,
76    token: Option<&str>,
77) -> Result<Vec<VersionInfo>, String> {
78    let url = format!("{base}/v1/packages/{ns}/{name}/index.json");
79    let body = http_get(&url, token)?;
80    let doc: serde_json::Value =
81        serde_json::from_str(&body).map_err(|e| format!("registry returned non-JSON: {e}"))?;
82    let versions = doc
83        .get("versions")
84        .and_then(|v| v.as_array())
85        .ok_or("registry index has no versions array")?;
86    Ok(versions
87        .iter()
88        .filter_map(|v| {
89            Some(VersionInfo {
90                version: v.get("version")?.as_str()?.to_string(),
91                artifact_sha256: v.get("artifact_sha256")?.as_str()?.to_string(),
92                yanked: v
93                    .get("yanked")
94                    .and_then(serde_json::Value::as_bool)
95                    .unwrap_or(false),
96            })
97        })
98        .collect())
99}
100
101/// Pick the version to install: an explicit pin (yanked allowed, warned by
102/// the caller) or the newest non-yanked version.
103pub fn select_version<'a>(
104    versions: &'a [VersionInfo],
105    pin: Option<&str>,
106) -> Result<&'a VersionInfo, String> {
107    match pin {
108        Some(want) => versions
109            .iter()
110            .find(|v| v.version == want)
111            .ok_or(format!("version {want} not found in the registry")),
112        None => versions
113            .iter()
114            .find(|v| !v.yanked)
115            .ok_or("no installable (non-yanked) version found".to_string()),
116    }
117}
118
119/// Download an artifact and verify its SHA-256 against the index entry.
120pub fn download_verified(
121    base: &str,
122    ns: &str,
123    name: &str,
124    info: &VersionInfo,
125    token: Option<&str>,
126) -> Result<Vec<u8>, String> {
127    let url = format!("{base}/v1/packages/{ns}/{name}/{}/download", info.version);
128    let bytes = http_get_bytes(&url, token)?;
129    let actual = sha256_hex(&bytes);
130    if actual != info.artifact_sha256 {
131        return Err(format!(
132            "artifact checksum mismatch — registry index says {}, downloaded bytes hash to {actual}; \
133             refusing to install",
134            info.artifact_sha256
135        ));
136    }
137    Ok(bytes)
138}
139
140/// Publish receipt as returned by the registry.
141#[derive(Debug)]
142pub struct PublishReceipt {
143    pub published: String,
144    pub artifact_sha256: String,
145}
146
147/// `PUT {base}/v1/packages/{ns}/{name}/{version}` with the artifact bytes.
148pub fn publish(
149    base: &str,
150    token: &str,
151    ns: &str,
152    name: &str,
153    version: &str,
154    bytes: &[u8],
155) -> Result<PublishReceipt, String> {
156    let url = format!("{base}/v1/packages/{ns}/{name}/{version}");
157    let agent: ureq::Agent = ureq::config::Config::builder()
158        .tls_config(crate::core::http_client::platform_tls_config())
159        .http_status_as_error(false)
160        .build()
161        .into();
162    let resp = agent
163        .put(&url)
164        .header("Authorization", &format!("Bearer {token}"))
165        .header("Content-Type", "application/octet-stream")
166        .send(bytes)
167        .map_err(|e| format!("registry unreachable: {e}"))?;
168    let status = resp.status().as_u16();
169    let body = resp
170        .into_body()
171        .read_to_string()
172        .map_err(|e| format!("read registry response: {e}"))?;
173
174    if status == 201 {
175        let doc: serde_json::Value =
176            serde_json::from_str(&body).map_err(|e| format!("registry returned non-JSON: {e}"))?;
177        return Ok(PublishReceipt {
178            published: doc
179                .get("published")
180                .and_then(|v| v.as_str())
181                .unwrap_or("(unknown)")
182                .to_string(),
183            artifact_sha256: doc
184                .get("artifact_sha256")
185                .and_then(|v| v.as_str())
186                .unwrap_or("")
187                .to_string(),
188        });
189    }
190    // Error bodies are JSON {"error": …} or plain text — surface either.
191    let detail = serde_json::from_str::<serde_json::Value>(&body)
192        .ok()
193        .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string))
194        .unwrap_or(body);
195    Err(format!(
196        "registry rejected the publish (HTTP {status}): {detail}"
197    ))
198}
199
200/// Parse + verify a local bundle before any network call: must be a valid
201/// manifest with a verifying ed25519 signature, and the scoped name must
202/// match the publish target. Returns `(namespace, name, version)`.
203pub fn preflight_bundle(bytes: &[u8]) -> Result<(String, String, String), String> {
204    #[derive(serde::Deserialize)]
205    struct BundleProbe {
206        manifest: PackageManifest,
207    }
208    let probe: BundleProbe =
209        serde_json::from_slice(bytes).map_err(|e| format!("not a ctxpkg bundle: {e}"))?;
210    let manifest = probe.manifest;
211
212    let signed = super::signing::verify_signature(&manifest)?;
213    if !signed {
214        return Err(
215            "package is unsigned — the hosted registry requires ed25519 signatures \
216             (re-export with `lean-ctx pack export <name> --sign`)"
217                .to_string(),
218        );
219    }
220
221    let scoped = manifest.name.clone();
222    let stripped = scoped.strip_prefix('@').ok_or(format!(
223        "manifest.name '{scoped}' is not scoped — hosted packages need '@namespace/name'"
224    ))?;
225    let (ns, name) = stripped
226        .split_once('/')
227        .ok_or(format!("manifest.name '{scoped}' is not '@namespace/name'"))?;
228    Ok((ns.to_string(), name.to_string(), manifest.version))
229}
230
231/// Private packages return 404 for outsiders — hint at the token when none
232/// was sent, so `install` failures stay actionable.
233fn not_found_hint(token: Option<&str>) -> &'static str {
234    if token.is_some() {
235        "package not found in the registry (or your token's namespace does not own it)"
236    } else {
237        "package not found in the registry — private packages need CTXPKG_TOKEN"
238    }
239}
240
241/// Paid packs answer 402 with an actionable message in `{"error": …}`
242/// (where to buy, how to install) — surface it verbatim (GL #529).
243fn payment_hint(body: &str) -> String {
244    serde_json::from_str::<serde_json::Value>(body)
245        .ok()
246        .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string))
247        .unwrap_or_else(|| "this is a paid package — purchase required".to_string())
248}
249
250fn http_get(url: &str, token: Option<&str>) -> Result<String, String> {
251    let agent: ureq::Agent = ureq::config::Config::builder()
252        .tls_config(crate::core::http_client::platform_tls_config())
253        .http_status_as_error(false)
254        .build()
255        .into();
256    let mut req = agent.get(url);
257    if let Some(t) = token {
258        req = req.header("Authorization", &format!("Bearer {t}"));
259    }
260    let resp = req
261        .call()
262        .map_err(|e| format!("registry unreachable: {e}"))?;
263    let status = resp.status().as_u16();
264    let body = resp
265        .into_body()
266        .read_to_string()
267        .map_err(|e| format!("read registry response: {e}"))?;
268    if status == 404 {
269        return Err(not_found_hint(token).to_string());
270    }
271    if status == 402 {
272        return Err(payment_hint(&body));
273    }
274    if status >= 400 {
275        return Err(format!("registry error (HTTP {status})"));
276    }
277    Ok(body)
278}
279
280fn http_get_bytes(url: &str, token: Option<&str>) -> Result<Vec<u8>, String> {
281    let agent: ureq::Agent = ureq::config::Config::builder()
282        .tls_config(crate::core::http_client::platform_tls_config())
283        .http_status_as_error(false)
284        .build()
285        .into();
286    let mut req = agent.get(url);
287    if let Some(t) = token {
288        req = req.header("Authorization", &format!("Bearer {t}"));
289    }
290    let resp = req
291        .call()
292        .map_err(|e| format!("registry unreachable: {e}"))?;
293    let status = resp.status().as_u16();
294    if status == 404 {
295        return Err(not_found_hint(token).to_string());
296    }
297    let mut reader = resp.into_body().into_reader();
298    let mut buf = Vec::new();
299    std::io::Read::read_to_end(&mut reader, &mut buf).map_err(|e| format!("read artifact: {e}"))?;
300    if status == 402 {
301        return Err(payment_hint(&String::from_utf8_lossy(&buf)));
302    }
303    if status >= 400 {
304        return Err(format!("registry error (HTTP {status})"));
305    }
306    Ok(buf)
307}
308
309fn sha256_hex(bytes: &[u8]) -> String {
310    let mut h = Sha256::new();
311    h.update(bytes);
312    crate::core::agent_identity::hex_encode(&h.finalize())
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318
319    #[test]
320    fn remote_ref_parsing() {
321        assert_eq!(
322            parse_remote_ref("acme/auth-context"),
323            Some(RemoteRef {
324                namespace: "acme".into(),
325                name: "auth-context".into(),
326                version: None
327            })
328        );
329        assert_eq!(
330            parse_remote_ref("@acme/auth-context@1.2.0"),
331            Some(RemoteRef {
332                namespace: "acme".into(),
333                name: "auth-context".into(),
334                version: Some("1.2.0".into())
335            })
336        );
337        assert_eq!(parse_remote_ref("local-package"), None);
338        assert_eq!(parse_remote_ref("/x"), None);
339        assert_eq!(parse_remote_ref("ns/"), None);
340    }
341
342    #[test]
343    fn version_selection_skips_yanked_unless_pinned() {
344        let versions = vec![
345            VersionInfo {
346                version: "2.0.0".into(),
347                artifact_sha256: "b".into(),
348                yanked: true,
349            },
350            VersionInfo {
351                version: "1.0.0".into(),
352                artifact_sha256: "a".into(),
353                yanked: false,
354            },
355        ];
356        assert_eq!(
357            select_version(&versions, None).expect("latest").version,
358            "1.0.0"
359        );
360        assert_eq!(
361            select_version(&versions, Some("2.0.0"))
362                .expect("pinned")
363                .version,
364            "2.0.0"
365        );
366        assert!(select_version(&versions, Some("3.0.0")).is_err());
367    }
368
369    #[test]
370    fn registry_base_resolution_order() {
371        assert_eq!(
372            registry_base(Some("https://r.example/api/")),
373            "https://r.example/api"
374        );
375        // No flag, no env (tests run without CTXPKG_REGISTRY) → default.
376        if std::env::var("CTXPKG_REGISTRY").is_err() {
377            assert_eq!(registry_base(None), DEFAULT_REGISTRY);
378        }
379    }
380
381    #[test]
382    fn preflight_rejects_garbage_and_unscoped() {
383        assert!(preflight_bundle(b"not json").is_err());
384    }
385}