lean-ctx-engine 3.12.2

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
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
//! HTTP client with pluggable authentication for config-based providers.
//!
//! Builds and executes authenticated HTTP requests using ureq based on
//! the `AuthConfig` from the provider's TOML/JSON definition.

use std::collections::HashMap;

use super::schema::{AuthConfig, ResourceConfig};

/// Resolved auth credentials (env vars already read).
#[derive(Debug, Clone)]
pub enum ResolvedAuth {
    Bearer(String),
    ApiKeyHeader { header: String, value: String },
    ApiKeyQuery { param: String, value: String },
    Basic { username: String, password: String },
    CustomHeader { header: String, value: String },
    None,
}

impl ResolvedAuth {
    /// Bind a source to the resolved credential without making credentials
    /// serializable. Length framing separates fields and authentication kinds.
    pub(super) fn binding_digest(&self) -> String {
        let fields: Vec<&str> = match self {
            Self::Bearer(token) => vec!["bearer", token],
            Self::ApiKeyHeader { header, value } => vec!["api-key-header", header, value],
            Self::ApiKeyQuery { param, value } => vec!["api-key-query", param, value],
            Self::Basic { username, password } => vec!["basic", username, password],
            Self::CustomHeader { header, value } => vec!["custom-header", header, value],
            Self::None => vec!["none"],
        };
        let mut hash = blake3::Hasher::new_derive_key("leanctx.provider.credential-binding.v1");
        for field in fields {
            hash.update(&(field.len() as u64).to_le_bytes());
            hash.update(field.as_bytes());
        }
        hash.finalize().to_hex().to_string()
    }

    /// Resolve auth credentials from environment variables.
    pub fn from_config(auth: &AuthConfig) -> Result<Self, String> {
        match auth {
            AuthConfig::Bearer { token_env } => {
                let token = read_env(token_env)?;
                Ok(Self::Bearer(token))
            }
            AuthConfig::ApiKey {
                key_env,
                header_name,
                query_param,
            } => {
                let key = read_env(key_env)?;
                if let Some(header) = header_name {
                    Ok(Self::ApiKeyHeader {
                        header: header.clone(),
                        value: key,
                    })
                } else if let Some(param) = query_param {
                    Ok(Self::ApiKeyQuery {
                        param: param.clone(),
                        value: key,
                    })
                } else {
                    Ok(Self::ApiKeyHeader {
                        header: "X-Api-Key".into(),
                        value: key,
                    })
                }
            }
            AuthConfig::Basic {
                username_env,
                password_env,
            } => {
                let username = read_env(username_env)?;
                let password = read_env(password_env)?;
                Ok(Self::Basic { username, password })
            }
            AuthConfig::Header {
                header_name,
                value_env,
            } => {
                let value = read_env(value_env)?;
                Ok(Self::CustomHeader {
                    header: header_name.clone(),
                    value,
                })
            }
            AuthConfig::None => Ok(Self::None),
        }
    }

    /// Whether auth credentials could be resolved (provider is usable).
    pub fn is_available(auth: &AuthConfig) -> bool {
        match auth {
            AuthConfig::Bearer { token_env } => std::env::var(token_env).is_ok(),
            AuthConfig::ApiKey { key_env, .. } => std::env::var(key_env).is_ok(),
            AuthConfig::Basic {
                username_env,
                password_env,
            } => std::env::var(username_env).is_ok() && std::env::var(password_env).is_ok(),
            AuthConfig::Header { value_env, .. } => std::env::var(value_env).is_ok(),
            AuthConfig::None => true,
        }
    }
}

fn read_env(var: &str) -> Result<String, String> {
    std::env::var(var).map_err(|_| format!("Environment variable '{var}' not set"))
}

/// Interpolate `{param}` placeholders in a string with actual values.
pub fn interpolate(template: &str, params: &HashMap<String, String>) -> String {
    let mut result = template.to_string();
    for (key, value) in params {
        result = result.replace(&format!("{{{key}}}"), value);
    }
    // Remove unresolved placeholders (optional params not provided)
    let re = regex::Regex::new(r"\{[a-zA-Z_][a-zA-Z0-9_]*\}").expect("valid placeholder regex");
    re.replace_all(&result, "").to_string()
}

