Skip to main content

lean_ctx/core/providers/
gitlab.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use super::config::GitLabConfig;
4use super::provider_trait::{ContextProvider, ProviderParams};
5use super::{ProviderItem, ProviderResult};
6
7const DEFAULT_PER_PAGE: usize = 20;
8
9fn push_filter(url: &mut String, key: &str, value: &str) {
10    let value = urlencoding::encode(value);
11    url.push_str(&format!("&{key}={value}"));
12}
13
14fn issues_endpoint(
15    encoded_project: &str,
16    per_page: usize,
17    state: Option<&str>,
18    labels: Option<&str>,
19) -> String {
20    let mut url = format!(
21        "/projects/{encoded_project}/issues?per_page={per_page}&order_by=updated_at&sort=desc"
22    );
23    if let Some(s) = state {
24        push_filter(&mut url, "state", s);
25    }
26    if let Some(l) = labels {
27        push_filter(&mut url, "labels", l);
28    }
29    url
30}
31
32fn merge_requests_endpoint(encoded_project: &str, per_page: usize, state: Option<&str>) -> String {
33    let mut url = format!(
34        "/projects/{encoded_project}/merge_requests?per_page={per_page}&order_by=updated_at&sort=desc"
35    );
36    if let Some(s) = state {
37        push_filter(&mut url, "state", s);
38    }
39    url
40}
41
42fn pipelines_endpoint(encoded_project: &str, per_page: usize, status: Option<&str>) -> String {
43    let mut url = format!(
44        "/projects/{encoded_project}/pipelines?per_page={per_page}&order_by=updated_at&sort=desc"
45    );
46    if let Some(s) = status {
47        push_filter(&mut url, "status", s);
48    }
49    url
50}
51
52pub fn list_issues(
53    config: &GitLabConfig,
54    state: Option<&str>,
55    labels: Option<&str>,
56    limit: Option<usize>,
57) -> Result<ProviderResult, String> {
58    let project = config
59        .project_path
60        .as_deref()
61        .ok_or("No project path configured. Set CI_PROJECT_PATH or configure git remote.")?;
62    let encoded = urlencoding::encode(project);
63    let per_page = limit.unwrap_or(DEFAULT_PER_PAGE).min(100);
64
65    let url = issues_endpoint(&encoded, per_page, state, labels);
66
67    // A cached response is not evidence of current source authorization. Ask
68    // GitLab on every acquisition, including after a token or membership revoke.
69    let body = api_get(config, &url)?;
70    let items: Vec<serde_json::Value> =
71        serde_json::from_str(&body).map_err(|e| format!("JSON parse error: {e}"))?;
72
73    let result = ProviderResult {
74        provider: "gitlab".to_string(),
75        resource_type: "issues".to_string(),
76        total_count: None,
77        truncated: items.len() >= per_page,
78        items: items.iter().map(parse_issue).collect(),
79    };
80
81    Ok(result)
82}
83
84pub fn show_issue(config: &GitLabConfig, iid: u64) -> Result<ProviderResult, String> {
85    let project = config
86        .project_path
87        .as_deref()
88        .ok_or("No project path configured.")?;
89    let encoded = urlencoding::encode(project);
90    let url = format!("/projects/{encoded}/issues/{iid}");
91
92    let body = api_get(config, &url)?;
93    let issue: serde_json::Value =
94        serde_json::from_str(&body).map_err(|e| format!("JSON parse error: {e}"))?;
95
96    Ok(ProviderResult {
97        provider: "gitlab".to_string(),
98        resource_type: "issue".to_string(),
99        total_count: Some(1),
100        truncated: false,
101        items: vec![parse_issue(&issue)],
102    })
103}
104
105pub fn list_mrs(
106    config: &GitLabConfig,
107    state: Option<&str>,
108    limit: Option<usize>,
109) -> Result<ProviderResult, String> {
110    let project = config
111        .project_path
112        .as_deref()
113        .ok_or("No project path configured.")?;
114    let encoded = urlencoding::encode(project);
115    let per_page = limit.unwrap_or(DEFAULT_PER_PAGE).min(100);
116
117    let url = merge_requests_endpoint(&encoded, per_page, state);
118
119    // Use the same fresh authorization boundary as issues, not stale cache data.
120    let body = api_get(config, &url)?;
121    let items: Vec<serde_json::Value> =
122        serde_json::from_str(&body).map_err(|e| format!("JSON parse error: {e}"))?;
123
124    let result = ProviderResult {
125        provider: "gitlab".to_string(),
126        resource_type: "merge_requests".to_string(),
127        total_count: None,
128        truncated: items.len() >= per_page,
129        items: items.iter().map(parse_mr).collect(),
130    };
131
132    Ok(result)
133}
134
135pub fn list_pipelines(
136    config: &GitLabConfig,
137    status: Option<&str>,
138    limit: Option<usize>,
139) -> Result<ProviderResult, String> {
140    let project = config
141        .project_path
142        .as_deref()
143        .ok_or("No project path configured.")?;
144    let encoded = urlencoding::encode(project);
145    let per_page = limit.unwrap_or(DEFAULT_PER_PAGE).min(100);
146
147    let url = pipelines_endpoint(&encoded, per_page, status);
148
149    let body = api_get(config, &url)?;
150    let items: Vec<serde_json::Value> =
151        serde_json::from_str(&body).map_err(|e| format!("JSON parse error: {e}"))?;
152
153    Ok(ProviderResult {
154        provider: "gitlab".to_string(),
155        resource_type: "pipelines".to_string(),
156        total_count: None,
157        truncated: items.len() >= per_page,
158        items: items
159            .iter()
160            .map(|p| ProviderItem {
161                id: p["id"].as_u64().unwrap_or(0).to_string(),
162                title: p["ref"].as_str().unwrap_or("").to_string(),
163                state: p["status"].as_str().map(std::string::ToString::to_string),
164                author: None,
165                created_at: p["created_at"]
166                    .as_str()
167                    .map(std::string::ToString::to_string),
168                updated_at: p["updated_at"]
169                    .as_str()
170                    .map(std::string::ToString::to_string),
171                url: p["web_url"].as_str().map(std::string::ToString::to_string),
172                labels: Vec::new(),
173                body: None,
174                ..Default::default()
175            })
176            .collect(),
177    })
178}
179
180pub struct GitLabProvider {
181    config: Result<GitLabConfig, String>,
182}
183
184impl GitLabProvider {
185    pub fn new() -> Self {
186        Self {
187            config: GitLabConfig::from_session(),
188        }
189    }
190
191    /// Construct with an explicit config, bypassing env discovery. Used by the
192    /// hosted team server's managed connectors so each scheduled run carries its
193    /// own credential without mutating process-global env (which would race
194    /// across connectors).
195    #[must_use]
196    pub fn with_config(config: GitLabConfig) -> Self {
197        Self { config: Ok(config) }
198    }
199}
200
201impl Default for GitLabProvider {
202    fn default() -> Self {
203        Self::new()
204    }
205}
206
207impl ContextProvider for GitLabProvider {
208    fn id(&self) -> &'static str {
209        "gitlab"
210    }
211
212    fn display_name(&self) -> &'static str {
213        "GitLab"
214    }
215
216    fn supported_actions(&self) -> &[&str] {
217        &["issues", "merge_requests", "pipelines"]
218    }
219
220    fn execute(&self, action: &str, params: &ProviderParams) -> Result<ProviderResult, String> {
221        super::selected_gitlab::check_project(params.project.as_deref())?;
222        let config = self.config.as_ref().map_err(std::clone::Clone::clone)?;
223        match action {
224            "issues" => list_issues(config, params.state.as_deref(), None, params.limit),
225            "merge_requests" | "mrs" => list_mrs(config, params.state.as_deref(), params.limit),
226            "pipelines" => list_pipelines(config, params.state.as_deref(), params.limit),
227            _ => Err(format!("Unknown GitLab action: {action}")),
228        }
229    }
230
231    fn cache_ttl_secs(&self) -> u64 {
232        0
233    }
234
235    fn reuse_binding(&self, action: &str, params: &ProviderParams) -> Option<String> {
236        if !matches!(action, "issues" | "merge_requests") {
237            return None;
238        }
239        super::selected_gitlab::check_project(params.project.as_deref()).ok()?;
240        super::selected_gitlab::reuse_binding(self.config.as_ref().ok()?)
241    }
242
243    fn reacquire_item(
244        &self,
245        action: &str,
246        params: &ProviderParams,
247        item_id: &str,
248    ) -> Result<ProviderResult, String> {
249        if self.reuse_binding(action, params).is_none() {
250            return Err("selected source is unavailable for item reauthorization".into());
251        }
252        let id: u64 = item_id
253            .parse()
254            .map_err(|_| "invalid stored GitLab item ID")?;
255        if id == 0 || id.to_string() != item_id {
256            return Err("invalid stored GitLab item ID".into());
257        }
258        let config = self.config.as_ref().map_err(Clone::clone)?;
259        let project = config
260            .project_path
261            .as_deref()
262            .ok_or("selected project missing")?;
263        let endpoint = format!("/projects/{}/{action}/{id}", urlencoding::encode(project));
264        let body = api_get(config, &endpoint)?;
265        let value = serde_json::from_str(&body).map_err(|_| "invalid GitLab item response")?;
266        let item = match action {
267            "issues" => parse_issue(&value),
268            "merge_requests" => parse_mr(&value),
269            _ => return Err("unsupported stored GitLab resource".into()),
270        };
271        Ok(ProviderResult {
272            provider: "gitlab".into(),
273            resource_type: action.into(),
274            items: vec![item],
275            total_count: Some(1),
276            truncated: false,
277        })
278    }
279
280    fn is_available(&self) -> bool {
281        self.config.is_ok()
282    }
283}
284
285fn api_get(config: &GitLabConfig, endpoint: &str) -> Result<String, String> {
286    super::selected_gitlab::authorize(config)?;
287    let url = config.api_url(endpoint);
288    super::hardened_http::provider_get_with_headers(
289        "gitlab",
290        &url,
291        &[("PRIVATE-TOKEN", config.token.as_str())],
292    )
293    .into_body()
294    .map_err(|e| format!("GitLab API error: {e}"))
295}
296
297fn parse_issue(v: &serde_json::Value) -> ProviderItem {
298    ProviderItem {
299        id: v["iid"].as_u64().unwrap_or(0).to_string(),
300        title: v["title"].as_str().unwrap_or("").to_string(),
301        state: v["state"].as_str().map(std::string::ToString::to_string),
302        author: v["author"]["username"]
303            .as_str()
304            .map(std::string::ToString::to_string),
305        created_at: v["created_at"]
306            .as_str()
307            .map(std::string::ToString::to_string),
308        updated_at: v["updated_at"]
309            .as_str()
310            .map(std::string::ToString::to_string),
311        url: v["web_url"].as_str().map(std::string::ToString::to_string),
312        labels: v["labels"]
313            .as_array()
314            .map(|arr| {
315                arr.iter()
316                    .filter_map(|l| l.as_str().map(std::string::ToString::to_string))
317                    .collect()
318            })
319            .unwrap_or_default(),
320        body: v["description"]
321            .as_str()
322            .map(std::string::ToString::to_string),
323        ..Default::default()
324    }
325}
326
327fn parse_mr(v: &serde_json::Value) -> ProviderItem {
328    ProviderItem {
329        id: v["iid"].as_u64().unwrap_or(0).to_string(),
330        title: v["title"].as_str().unwrap_or("").to_string(),
331        state: v["state"].as_str().map(std::string::ToString::to_string),
332        author: v["author"]["username"]
333            .as_str()
334            .map(std::string::ToString::to_string),
335        created_at: v["created_at"]
336            .as_str()
337            .map(std::string::ToString::to_string),
338        updated_at: v["updated_at"]
339            .as_str()
340            .map(std::string::ToString::to_string),
341        url: v["web_url"].as_str().map(std::string::ToString::to_string),
342        labels: v["labels"]
343            .as_array()
344            .map(|arr| {
345                arr.iter()
346                    .filter_map(|l| l.as_str().map(std::string::ToString::to_string))
347                    .collect()
348            })
349            .unwrap_or_default(),
350        body: v["description"]
351            .as_str()
352            .map(std::string::ToString::to_string),
353        ..Default::default()
354    }
355}
356
357#[cfg(test)]
358mod authorization_tests;
359
360#[cfg(test)]
361mod tests {
362    use super::{issues_endpoint, merge_requests_endpoint, pipelines_endpoint};
363
364    /// Split the query half of an endpoint into raw `key=value` pairs the way a
365    /// server's query parser would: on `&`, then on the first `=`. Values are left
366    /// percent-encoded so the tests can assert on the wire form.
367    fn query_pairs(endpoint: &str) -> Vec<(String, String)> {
368        let query = endpoint.split_once('?').expect("endpoint has a query").1;
369        query
370            .split('&')
371            .map(|pair| {
372                let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
373                (key.to_owned(), value.to_owned())
374            })
375            .collect()
376    }
377
378    fn value_of(endpoint: &str, key: &str) -> Option<String> {
379        query_pairs(endpoint)
380            .into_iter()
381            .find(|(k, _)| k == key)
382            .map(|(_, v)| v)
383    }
384
385    fn keys_of(endpoint: &str) -> Vec<String> {
386        query_pairs(endpoint).into_iter().map(|(k, _)| k).collect()
387    }
388
389    /// The filter value a caller passed must survive as exactly one query value.
390    fn assert_round_trips(endpoint: &str, key: &str, original: &str) {
391        let encoded = value_of(endpoint, key).expect("filter parameter present");
392        let decoded = urlencoding::decode(&encoded).expect("value is valid percent-encoding");
393        assert_eq!(
394            decoded, original,
395            "filter {key} must decode back to the caller's exact value"
396        );
397    }
398
399    #[test]
400    fn plain_filters_keep_their_literal_form() {
401        let endpoint = issues_endpoint("group%2Fproject", 20, Some("opened"), Some("bug,urgent"));
402        assert_eq!(value_of(&endpoint, "state").as_deref(), Some("opened"));
403        // Comma is percent-encoded on the wire but still decodes to a label list.
404        assert_round_trips(&endpoint, "labels", "bug,urgent");
405        assert_eq!(value_of(&endpoint, "per_page").as_deref(), Some("20"));
406        assert_eq!(
407            value_of(&endpoint, "order_by").as_deref(),
408            Some("updated_at")
409        );
410        assert_eq!(value_of(&endpoint, "sort").as_deref(), Some("desc"));
411    }
412
413    #[test]
414    fn absent_filters_add_no_parameters() {
415        assert_eq!(
416            keys_of(&issues_endpoint("p", 20, None, None)),
417            ["per_page", "order_by", "sort"]
418        );
419        assert_eq!(
420            keys_of(&merge_requests_endpoint("p", 20, None)),
421            ["per_page", "order_by", "sort"]
422        );
423        assert_eq!(
424            keys_of(&pipelines_endpoint("p", 20, None)),
425            ["per_page", "order_by", "sort"]
426        );
427    }
428
429    #[test]
430    fn ampersand_in_issue_state_cannot_inject_a_parameter() {
431        let hostile = "opened&per_page=100";
432        let endpoint = issues_endpoint("p", 20, Some(hostile), None);
433        assert_eq!(
434            keys_of(&endpoint),
435            ["per_page", "order_by", "sort", "state"],
436            "hostile filter must not add a query parameter"
437        );
438        assert_eq!(value_of(&endpoint, "per_page").as_deref(), Some("20"));
439        assert_round_trips(&endpoint, "state", hostile);
440    }
441
442    #[test]
443    fn ampersand_in_labels_cannot_inject_a_parameter() {
444        let hostile = "bug&state=closed";
445        let endpoint = issues_endpoint("p", 20, None, Some(hostile));
446        assert_eq!(
447            keys_of(&endpoint),
448            ["per_page", "order_by", "sort", "labels"]
449        );
450        assert_round_trips(&endpoint, "labels", hostile);
451    }
452
453    #[test]
454    fn ampersand_in_mr_state_cannot_inject_a_parameter() {
455        let hostile = "opened&per_page=100";
456        let endpoint = merge_requests_endpoint("p", 20, Some(hostile));
457        assert_eq!(
458            keys_of(&endpoint),
459            ["per_page", "order_by", "sort", "state"]
460        );
461        assert_eq!(value_of(&endpoint, "per_page").as_deref(), Some("20"));
462        assert_round_trips(&endpoint, "state", hostile);
463    }
464
465    #[test]
466    fn ampersand_in_pipeline_status_cannot_inject_a_parameter() {
467        let hostile = "success&ref=main";
468        let endpoint = pipelines_endpoint("p", 20, Some(hostile));
469        assert_eq!(
470            keys_of(&endpoint),
471            ["per_page", "order_by", "sort", "status"]
472        );
473        assert_round_trips(&endpoint, "status", hostile);
474    }
475
476    #[test]
477    fn fragment_marker_cannot_truncate_the_query() {
478        let hostile = "opened#frag";
479        let endpoint = issues_endpoint("p", 20, Some(hostile), None);
480        assert!(
481            !endpoint.contains('#'),
482            "a literal '#' would make the rest of the query a fragment: {endpoint}"
483        );
484        assert_round_trips(&endpoint, "state", hostile);
485    }
486
487    #[test]
488    fn reserved_characters_stay_inside_one_value() {
489        for original in [
490            "opened=closed",
491            "needs review",
492            "rust+lang",
493            "a=b&c=d#e f",
494            "50%",
495        ] {
496            let endpoint = issues_endpoint("p", 20, Some(original), None);
497            assert_eq!(
498                keys_of(&endpoint),
499                ["per_page", "order_by", "sort", "state"],
500                "value {original:?} must stay one parameter"
501            );
502            assert_round_trips(&endpoint, "state", original);
503        }
504    }
505
506    #[test]
507    fn literal_plus_is_not_decoded_as_a_space() {
508        // `+` means space in form decoding, so it must go out as %2B to survive.
509        let endpoint = issues_endpoint("p", 20, Some("rust+lang"), None);
510        assert_eq!(value_of(&endpoint, "state").as_deref(), Some("rust%2Blang"));
511        assert_round_trips(&endpoint, "state", "rust+lang");
512    }
513
514    #[test]
515    fn space_is_percent_encoded_not_left_raw() {
516        let endpoint = issues_endpoint("p", 20, Some("needs review"), None);
517        assert!(
518            !endpoint.contains(' '),
519            "a raw space would break the HTTP request line: {endpoint}"
520        );
521        assert_eq!(
522            value_of(&endpoint, "state").as_deref(),
523            Some("needs%20review")
524        );
525    }
526
527    #[test]
528    fn unicode_filter_values_round_trip() {
529        for original in ["priorität:hoch", "标签", "naïve café", "🙂"] {
530            let endpoint = issues_endpoint("p", 20, None, Some(original));
531            assert!(endpoint.is_ascii(), "wire form must be ASCII: {endpoint}");
532            assert_round_trips(&endpoint, "labels", original);
533        }
534    }
535
536    #[test]
537    fn project_path_stays_encoded_alongside_filters() {
538        let endpoint = issues_endpoint(
539            &urlencoding::encode("group/sub/project"),
540            50,
541            Some("opened"),
542            None,
543        );
544        assert!(endpoint.starts_with("/projects/group%2Fsub%2Fproject/issues?"));
545        assert_eq!(value_of(&endpoint, "per_page").as_deref(), Some("50"));
546    }
547}