1#![doc = include_str!("../README.md")]
11#![forbid(unsafe_code)]
12#![warn(missing_docs)]
13
14ai6::guatiao::providers!(Gitlab);
15
16use std::collections::BTreeMap;
17use std::path::PathBuf;
18use std::sync::Mutex;
19use std::time::{Duration, Instant};
20
21use ai6::guatiao::library::ProviderError;
22use ai6::guatiao::{FromValue, Provider, Schema, Status, ToValue};
23use ai6::{
24 IssueSpec, PostedComment, Reply, ReplyBatch, ReplyPoll, Source, SourceBatch, SourceFacts,
25 SourceItem, SourcePoll, Tracker, TrackerCapabilities, TrackerIssue, TrackerLink, TrackerPost,
26 TrackerUpdate, settled_cursor,
27};
28use serde::{Deserialize, Serialize};
29use url::Url;
30
31pub const PROVIDER_ID: &str = "gitlab";
33
34const MARKER_PREFIX: &str = "<!-- ai6:";
36
37#[derive(Debug, Clone, ToValue, FromValue, Schema)]
42#[map(crate = ::ai6::guatiao, deny_unknown_fields)]
43pub struct Settings {
44 #[schema(title = "Project")]
46 #[map(default)]
47 project: String,
48 #[schema(title = "Target")]
50 target: Option<String>,
51 #[schema(title = "Intake labels")]
53 #[map(default = vec!["ai6:ready".to_owned()])]
54 labels: Vec<String>,
55 #[schema(title = "Assignee")]
57 assignee: Option<String>,
58 #[schema(
60 title = "Token variable",
61 format = "credential-variable:GITLAB_TOKEN,GITLAB_ACCESS_TOKEN"
62 )]
63 #[map(default = "GITLAB_TOKEN".to_owned())]
64 token_env: String,
65 #[schema(title = "API address")]
67 #[map(default = "https://gitlab.com/api/v4".to_owned())]
68 api_url: String,
69 #[schema(title = "Certificate authorities")]
72 ca_file: Option<PathBuf>,
73 #[schema(title = "A request may take", format = "seconds")]
75 #[map(default = 30)]
76 request_timeout_secs: u64,
77 #[schema(title = "Items per page")]
79 #[map(default = 100)]
80 page_size: u32,
81 #[schema(title = "Pages per listing")]
83 #[map(default = 5)]
84 max_pages: u64,
85 #[schema(title = "Search behind the cursor by", format = "seconds")]
89 #[map(default = 120)]
90 settling_secs: u64,
91 #[schema(title = "People who may answer")]
94 #[map(default)]
95 reply_authors: Vec<String>,
96 #[schema(title = "Least access that may answer")]
99 #[map(default = 30)]
100 reply_min_access: u64,
101 #[schema(title = "Remember the project for", format = "seconds")]
103 #[map(default = 600)]
104 capability_ttl_secs: u64,
105 #[schema(title = "Board address")]
108 board_url: Option<String>,
109}
110
111#[derive(Debug, Provider)]
113#[provider(
114 Source,
115 Tracker,
116 id = "gitlab",
117 name = "GitLab issues",
118 config = Settings,
119 crate = ::ai6::guatiao
120)]
121pub struct Gitlab {
122 settings: Settings,
123 api: Url,
124 agent: ureq::Agent,
125 capabilities: Mutex<Option<(Instant, TrackerCapabilities)>>,
127}
128
129impl Gitlab {
130 pub fn new(mut settings: Settings) -> Result<Self, String> {
137 if let Some(target) = settings.target.take() {
138 if !settings.project.is_empty() {
139 return Err("set `project` or `target`, not both".to_owned());
140 }
141 settings.project = target;
142 }
143 let valid_part = |part: &str| {
144 !part.is_empty()
145 && !part.starts_with('.')
146 && part
147 .chars()
148 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
149 };
150 let parts: Vec<&str> = settings.project.split('/').collect();
151 if parts.len() < 2 || !parts.iter().all(|part| valid_part(part)) {
152 return Err("project must be `group/name` or `group/subgroup/name`".to_owned());
153 }
154 if settings.token_env.trim().is_empty() {
155 return Err("token_env must name an environment variable".to_owned());
156 }
157 let api = Url::parse(settings.api_url.trim_end_matches('/'))
158 .map_err(|e| format!("api_url: {e}"))?;
159 let loopback = matches!(api.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"));
160 if api.scheme() != "https" && !(api.scheme() == "http" && loopback) {
161 return Err("api_url must be https (http only on a loopback address)".to_owned());
162 }
163 if let Some(board) = &settings.board_url {
164 https_page(board).map_err(|e| format!("board_url: {e}"))?;
165 }
166 for (name, zero) in [
167 ("request_timeout_secs", settings.request_timeout_secs == 0),
168 ("page_size", settings.page_size == 0),
169 ("max_pages", settings.max_pages == 0),
170 ] {
171 if zero {
172 return Err(format!("{name} must be at least 1"));
173 }
174 }
175 let mut agent = ureq::Agent::config_builder()
176 .timeout_global(Some(Duration::from_secs(settings.request_timeout_secs)))
177 .max_redirects(0)
178 .http_status_as_error(false);
179 if let Some(ca_file) = &settings.ca_file {
180 agent = agent.tls_config(ai6::tls::trusting_file(ca_file)?);
181 }
182 let agent = agent.build().into();
183 Ok(Self {
184 settings,
185 api,
186 agent,
187 capabilities: Mutex::new(None),
188 })
189 }
190
191 fn endpoint(&self, path: &str) -> String {
192 format!("{}{path}", self.api.as_str().trim_end_matches('/'))
193 }
194
195 fn graphql_url(&self) -> String {
197 let mut api = self.api.clone();
198 if !api.path().ends_with('/') {
199 api.set_path(&format!("{}/", api.path()));
200 }
201 api.join("../graphql")
202 .map_or_else(|_| self.endpoint("/graphql"), |url| url.to_string())
203 }
204
205 fn web_project(&self) -> Option<String> {
208 let api = self.api.as_str().trim_end_matches('/');
209 api.strip_suffix("/api/v4")
210 .map(|web| format!("{web}/{}", self.settings.project))
211 }
212
213 fn token(&self) -> Option<String> {
214 std::env::var(&self.settings.token_env)
215 .ok()
216 .filter(|token| !token.trim().is_empty())
217 }
218
219 fn send<B: Serialize + ?Sized>(
222 &self,
223 method: &str,
224 url: &str,
225 query: &[(&str, String)],
226 body: Option<&B>,
227 ) -> Result<ureq::http::Response<ureq::Body>, ProviderError> {
228 let mut url = Url::parse(url).map_err(|e| failure(&format!("bad address: {e}")))?;
229 for (key, value) in query {
230 url.query_pairs_mut().append_pair(key, value);
231 }
232 let mut request = ureq::http::Request::builder()
233 .method(method)
234 .uri(url.as_str())
235 .header("Accept", "application/json")
236 .header("User-Agent", "ai6-source-gitlab");
237 match self.token() {
238 Some(token) => request = request.header("PRIVATE-TOKEN", token),
239 None if method != "GET" => {
240 return Err(failure(&format!(
241 "no token: set the environment variable {}",
242 self.settings.token_env
243 )));
244 }
245 None => {}
246 }
247 let bytes = match body {
248 Some(body) => {
249 request = request.header("Content-Type", "application/json");
250 serde_json::to_vec(body).map_err(|e| failure(&e.to_string()))?
251 }
252 None => Vec::new(),
253 };
254 let request = request
255 .body(bytes)
256 .map_err(|e| failure(&format!("bad request: {e}")))?;
257 self.agent
258 .run(request)
259 .map_err(|e| failure(&format!("request failed: {e}")))
260 }
261
262 fn call<B: Serialize + ?Sized>(
264 &self,
265 method: &str,
266 url: &str,
267 query: &[(&str, String)],
268 body: Option<&B>,
269 ) -> Result<ureq::http::Response<ureq::Body>, ProviderError> {
270 let response = self.send(method, url, query, body)?;
271 self.check(&response)?;
272 Ok(response)
273 }
274
275 fn get(
276 &self,
277 url: &str,
278 query: &[(&str, String)],
279 ) -> Result<ureq::http::Response<ureq::Body>, ProviderError> {
280 self.call("GET", url, query, None::<&()>)
281 }
282
283 fn get_json<T: serde::de::DeserializeOwned>(
284 &self,
285 url: &str,
286 query: &[(&str, String)],
287 ) -> Result<T, ProviderError> {
288 read_json(self.get(url, query)?)
289 }
290
291 fn check(&self, response: &ureq::http::Response<ureq::Body>) -> Result<(), ProviderError> {
292 let status = response.status().as_u16();
293 let header = |name: &str| {
294 response
295 .headers()
296 .get(name)
297 .and_then(|value| value.to_str().ok())
298 };
299 match status {
300 200..=299 => Ok(()),
301 429 => Err(failure(&format!(
302 "GitLab rate limit reached; retry after {}s",
303 header("retry-after").unwrap_or("60")
304 ))),
305 401 => Err(failure(&format!(
306 "GitLab refused the token in {}",
307 self.settings.token_env
308 ))),
309 403 => Err(failure(&format!(
310 "GitLab does not let the token in {} do this",
311 self.settings.token_env
312 ))),
313 404 if self.token().is_none() => Err(failure(&format!(
315 "GitLab does not show this project or issue without a token: \
316 set the environment variable {}",
317 self.settings.token_env
318 ))),
319 404 => Err(failure(
320 "GitLab does not show this project or issue to the token",
321 )),
322 400 | 422 => Err(failure("GitLab rejected the request as invalid")),
323 other => Err(failure(&format!("GitLab answered status {other}"))),
324 }
325 }
326
327 fn project_url(&self) -> String {
328 self.endpoint(&format!(
329 "/projects/{}",
330 encode_segment(&self.settings.project)
331 ))
332 }
333
334 fn issues_url(&self) -> String {
335 format!("{}/issues", self.project_url())
336 }
337
338 fn iid(&self, item: &str) -> Result<u64, ProviderError> {
341 let (project, iid) = item
342 .rsplit_once('#')
343 .ok_or_else(|| bad_value(&format!("{item:?} is not an issue ID like group/name#1")))?;
344 let iid = iid
345 .parse::<u64>()
346 .map_err(|_| bad_value(&format!("{item:?} has no issue number")))?;
347 if !project.eq_ignore_ascii_case(&self.settings.project) {
348 return Err(bad_value(&format!(
349 "foreign item {item:?}: this instance serves {}",
350 self.settings.project
351 )));
352 }
353 Ok(iid)
354 }
355
356 fn issue_url(&self, iid: u64) -> String {
357 format!("{}/{iid}", self.issues_url())
358 }
359
360 fn item_id(&self, iid: u64) -> String {
361 format!("{}#{iid}", self.settings.project)
362 }
363
364 fn pages<T: serde::de::DeserializeOwned>(
367 &self,
368 url: &str,
369 query: &[(&str, String)],
370 mut keep_going: impl FnMut(&[T]) -> bool,
371 ) -> Result<(Vec<T>, bool), ProviderError> {
372 let mut url = url.to_owned();
373 let mut first = true;
374 let mut items = Vec::new();
375 let mut more = false;
376 for _ in 0..self.settings.max_pages {
377 let response = self.get(&url, if first { query } else { &[] })?;
378 first = false;
379 let next = next_link(response.headers().get("link").and_then(|v| v.to_str().ok()))
380 .filter(|next| same_origin(next, &self.api));
381 let exhausted = response
382 .headers()
383 .get("ratelimit-remaining")
384 .and_then(|value| value.to_str().ok())
385 == Some("0");
386 let page: Vec<T> = read_json(response)?;
387 let go_on = keep_going(&page);
388 items.extend(page);
389 more = next.is_some();
390 match next {
391 Some(next) if go_on && !exhausted => url = next,
392 _ => break,
393 }
394 }
395 Ok((items, more))
396 }
397
398 fn token_writes(&self) -> bool {
402 let Ok(token) =
403 self.get_json::<TokenSelfDto>(&self.endpoint("/personal_access_tokens/self"), &[])
404 else {
405 return true;
406 };
407 token
408 .scopes
409 .is_none_or(|scopes| scopes.iter().any(|scope| scope == "api"))
410 }
411
412 fn project_capabilities(&self) -> Result<TrackerCapabilities, ProviderError> {
413 let ttl = Duration::from_secs(self.settings.capability_ttl_secs);
414 if let Ok(cache) = self.capabilities.lock()
415 && let Some((at, capabilities)) = cache.as_ref()
416 && at.elapsed() < ttl
417 {
418 return Ok(capabilities.clone());
419 }
420 let project: ProjectDto = self.get_json(&self.project_url(), &[])?;
421 let visibility = match project.visibility.as_deref() {
423 Some("private") => "private",
424 Some("public") => "public",
425 _ => "unknown",
426 };
427 let (labels, _) = self.pages::<LabelDto>(
428 &format!("{}/labels", self.project_url()),
429 &[("per_page", self.settings.page_size.to_string())],
430 |_| true,
431 )?;
432 let labels = labels.into_iter().map(|label| label.name).collect();
433 let issues_enabled = project.issues_enabled.unwrap_or(true)
434 && project.issues_access_level.as_deref() != Some("disabled");
435 let writes = self.token_writes();
436 let capabilities = TrackerCapabilities {
437 comment: writes,
438 edit_comment: writes,
439 labels,
440 free_labels: false,
441 transitions: Vec::new(),
442 assign: writes,
443 close: writes,
444 create: issues_enabled && writes,
445 issue_types: Vec::new(),
446 priorities: Vec::new(),
447 children: "subtasks".to_owned(),
448 links: vec!["issue_links".to_owned()],
449 replies: true,
450 visibility: visibility.to_owned(),
451 markers: true,
452 };
453 if let Ok(mut cache) = self.capabilities.lock() {
454 *cache = Some((Instant::now(), capabilities.clone()));
455 }
456 Ok(capabilities)
457 }
458
459 fn graphql<V: Serialize, D: serde::de::DeserializeOwned>(
461 &self,
462 query: &str,
463 variables: V,
464 ) -> Result<Option<D>, ProviderError> {
465 let answer: GraphqlResponse<D> = read_json(self.call(
466 "POST",
467 &self.graphql_url(),
468 &[],
469 Some(&GraphqlRequest { query, variables }),
470 )?)?;
471 if answer.errors.is_some_and(|errors| !errors.is_empty()) {
472 return Err(failure("GitLab refused the GraphQL request"));
473 }
474 Ok(answer.data)
475 }
476
477 fn parent_of(&self, iid: u64) -> Option<String> {
479 let answer: ParentQueryData = self
480 .graphql(
481 "query($path: ID!, $iid: String!) { project(fullPath: $path) { \
482 workItems(iid: $iid) { nodes { widgets { \
483 ... on WorkItemWidgetHierarchy { parent { iid namespace { fullPath } } } } } } } }",
484 ParentQueryVariables {
485 path: &self.settings.project,
486 iid: iid.to_string(),
487 },
488 )
489 .ok()??;
490 let nodes = answer.project?.work_items?.nodes?;
491 let widgets = nodes.into_iter().next()?.widgets?;
492 widgets.into_iter().find_map(|widget| {
493 let parent = widget.parent?;
494 let iid = parent.iid?;
495 let path = parent
496 .namespace
497 .and_then(|ns| ns.full_path)
498 .unwrap_or_else(|| self.settings.project.clone());
499 Some(format!("{path}#{iid}"))
500 })
501 }
502
503 fn attach(&self, child: u64, parent: u64) -> Result<(), ProviderError> {
505 let answer: Option<AttachData> = self.graphql(
506 "mutation($id: WorkItemID!, $parent: WorkItemID!) { workItemUpdate(input: \
507 {id: $id, hierarchyWidget: {parentId: $parent}}) { errors } }",
508 AttachVariables {
509 id: format!("gid://gitlab/WorkItem/{child}"),
510 parent: format!("gid://gitlab/WorkItem/{parent}"),
511 },
512 )?;
513 let refused = answer
514 .and_then(|data| data.work_item_update)
515 .and_then(|update| update.errors)
516 .is_none_or(|errors| !errors.is_empty());
517 if refused {
518 return Err(failure("GitLab refused to attach the child"));
519 }
520 Ok(())
521 }
522
523 fn member_id(&self, username: &str) -> Result<u64, ProviderError> {
525 let members: Vec<MemberDto> = self.get_json(
526 &format!("{}/members/all", self.project_url()),
527 &[("query", username.to_owned())],
528 )?;
529 members
530 .into_iter()
531 .find(|member| member.username.eq_ignore_ascii_case(username))
532 .map(|member| member.id)
533 .ok_or_else(|| bad_value(&format!("GitLab has no member {username} in this project")))
534 }
535
536 fn access_of(&self, user_id: u64) -> u64 {
538 let response = self.send(
539 "GET",
540 &format!("{}/members/all/{user_id}", self.project_url()),
541 &[],
542 None::<&()>,
543 );
544 match response {
545 Ok(response) if response.status().is_success() => {
546 read_json::<MemberAccessDto>(response)
547 .ok()
548 .and_then(|member| member.access_level)
549 .unwrap_or(0)
550 }
551 _ => 0,
552 }
553 }
554
555 fn unsupported(what: &str, can: &str) -> ProviderError {
556 ProviderError::new(
557 Status::GUATIAO_ERR_UNSUPPORTED,
558 &format!("GitLab cannot {what}; it can {can}"),
559 )
560 }
561}
562
563impl TryFrom<Settings> for Gitlab {
564 type Error = ProviderError;
565
566 fn try_from(settings: Settings) -> Result<Self, Self::Error> {
567 Self::new(settings).map_err(|e| ProviderError::new(Status::GUATIAO_ERR_BAD_VALUE, &e))
568 }
569}
570
571impl Gitlab {
572 fn changed_issues(
575 &self,
576 since: Option<&str>,
577 ) -> Result<(Vec<SourceItem>, bool), ProviderError> {
578 let mut query = vec![
579 ("state", "opened".to_owned()),
580 ("order_by", "updated_at".to_owned()),
581 ("sort", "asc".to_owned()),
582 ("per_page", self.settings.page_size.to_string()),
583 ];
584 if !self.settings.labels.is_empty() {
585 query.push(("labels", self.settings.labels.join(",")));
586 }
587 if let Some(assignee) = &self.settings.assignee {
588 query.push(("assignee_username", assignee.clone()));
589 }
590 if let Some(since) = since {
591 query.push(("updated_after", since.to_owned()));
592 }
593 let (issues, more) = self.pages::<IssueDto>(&self.issues_url(), &query, |_| true)?;
594 let items = issues
595 .into_iter()
596 .map(|issue| item_of(&self.settings.project, issue))
597 .collect();
598 Ok((items, more))
599 }
600}
601
602impl Gitlab {
603 fn repository_file(&self, path: &str) -> Result<Option<String>, ProviderError> {
606 let url = format!(
607 "{}/repository/files/{}/raw",
608 self.project_url(),
609 encode_segment(path)
610 );
611 let response = self.send("GET", &url, &[("ref", "HEAD".to_owned())], None::<&()>)?;
612 if response.status().as_u16() == 404 {
613 return Ok(None);
614 }
615 self.check(&response)?;
616 response
617 .into_body()
618 .read_to_string()
619 .map(Some)
620 .map_err(|e| failure(&format!("could not read {path}: {e}")))
621 }
622
623 fn markdown_files(&self, directory: &str) -> Result<Vec<String>, ProviderError> {
625 let url = format!("{}/repository/tree", self.project_url());
626 let mut files = Vec::new();
627 for page in 1_u32.. {
628 let query = [
629 ("path", directory.to_owned()),
630 ("per_page", "100".to_owned()),
631 ("page", page.to_string()),
632 ];
633 let response = self.send("GET", &url, &query, None::<&()>)?;
634 if response.status().as_u16() == 404 {
635 break;
636 }
637 self.check(&response)?;
638 let entries: Vec<TreeEntryDto> = read_json(response)?;
639 let count = entries.len();
640 files.extend(entries.into_iter().filter_map(|entry| {
641 (entry.kind == "blob" && entry.path.to_ascii_lowercase().ends_with(".md"))
642 .then_some(entry.path)
643 }));
644 if count < 100 {
645 break;
646 }
647 }
648 Ok(files)
649 }
650}
651
652impl Source for Gitlab {
653 fn issue_templates(&self) -> Result<Vec<String>, ProviderError> {
654 let mut templates = Vec::new();
655 for path in self.markdown_files(".gitlab/issue_templates")? {
656 templates.extend(self.repository_file(&path)?);
657 }
658 Ok(templates)
659 }
660
661 fn poll(&self, request: SourcePoll) -> Result<SourceBatch, ProviderError> {
662 let since = request.cursor.as_deref().map(|cursor| {
663 settled_cursor(cursor, self.settings.settling_secs).unwrap_or_else(|| cursor.to_owned())
664 });
665 let (mut items, more) = self.changed_issues(since.as_deref())?;
666 if more
668 && since != request.cursor
669 && !items
670 .iter()
671 .any(|item| Some(item.updated.as_str()) > request.cursor.as_deref())
672 {
673 items = self.changed_issues(request.cursor.as_deref())?.0;
674 }
675 let cursor = items
677 .iter()
678 .map(|item| item.updated.clone())
679 .chain(request.cursor)
680 .max();
681 Ok(SourceBatch { items, cursor })
682 }
683
684 fn board_url(&self) -> Result<Option<String>, ProviderError> {
685 Ok(self.settings.board_url.clone().or_else(|| {
686 self.web_project()
687 .filter(|web| web.starts_with("https://"))
688 .map(|web| format!("{web}/-/boards"))
689 }))
690 }
691
692 fn facts(&self) -> Result<SourceFacts, ProviderError> {
693 let mut credential_variables = vec![self.settings.token_env.clone()];
694 credential_variables.extend(CLI_TOKEN_VARIABLES.map(str::to_owned));
695 credential_variables.sort();
696 credential_variables.dedup();
697 Ok(SourceFacts {
698 web: self.web_project().filter(|web| web.starts_with("https://")),
699 project: None,
700 intake_labels: self.settings.labels.clone(),
701 hosts: self
702 .api
703 .host_str()
704 .map(str::to_lowercase)
705 .into_iter()
706 .collect(),
707 credential_variables,
708 })
709 }
710}
711
712const CLI_TOKEN_VARIABLES: [&str; 2] = ["GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN"];
714
715impl Tracker for Gitlab {
716 fn capabilities(&self, item: Option<String>) -> Result<TrackerCapabilities, ProviderError> {
717 let mut capabilities = self.project_capabilities()?;
718 if let Some(item) = item {
719 let iid = self.iid(&item)?;
720 let kind = self
722 .get_json::<IssueTypeDto>(&self.issue_url(iid), &[])
723 .ok()
724 .and_then(|issue| issue.issue_type);
725 if kind.as_deref() != Some("issue") {
726 capabilities.children = "none".to_owned();
727 }
728 }
729 Ok(capabilities)
730 }
731
732 fn issue(&self, item: String) -> Result<TrackerIssue, ProviderError> {
733 let iid = self.iid(&item)?;
734 let issue: IssueDto = self.get_json(&self.issue_url(iid), &[])?;
735 let is_task = issue.issue_type.as_deref() == Some("task");
736 let mut read = issue_of(&self.settings.project, issue);
737 if is_task {
738 read.parent = self.parent_of(iid);
739 }
740 Ok(read)
741 }
742
743 fn replies(&self, request: ReplyPoll) -> Result<ReplyBatch, ProviderError> {
744 let wanted: Vec<u64> = request
745 .items
746 .iter()
747 .map(|item| self.iid(item))
748 .collect::<Result<_, _>>()?;
749 let mut cursor = request.since.clone();
750 let mut replies = Vec::new();
751 let mut access: BTreeMap<u64, u64> = BTreeMap::new();
752 let since = request.since.as_deref();
753 for iid in wanted {
754 let (notes, _) = self.pages::<NoteDto>(
756 &format!("{}/notes", self.issue_url(iid)),
757 &[
758 ("order_by", "updated_at".to_owned()),
759 ("sort", "desc".to_owned()),
760 ("per_page", self.settings.page_size.to_string()),
761 ],
762 |page| {
763 page.iter().all(|note| {
764 since.is_none_or(|since| {
765 note.updated_at
766 .as_deref()
767 .is_some_and(|updated| updated >= since)
768 })
769 })
770 },
771 )?;
772 let mut author: Option<Option<String>> = None;
773 for note in notes.into_iter().rev() {
774 let Some(updated) = note.updated_at.as_deref() else {
775 continue;
776 };
777 if since.is_some_and(|since| updated < since) {
778 continue;
779 }
780 if cursor.as_deref().is_none_or(|current| updated > current) {
781 cursor = Some(updated.to_owned());
782 }
783 if note.system == Some(true) {
785 continue;
786 }
787 let username = note
788 .author
789 .as_ref()
790 .and_then(|author| author.username.as_deref())
791 .unwrap_or_default()
792 .to_owned();
793 let user_id = note.author.as_ref().and_then(|author| author.id);
794 let permitted = self
795 .settings
796 .reply_authors
797 .iter()
798 .any(|allowed| allowed.eq_ignore_ascii_case(&username))
799 || author
800 .get_or_insert_with(|| {
801 self.get_json::<IssueAuthorDto>(&self.issue_url(iid), &[])
802 .ok()
803 .and_then(|issue| issue.author?.username)
804 })
805 .as_deref()
806 .is_some_and(|author| author.eq_ignore_ascii_case(&username))
807 || user_id.is_some_and(|id| {
808 *access.entry(id).or_insert_with(|| self.access_of(id))
809 >= self.settings.reply_min_access
810 });
811 let body = note.body.unwrap_or_default();
812 replies.push(Reply {
813 id: note.id.to_string(),
814 item: self.item_id(iid),
815 author_id: username.clone(),
816 author: username,
817 permitted,
818 own: body.contains(MARKER_PREFIX),
820 body,
821 created: note.created_at.unwrap_or_default(),
822 });
823 }
824 }
825 Ok(ReplyBatch { replies, cursor })
826 }
827
828 fn post(&self, post: TrackerPost) -> Result<PostedComment, ProviderError> {
829 let iid = self.iid(&post.item)?;
830 if post.body.trim().is_empty() {
831 return Err(bad_value(
832 "the comment is empty, and GitLab refuses such a comment",
833 ));
834 }
835 let mut body = post.body;
836 let marker: String = post
837 .marker
838 .as_deref()
839 .unwrap_or("comment")
840 .chars()
841 .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | ':' | '.'))
842 .collect();
843 body.push_str(&format!("\n\n{MARKER_PREFIX}{marker} -->"));
844 let payload = NoteBodyRequest { body: &body };
845 let notes = format!("{}/notes", self.issue_url(iid));
846 let note: PostedNoteDto = match &post.edit {
847 Some(id) => {
848 if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
849 return Err(bad_value("a comment ID is a number"));
850 }
851 read_json(self.call("PUT", &format!("{notes}/{id}"), &[], Some(&payload))?)?
852 }
853 None => read_json(self.call("POST", ¬es, &[], Some(&payload))?)?,
854 };
855 let id = note.id;
856 Ok(PostedComment {
857 id: id.to_string(),
858 url: self
859 .web_project()
860 .map(|web| format!("{web}/-/issues/{iid}#note_{id}")),
861 })
862 }
863
864 fn update(&self, update: TrackerUpdate) -> Result<(), ProviderError> {
865 let iid = self.iid(&update.item)?;
866 if update.transition.is_some() {
867 return Err(Self::unsupported(
868 "make a workflow transition",
869 "set the state to open or closed",
870 ));
871 }
872 let state_event = match update.state.as_deref() {
873 None => None,
874 Some("closed") => Some("close"),
875 Some("open") => Some("reopen"),
876 Some(other) => {
877 return Err(bad_value(&format!(
878 "state {other:?} is not `open` or `closed`"
879 )));
880 }
881 };
882 let mut changes = UpdateIssueRequest::default();
883 if !update.add_labels.is_empty() {
885 changes.add_labels = Some(update.add_labels.join(","));
886 }
887 if !update.remove_labels.is_empty() {
888 changes.remove_labels = Some(update.remove_labels.join(","));
889 }
890 changes.state_event = state_event;
891 if !update.add_assignees.is_empty() || !update.remove_assignees.is_empty() {
892 let issue: IssueAssigneesDto = self.get_json(&self.issue_url(iid), &[])?;
894 let mut assignees: Vec<(u64, String)> = issue
895 .assignees
896 .into_iter()
897 .flatten()
898 .filter_map(|person| Some((person.id?, person.username?)))
899 .collect();
900 assignees.retain(|(_, name)| {
901 !update
902 .remove_assignees
903 .iter()
904 .any(|gone| gone.eq_ignore_ascii_case(name))
905 });
906 for name in &update.add_assignees {
907 if !assignees
908 .iter()
909 .any(|(_, have)| have.eq_ignore_ascii_case(name))
910 {
911 assignees.push((self.member_id(name)?, name.clone()));
912 }
913 }
914 changes.assignee_ids = Some(assignees.into_iter().map(|(id, _)| id).collect());
915 }
916 if changes.is_empty() {
917 return Ok(());
918 }
919 self.call("PUT", &self.issue_url(iid), &[], Some(&changes))?;
920 Ok(())
921 }
922
923 fn create(&self, spec: IssueSpec) -> Result<TrackerIssue, ProviderError> {
924 let capabilities = self.project_capabilities()?;
925 if !capabilities.create {
926 return Err(Self::unsupported(
927 "create issues here",
928 "read and comment on them",
929 ));
930 }
931 let parent = match spec.parent.as_deref() {
933 Some(parent) => {
934 let iid = self.iid(parent)?;
935 self.get_json::<IssueParentDto>(&self.issue_url(iid), &[])
936 .ok()
937 .filter(|issue| issue.issue_type.as_deref() == Some("issue"))
938 .and_then(|issue| Some((iid, issue.id?)))
939 }
940 None => None,
941 };
942 let labels: Vec<&str> = spec
944 .labels
945 .iter()
946 .filter(|label| capabilities.labels.contains(label))
947 .map(String::as_str)
948 .collect();
949 let payload = CreateIssueRequest {
950 title: &spec.title,
951 description: &spec.body,
952 labels: labels.join(","),
953 issue_type: parent.map(|_| "task"),
954 };
955 let created: IssueDto =
956 read_json(self.call("POST", &self.issues_url(), &[], Some(&payload))?)?;
957 let created_id = created.id;
958 let mut issue = issue_of(&self.settings.project, created);
959 if let (Some((parent_iid, parent_id)), Some(id)) = (parent, created_id) {
960 if self.attach(id, parent_id).is_ok() {
962 issue.parent = Some(self.item_id(parent_iid));
963 }
964 }
965 Ok(issue)
966 }
967
968 fn link(&self, link: TrackerLink) -> Result<(), ProviderError> {
969 let from = self.iid(&link.from)?;
970 let Some(to) = link.to.as_deref() else {
971 if link.url.is_some() {
972 return Err(Self::unsupported(
973 "link an issue to an address",
974 "link two issues, or name the address in a comment",
975 ));
976 }
977 return Err(bad_value("a link names an issue or an address"));
978 };
979 let to = self.iid(to)?;
980 let response = self.send(
981 "POST",
982 &format!("{}/links", self.issue_url(from)),
983 &[],
984 Some(&LinkIssueRequest {
985 target_project_id: &self.settings.project,
986 target_issue_iid: to.to_string(),
987 link_type: "relates_to",
988 }),
989 )?;
990 if response.status().as_u16() == 409 {
992 return Ok(());
993 }
994 self.check(&response)
995 }
996}
997
998#[derive(Deserialize)]
999struct TokenSelfDto {
1000 scopes: Option<Vec<String>>,
1001}
1002
1003#[derive(Deserialize)]
1004struct ProjectDto {
1005 visibility: Option<String>,
1006 issues_enabled: Option<bool>,
1007 issues_access_level: Option<String>,
1008}
1009
1010#[derive(Deserialize)]
1011struct LabelDto {
1012 name: String,
1013}
1014
1015#[derive(Deserialize)]
1016struct MemberDto {
1017 id: u64,
1018 username: String,
1019}
1020
1021#[derive(Deserialize)]
1022struct MemberAccessDto {
1023 access_level: Option<u64>,
1024}
1025
1026#[derive(Deserialize)]
1027struct TreeEntryDto {
1028 path: String,
1029 #[serde(rename = "type")]
1030 kind: String,
1031}
1032
1033#[derive(Deserialize)]
1034struct UserDto {
1035 id: Option<u64>,
1036 username: Option<String>,
1037}
1038
1039#[derive(Deserialize)]
1040struct IssueDto {
1041 id: Option<u64>,
1042 iid: u64,
1043 title: String,
1044 description: Option<String>,
1045 state: Option<String>,
1046 web_url: Option<String>,
1047 labels: Option<Vec<String>>,
1048 assignees: Option<Vec<UserDto>>,
1049 author: Option<UserDto>,
1050 issue_type: Option<String>,
1051 updated_at: String,
1052}
1053
1054#[derive(Deserialize)]
1055struct IssueTypeDto {
1056 issue_type: Option<String>,
1057}
1058
1059#[derive(Deserialize)]
1060struct IssueAuthorDto {
1061 author: Option<UserDto>,
1062}
1063
1064#[derive(Deserialize)]
1065struct IssueAssigneesDto {
1066 assignees: Option<Vec<UserDto>>,
1067}
1068
1069#[derive(Deserialize)]
1070struct IssueParentDto {
1071 id: Option<u64>,
1072 issue_type: Option<String>,
1073}
1074
1075#[derive(Deserialize)]
1076struct NoteDto {
1077 id: u64,
1078 body: Option<String>,
1079 system: Option<bool>,
1080 author: Option<UserDto>,
1081 created_at: Option<String>,
1082 updated_at: Option<String>,
1083}
1084
1085#[derive(Deserialize)]
1086struct PostedNoteDto {
1087 id: u64,
1088}
1089
1090#[derive(Serialize)]
1091struct NoteBodyRequest<'a> {
1092 body: &'a str,
1093}
1094
1095#[derive(Default, Serialize)]
1096struct UpdateIssueRequest {
1097 #[serde(skip_serializing_if = "Option::is_none")]
1098 add_labels: Option<String>,
1099 #[serde(skip_serializing_if = "Option::is_none")]
1100 remove_labels: Option<String>,
1101 #[serde(skip_serializing_if = "Option::is_none")]
1102 state_event: Option<&'static str>,
1103 #[serde(skip_serializing_if = "Option::is_none")]
1104 assignee_ids: Option<Vec<u64>>,
1105}
1106
1107impl UpdateIssueRequest {
1108 fn is_empty(&self) -> bool {
1109 self.add_labels.is_none()
1110 && self.remove_labels.is_none()
1111 && self.state_event.is_none()
1112 && self.assignee_ids.is_none()
1113 }
1114}
1115
1116#[derive(Serialize)]
1117struct CreateIssueRequest<'a> {
1118 title: &'a str,
1119 description: &'a str,
1120 labels: String,
1121 #[serde(skip_serializing_if = "Option::is_none")]
1122 issue_type: Option<&'static str>,
1123}
1124
1125#[derive(Serialize)]
1126struct LinkIssueRequest<'a> {
1127 target_project_id: &'a str,
1128 target_issue_iid: String,
1129 link_type: &'static str,
1130}
1131
1132#[derive(Serialize)]
1133struct GraphqlRequest<'a, V> {
1134 query: &'a str,
1135 variables: V,
1136}
1137
1138#[derive(Deserialize)]
1139struct GraphqlResponse<D> {
1140 data: Option<D>,
1141 errors: Option<Vec<serde::de::IgnoredAny>>,
1142}
1143
1144#[derive(Serialize)]
1145struct ParentQueryVariables<'a> {
1146 path: &'a str,
1147 iid: String,
1148}
1149
1150#[derive(Deserialize)]
1151struct ParentQueryData {
1152 project: Option<GraphqlProjectDto>,
1153}
1154
1155#[derive(Deserialize)]
1156struct GraphqlProjectDto {
1157 #[serde(rename = "workItems")]
1158 work_items: Option<WorkItemsConnectionDto>,
1159}
1160
1161#[derive(Deserialize)]
1162struct WorkItemsConnectionDto {
1163 nodes: Option<Vec<WorkItemNodeDto>>,
1164}
1165
1166#[derive(Deserialize)]
1167struct WorkItemNodeDto {
1168 widgets: Option<Vec<WorkItemWidgetDto>>,
1169}
1170
1171#[derive(Deserialize)]
1172struct WorkItemWidgetDto {
1173 parent: Option<WorkItemParentDto>,
1174}
1175
1176#[derive(Deserialize)]
1177struct WorkItemParentDto {
1178 iid: Option<String>,
1179 namespace: Option<WorkItemNamespaceDto>,
1180}
1181
1182#[derive(Deserialize)]
1183struct WorkItemNamespaceDto {
1184 #[serde(rename = "fullPath")]
1185 full_path: Option<String>,
1186}
1187
1188#[derive(Serialize)]
1189struct AttachVariables {
1190 id: String,
1191 parent: String,
1192}
1193
1194#[derive(Deserialize)]
1195struct AttachData {
1196 #[serde(rename = "workItemUpdate")]
1197 work_item_update: Option<WorkItemUpdateDto>,
1198}
1199
1200#[derive(Deserialize)]
1201struct WorkItemUpdateDto {
1202 errors: Option<Vec<serde::de::IgnoredAny>>,
1203}
1204
1205fn read_json<T: serde::de::DeserializeOwned>(
1206 mut response: ureq::http::Response<ureq::Body>,
1207) -> Result<T, ProviderError> {
1208 response
1209 .body_mut()
1210 .read_json()
1211 .map_err(|e| failure(&format!("unreadable response: {e}")))
1212}
1213
1214fn encode_segment(text: &str) -> String {
1216 let mut out = String::new();
1217 for byte in text.bytes() {
1218 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
1219 out.push(byte as char);
1220 } else {
1221 out.push_str(&format!("%{byte:02X}"));
1222 }
1223 }
1224 out
1225}
1226
1227fn issue_of(project: &str, issue: IssueDto) -> TrackerIssue {
1228 let native_id = issue.id.map(|id| id.to_string()).unwrap_or_default();
1229 let state = match issue.state.as_deref() {
1230 Some("closed") => "closed",
1231 _ => "open",
1232 }
1233 .to_owned();
1234 let assignees = issue
1235 .assignees
1236 .as_ref()
1237 .map(|people| {
1238 people
1239 .iter()
1240 .filter_map(|person| person.username.clone())
1241 .collect()
1242 })
1243 .unwrap_or_default();
1244 let item = item_of(project, issue);
1245 TrackerIssue {
1246 id: item.id,
1247 native_id,
1248 title: item.title,
1249 body: item.body,
1250 state,
1251 labels: item.labels,
1252 assignees,
1253 url: item.url,
1254 updated: item.updated,
1255 parent: None,
1256 author_id: item.author,
1257 priority: None,
1258 code: item.code,
1259 code_tag: item.code_tag,
1260 }
1261}
1262
1263fn bad_value(message: &str) -> ProviderError {
1264 ProviderError::new(Status::GUATIAO_ERR_BAD_VALUE, message)
1265}
1266
1267fn item_of(project: &str, issue: IssueDto) -> SourceItem {
1268 let iid = issue.iid;
1269 SourceItem {
1270 id: format!("{project}#{iid}"),
1271 title: issue.title,
1272 body: issue.description.unwrap_or_default(),
1273 url: issue.web_url,
1274 labels: issue.labels.unwrap_or_default(),
1275 author: issue.author.and_then(|author| author.username),
1276 updated: issue.updated_at,
1277 code: Some(iid.to_string()),
1278 code_tag: Some("gl".to_owned()),
1279 event: None,
1280 }
1281}
1282
1283fn next_link(header: Option<&str>) -> Option<String> {
1285 header?.split(',').find_map(|part| {
1286 let (target, params) = part.split_once(';')?;
1287 params
1288 .split(';')
1289 .any(|param| param.trim().replace(' ', "") == "rel=\"next\"")
1290 .then(|| {
1291 target
1292 .trim()
1293 .trim_start_matches('<')
1294 .trim_end_matches('>')
1295 .to_owned()
1296 })
1297 })
1298}
1299
1300fn same_origin(candidate: &str, api: &Url) -> bool {
1302 Url::parse(candidate).is_ok_and(|url| url.origin() == api.origin())
1303}
1304
1305fn https_page(text: &str) -> Result<(), String> {
1307 let url = Url::parse(text).map_err(|error| error.to_string())?;
1308 if url.scheme() != "https"
1309 || url.host_str().is_none()
1310 || !url.username().is_empty()
1311 || url.password().is_some()
1312 {
1313 return Err("must be an https address without credentials".to_owned());
1314 }
1315 Ok(())
1316}
1317
1318fn failure(message: &str) -> ProviderError {
1319 ProviderError::new(Status::GUATIAO_ERR_INTERNAL, message)
1320}
1321
1322#[cfg(test)]
1323mod tests {
1324 use super::*;
1325
1326 trait FromText: Sized {
1327 fn from_settings(text: &str) -> Result<Self, String>;
1328 }
1329
1330 impl FromText for Gitlab {
1331 fn from_settings(text: &str) -> Result<Self, String> {
1332 Gitlab::new(ai6::provider_settings::settings_from_text(
1333 ai6::bootstrap::format::Format::Toml,
1334 text,
1335 )?)
1336 }
1337 }
1338
1339 #[test]
1340 fn the_facts_name_the_page_the_labels_the_hosts_and_the_credential_variables() {
1341 let facts = |text: &str| Gitlab::from_settings(text).unwrap().facts().unwrap();
1342 let public = facts("project = \"g/n\"");
1343 assert_eq!(public.web.as_deref(), Some("https://gitlab.com/g/n"));
1344 assert_eq!(
1345 public.intake_labels,
1346 ["ai6:ready"],
1347 "a GitLab instance has an intake label"
1348 );
1349 assert_eq!(public.hosts, ["gitlab.com"]);
1350 for name in ["GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN"] {
1351 assert!(
1352 public.credential_variables.iter().any(|v| v == name),
1353 "{name}"
1354 );
1355 }
1356 let lab = facts(
1357 "project = \"g/s/n\"
1358token_env = \"LAB\"
1359api_url = \"https://gitlab.example/api/v4\"",
1360 );
1361 assert_eq!(lab.web.as_deref(), Some("https://gitlab.example/g/s/n"));
1362 assert!(lab.credential_variables.contains(&"LAB".to_owned()));
1363 }
1364
1365 #[test]
1366 fn link_headers_yield_the_next_page() {
1367 let header = r#"<https://gitlab.com/api/v4/x?page=2>; rel="next", <https://gitlab.com/api/v4/x?page=1>; rel="first""#;
1368 assert_eq!(
1369 next_link(Some(header)).as_deref(),
1370 Some("https://gitlab.com/api/v4/x?page=2")
1371 );
1372 assert_eq!(next_link(Some(r#"<https://a/x>; rel="last""#)), None);
1373 assert_eq!(next_link(None), None);
1374 }
1375
1376 #[test]
1377 fn settings_reject_unknown_keys_bad_projects_and_insecure_apis() {
1378 assert!(Gitlab::from_settings("project = \"g/p\"").is_ok());
1379 assert!(Gitlab::from_settings("project = \"g/sub/p\"").is_ok());
1380 assert!(Gitlab::from_settings("target = \"g/p\"").is_ok());
1381 assert!(Gitlab::from_settings("project = \"g/p\"\nlabel = \"x\"").is_err());
1382 assert!(Gitlab::from_settings("project = \"nope\"").is_err());
1383 assert!(Gitlab::from_settings("project = \"g/../p\"").is_err());
1384 assert!(Gitlab::from_settings("project = \"g//p\"").is_err());
1385 assert!(
1386 Gitlab::from_settings("project = \"g/p\"\napi_url = \"http://example.com\"").is_err()
1387 );
1388 assert!(
1389 Gitlab::from_settings("project = \"g/p\"\napi_url = \"http://127.0.0.1:9\"").is_ok()
1390 );
1391 }
1392
1393 #[test]
1394 fn the_board_is_the_projects_boards_unless_the_settings_name_another() {
1395 let board = |text: &str| Gitlab::from_settings(text).unwrap().board_url().unwrap();
1396 assert_eq!(
1397 board("project = \"g/sub/p\"").as_deref(),
1398 Some("https://gitlab.com/g/sub/p/-/boards")
1399 );
1400 assert_eq!(
1401 board(
1402 "project = \"g/p\"
1403api_url = \"https://git.example.com/gitlab/api/v4/\""
1404 )
1405 .as_deref(),
1406 Some("https://git.example.com/gitlab/g/p/-/boards")
1407 );
1408 assert_eq!(
1409 board(
1410 "project = \"g/p\"
1411board_url = \"https://gitlab.com/groups/g/-/boards/9\""
1412 )
1413 .as_deref(),
1414 Some("https://gitlab.com/groups/g/-/boards/9")
1415 );
1416 assert_eq!(
1417 board(
1418 "project = \"g/p\"
1419api_url = \"http://127.0.0.1:9/api/v4\""
1420 ),
1421 None
1422 );
1423 assert_eq!(
1424 board(
1425 "project = \"g/p\"
1426api_url = \"https://proxy.example/gl\""
1427 ),
1428 None
1429 );
1430 assert!(
1431 Gitlab::from_settings(
1432 "project = \"g/p\"
1433board_url = \"http://gitlab.com/g\""
1434 )
1435 .is_err()
1436 );
1437 }
1438
1439 #[test]
1440 fn graphql_and_web_addresses_sit_beside_the_api_root() {
1441 let gitlab = Gitlab::from_settings("project = \"g/sub/p\"").unwrap();
1442 assert_eq!(gitlab.graphql_url(), "https://gitlab.com/api/graphql");
1443 assert_eq!(
1444 gitlab.web_project().as_deref(),
1445 Some("https://gitlab.com/g/sub/p")
1446 );
1447 assert_eq!(
1448 gitlab.project_url(),
1449 "https://gitlab.com/api/v4/projects/g%2Fsub%2Fp"
1450 );
1451 let elsewhere = Gitlab::from_settings(
1452 "project = \"g/p\"\napi_url = \"https://git.example.com/gitlab/api/v4/\"",
1453 )
1454 .unwrap();
1455 assert_eq!(
1456 elsewhere.graphql_url(),
1457 "https://git.example.com/gitlab/api/graphql"
1458 );
1459 assert_eq!(
1460 elsewhere.web_project().as_deref(),
1461 Some("https://git.example.com/gitlab/g/p")
1462 );
1463 }
1464
1465 #[test]
1466 fn pagination_never_leaves_the_api_origin() {
1467 let api = Url::parse("https://gitlab.com/api/v4").unwrap();
1468 assert!(same_origin(
1469 "https://gitlab.com/api/v4/projects?page=2",
1470 &api
1471 ));
1472 assert!(!same_origin("https://evil.example/projects?page=2", &api));
1473 }
1474}