/// Build the full URL with query parameters.
fn build_url(
    base_url: &str,
    resource: &ResourceConfig,
    interp_params: &HashMap<String, String>,
    auth: &ResolvedAuth,
) -> String {
    let path = interpolate(&resource.path, interp_params);
    let base = base_url.trim_end_matches('/');
    let mut url = format!("{base}{path}");

    let mut query_parts: Vec<String> = Vec::new();
    for (key, val_template) in &resource.query_params {
        let val = interpolate(val_template, interp_params);
        if !val.is_empty() {
            query_parts.push(format!(
                "{}={}",
                urlencoding::encode(key),
                urlencoding::encode(&val)
            ));
        }
    }

    if let ResolvedAuth::ApiKeyQuery { param, value } = auth {
        query_parts.push(format!(
            "{}={}",
            urlencoding::encode(param),
            urlencoding::encode(value)
        ));
    }

    if !query_parts.is_empty() {
        url.push('?');
        url.push_str(&query_parts.join("&"));
    }

    url
}

/// Collect all headers (auth + resource-specific + Accept).
fn collect_headers(
    auth: &ResolvedAuth,
    resource_headers: &HashMap<String, String>,
) -> Vec<(String, String)> {
    let mut headers = Vec::new();

    match auth {
        ResolvedAuth::Bearer(token) => {
            headers.push(("Authorization".into(), format!("Bearer {token}")));
        }
        ResolvedAuth::ApiKeyHeader { header, value }
        | ResolvedAuth::CustomHeader { header, value } => {
            headers.push((header.clone(), value.clone()));
        }
        ResolvedAuth::Basic { username, password } => {
            let encoded = crate::core::providers::config_provider::base64_encode(
                format!("{username}:{password}").as_bytes(),
            );
            headers.push(("Authorization".into(), format!("Basic {encoded}")));
        }
        ResolvedAuth::ApiKeyQuery { .. } | ResolvedAuth::None => {}
    }

    for (key, value) in resource_headers {
        headers.push((key.clone(), value.clone()));
    }

    headers.push(("Accept".into(), "application/json".into()));
    headers
}

/// Parse the response body into JSON, checking status first.
fn parse_response(status: u16, body: &str, url: &str) -> Result<serde_json::Value, String> {
    if !(200..300).contains(&status) {
        return Err(format!(
            "API returned status {status} for {}",
            url.split('?').next().unwrap_or(url)
        ));
    }
    serde_json::from_str(body).map_err(|e| format!("Invalid JSON response: {e}"))
}

fn status_to_u16(status: ureq::http::StatusCode) -> u16 {
    status.as_u16()
}

/// Execute an HTTP request to the external API.
///
/// Only the read methods of [`super::schema::READ_METHODS`] are sent: GET, and
/// POST with an empty body (ureq 3 uses different types for body vs bodyless
/// requests). Any other method is refused before a request exists, even if
/// validation was bypassed.
pub fn execute_request(
    base_url: &str,
    resource: &ResourceConfig,
    auth: &ResolvedAuth,
    interp_params: &HashMap<String, String>,
) -> Result<serde_json::Value, String> {
    let method = resource.method.to_uppercase();
    if !super::schema::READ_METHODS.contains(&method.as_str()) {
        return Err(format!(
            "method '{}' is not a read method; connectors are read-only",
            resource.method
        ));
    }
    let url = build_url(base_url, resource, interp_params, auth);
    let headers = collect_headers(auth, &resource.headers);
    let agent = crate::core::providers::hardened_http::hardened_agent();

    let res = if method == "POST" {
        let mut req = agent.post(&url);
        for (k, v) in &headers {
            req = req.header(k, v);
        }
        req.send_empty()
    } else {
        let mut req = agent.get(&url);
        for (k, v) in &headers {
            req = req.header(k, v);
        }
        req.call()
    }
    .map_err(|e| format!("HTTP request failed: {e}"))?;
    let status = status_to_u16(res.status());
    if !(200..300).contains(&status) {
        return Err(format!("API returned status {status}"));
    }
    let body = res
        .into_body()
        .read_to_string()
        .map_err(|e| format!("Failed to read response body: {e}"))?;

    parse_response(status, &body, &url)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn interpolate_replaces_known_params() {
        let mut params = HashMap::new();
        params.insert("limit".into(), "10".into());
        params.insert("state".into(), "open".into());
        params.insert("owner".into(), "acme".into());
        assert_eq!(
            interpolate("/repos/{owner}/issues?limit={limit}&state={state}", &params),
            "/repos/acme/issues?limit=10&state=open"
        );
    }

    #[test]
    fn interpolate_removes_unresolved_placeholders() {
        let params = HashMap::new();
        assert_eq!(
            interpolate("/items?filter={filter}", &params),
            "/items?filter="
        );
    }

    #[test]
    fn build_url_with_query_params() {
        let resource = ResourceConfig {
            method: "GET".into(),
            path: "/issues".into(),
            query_params: {
                let mut m = HashMap::new();
                m.insert("state".into(), "{state}".into());
                m.insert("per_page".into(), "{limit}".into());
                m
            },
            headers: HashMap::new(),
            response: super::super::schema::ResponseConfig {
                root: None,
                mapping: super::super::schema::FieldMapping {
                    id: "id".into(),
                    title: "title".into(),
                    body: None,
                    state: None,
                    author: None,
                    url: None,
                    labels: None,
                    created_at: None,
                    updated_at: None,
                },
            },
        };
        let mut params = HashMap::new();
        params.insert("state".into(), "open".into());
        params.insert("limit".into(), "25".into());

        let url = build_url(
            "https://api.example.com",
            &resource,
            &params,
            &ResolvedAuth::None,
        );
        assert!(url.starts_with("https://api.example.com/issues?"));
        assert!(url.contains("state=open"));
        assert!(url.contains("per_page=25"));
    }

    /// A write method never becomes a request, even on a config that skipped
    /// validation: the refusal comes before any URL is built or sent (the
    /// unroutable host would otherwise give a transport error).
    #[test]
    fn write_methods_are_refused_before_any_request() {
        for method in ["PUT", "PATCH", "DELETE", "delete"] {
            let resource = ResourceConfig {
                method: method.into(),
                path: "/items".into(),
                query_params: HashMap::new(),
                headers: HashMap::new(),
                response: super::super::schema::ResponseConfig {
                    root: None,
                    mapping: super::super::schema::FieldMapping {
                        id: "id".into(),
                        title: "title".into(),
                        body: None,
                        state: None,
                        author: None,
                        url: None,
                        labels: None,
                        created_at: None,
                        updated_at: None,
                    },
                },
            };
            let err = execute_request(
                "https://unroutable.invalid",
                &resource,
                &ResolvedAuth::None,
                &HashMap::new(),
            )
            .unwrap_err();
            assert!(err.contains("connectors are read-only"), "{method}: {err}");
        }
    }

    #[test]
    fn build_url_with_api_key_query() {
        let resource = ResourceConfig {
            method: "GET".into(),
            path: "/data".into(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            response: super::super::schema::ResponseConfig {
                root: None,
                mapping: super::super::schema::FieldMapping {
                    id: "id".into(),
                    title: "name".into(),
                    body: None,
                    state: None,
                    author: None,
                    url: None,
                    labels: None,
                    created_at: None,
                    updated_at: None,
                },
            },
        };
        let auth = ResolvedAuth::ApiKeyQuery {
            param: "api_key".into(),
            value: "secret123".into(),
        };
        let url = build_url("https://api.example.com", &resource, &HashMap::new(), &auth);
        assert!(url.contains("api_key=secret123"));
    }

    #[test]
    fn resolved_auth_none_always_available() {
        assert!(ResolvedAuth::is_available(&AuthConfig::None));
    }

    #[test]
    fn resolved_auth_bearer_unavailable_without_env() {
        let auth = AuthConfig::Bearer {
            token_env: "LEAN_CTX_TEST_NONEXISTENT_TOKEN_12345".into(),
        };
        assert!(!ResolvedAuth::is_available(&auth));
    }
}