Skip to main content

gitpoulpi_hosting/bitbucket/
client.rs

1//! The Bitbucket Cloud client.
2
3use std::sync::Arc;
4
5use serde::de::DeserializeOwned;
6
7use super::map::{Account, Page, PullRequest, Repo, SshKey, WorkspaceAccess};
8use crate::client::{
9    encode_component, CreatedIssue, CreatedPullRequest, HostingClient, NewIssue, NewPullRequest,
10    MAX_PAGES,
11};
12use crate::conversation::{
13    Comment, ConversationCaps, ItemKey, ItemKind, PageCursor, PostingIdentity, TimelineOpts,
14    TimelinePage,
15};
16use crate::http::{HttpRequest, HttpTransport};
17use crate::integration::Integration;
18use crate::model::{
19    best_pull_request, excess_scopes, missing_scopes, HostedUser, IssueFilter, IssueSummary,
20    PrFilter, PullRequestSummary, StateFilter, TokenCheck, TokenFlavor,
21};
22use crate::project::{HostedProject, HostedSshKey};
23use crate::{Error, Result};
24
25/// The pull request endpoints cap `pagelen` at 50; repositories and the
26/// rest accept 100.
27const PR_PAGELEN: u32 = 50;
28const PAGELEN: u32 = 100;
29
30/// Why `list_issues` / `create_issue` always fail.
31pub const ISSUES_RETIRED: &str =
32    "Bitbucket issues were retired on 2026-08-20; link a Jira project instead";
33
34mod conversation;
35mod protection;
36
37pub struct BitbucketClient {
38    integration: Integration,
39    token: String,
40    transport: Arc<dyn HttpTransport>,
41    pub(crate) scopes: crate::scope_handle::ScopeHandle,
42}
43
44impl BitbucketClient {
45    pub(crate) fn new(
46        integration: Integration,
47        token: String,
48        transport: Arc<dyn HttpTransport>,
49    ) -> Self {
50        Self {
51            integration,
52            token,
53            transport,
54            scopes: Default::default(),
55        }
56    }
57
58    fn authed(&self, mut request: HttpRequest) -> HttpRequest {
59        for (name, value) in crate::auth::auth_headers(&self.integration, &self.token) {
60            request = request.header(name, value);
61        }
62        request
63    }
64
65    fn get(&self, url: String) -> HttpRequest {
66        self.authed(HttpRequest::get(url))
67    }
68
69    fn api(&self) -> String {
70        self.integration.api_base()
71    }
72
73    /// `scheme://host[:port]` of the API root: a `next` link may only point
74    /// there, so the token is never sent to another host.
75    fn origin(&self) -> String {
76        let api = self.api();
77        match api.split_once("://") {
78            Some((scheme, rest)) => format!("{scheme}://{}", rest.split('/').next().unwrap_or("")),
79            None => api,
80        }
81    }
82
83    /// Every page of a list endpoint, following the `next` URLs the host
84    /// returns (never constructing its own), capped at [`MAX_PAGES`].
85    async fn fetch_all<T: DeserializeOwned>(&self, first: String, what: &str) -> Result<Vec<T>> {
86        let origin = self.origin();
87        let mut out = Vec::new();
88        let mut url = first;
89        for _ in 0..MAX_PAGES {
90            let response = self.transport.send(self.get(url)).await?;
91            response.error_for_status(what)?;
92            let page: Page<T> = response.json()?;
93            out.extend(page.values);
94            match page.next.filter(|n| !n.is_empty()) {
95                None => break,
96                Some(next) if next.starts_with(&origin) => url = next,
97                Some(next) => {
98                    return Err(Error::Decode(format!(
99                        "{what}: refusing to follow a next link to another host ({next})"
100                    )))
101                }
102            }
103        }
104        Ok(out)
105    }
106
107    async fn fetch_account(&self, what: &str) -> Result<Account> {
108        let response = self
109            .transport
110            .send(self.get(format!("{}/user", self.api())))
111            .await?;
112        response.error_for_status(what)?;
113        response.json()
114    }
115
116    async fn workspaces(&self) -> Result<Vec<String>> {
117        let url = format!("{}/user/workspaces?pagelen={PAGELEN}", self.api());
118        let rows: Vec<WorkspaceAccess> =
119            self.fetch_all(url, "listing Bitbucket workspaces").await?;
120        Ok(rows.into_iter().map(|w| w.workspace.slug).collect())
121    }
122
123    async fn my_uuid(&self) -> Result<String> {
124        Ok(self
125            .fetch_account("reading the Bitbucket account")
126            .await?
127            .uuid)
128    }
129
130    fn pr_url(&self, project: &str) -> String {
131        format!("{}/repositories/{project}/pullrequests", self.api())
132    }
133
134    async fn pull_requests(
135        &self,
136        project: &str,
137        states: &[&str],
138        q: &[String],
139        what: &str,
140    ) -> Result<Vec<PullRequest>> {
141        let mut url = format!(
142            "{}?pagelen={PR_PAGELEN}&sort=-updated_on",
143            self.pr_url(project)
144        );
145        for state in states {
146            url.push_str(&format!("&state={state}"));
147        }
148        if !q.is_empty() {
149            url.push_str(&format!("&q={}", encode_component(&q.join(" AND "))));
150        }
151        self.fetch_all(url, what).await
152    }
153}
154
155/// A string literal in Bitbucket's filter language.
156fn q_string(text: &str) -> String {
157    format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
158}
159
160#[async_trait::async_trait]
161impl HostingClient for BitbucketClient {
162    fn integration(&self) -> &Integration {
163        &self.integration
164    }
165
166    async fn list_projects(&self) -> Result<Vec<HostedProject>> {
167        let mut out = Vec::new();
168        for workspace in self.workspaces().await? {
169            let url = format!(
170                "{}/repositories/{}?role=member&sort=-updated_on&pagelen={PAGELEN}",
171                self.api(),
172                encode_component(&workspace)
173            );
174            match self
175                .fetch_all::<Repo>(url, "listing Bitbucket repositories")
176                .await
177            {
178                Ok(rows) => out.extend(
179                    rows.into_iter()
180                        .map(|r| r.into_project(&self.integration.id)),
181                ),
182                // A workspace the token cannot read (scope or SSO) must not
183                // hide the others.
184                Err(Error::Forbidden { .. }) => {}
185                Err(Error::Api { status: 404, .. }) => {}
186                Err(e) => return Err(e),
187            }
188        }
189        Ok(out)
190    }
191
192    async fn account_items(
193        &self,
194        _query: &crate::account::AccountQuery,
195    ) -> Result<crate::account::AccountItems> {
196        Err(Error::Unsupported(
197            crate::account::NO_BITBUCKET_CLOUD.to_string(),
198        ))
199    }
200
201    async fn list_ssh_keys(&self) -> Result<Vec<HostedSshKey>> {
202        let uuid = encode_component(&self.my_uuid().await?);
203        let url = format!("{}/users/{uuid}/ssh-keys?pagelen={PAGELEN}", self.api());
204        let rows: Vec<SshKey> = self.fetch_all(url, "listing Bitbucket SSH keys").await?;
205        Ok(rows.into_iter().map(SshKey::into_key).collect())
206    }
207
208    async fn upload_ssh_key(&self, title: &str, public_key: &str) -> Result<HostedSshKey> {
209        let uuid = encode_component(&self.my_uuid().await?);
210        let url = format!("{}/users/{uuid}/ssh-keys", self.api());
211        let body = serde_json::json!({ "label": title, "key": public_key.trim() });
212        let response = self
213            .transport
214            .send(self.authed(HttpRequest::post_json(url, &body)))
215            .await?;
216        response.error_for_status("uploading an SSH key to Bitbucket")?;
217        Ok(response.json::<SshKey>()?.into_key())
218    }
219
220    async fn delete_ssh_key(&self, id: &str) -> Result<()> {
221        let uuid = encode_component(&self.my_uuid().await?);
222        let url = format!(
223            "{}/users/{uuid}/ssh-keys/{}",
224            self.api(),
225            encode_component(id)
226        );
227        let response = self
228            .transport
229            .send(self.authed(HttpRequest::delete(url)))
230            .await?;
231        response.error_for_status("deleting a Bitbucket SSH key")
232    }
233
234    async fn create_pull_request(&self, req: &NewPullRequest) -> Result<CreatedPullRequest> {
235        let mut source = serde_json::json!({ "branch": { "name": req.source_branch } });
236        if let Some(fork) = req.fork_source() {
237            source["repository"] = serde_json::json!({ "full_name": fork });
238        }
239        let body = serde_json::json!({
240            "title": req.title,
241            "description": req.body,
242            "source": source,
243            "destination": { "branch": { "name": req.target_branch } },
244            "draft": req.draft,
245        });
246        let response = self
247            .transport
248            .send(self.authed(HttpRequest::post_json(self.pr_url(&req.project), &body)))
249            .await?;
250        response.error_for_status("opening a Bitbucket pull request")?;
251        let created: PullRequest = response.json()?;
252        let number = created.id;
253        Ok(CreatedPullRequest {
254            number,
255            web_url: created.links.html.href.unwrap_or_default(),
256            ..Default::default()
257        })
258    }
259
260    async fn protected_branches(
261        &self,
262        project: &str,
263    ) -> Result<crate::protection::ProtectedBranches> {
264        self.protection(project).await
265    }
266
267    async fn current_user(&self) -> Result<HostedUser> {
268        Ok(self
269            .fetch_account("checking the Bitbucket token")
270            .await?
271            .into_user())
272    }
273
274    async fn check_token(&self) -> Result<TokenCheck> {
275        // Bitbucket sends the token's scopes in `x-oauth-scopes` when it
276        // sends them at all (an API token does not): absent is unknown,
277        // never "missing".
278        let response = self
279            .transport
280            .send(self.get(format!("{}/user", self.api())))
281            .await?;
282        response.error_for_status("checking the Bitbucket token")?;
283        let scopes = response
284            .headers
285            .iter()
286            .find(|(k, _)| k.eq_ignore_ascii_case("x-oauth-scopes"))
287            .map(|(_, v)| {
288                v.split([',', ' '])
289                    .map(str::trim)
290                    .filter(|s| !s.is_empty())
291                    .map(str::to_string)
292                    .collect::<Vec<_>>()
293            })
294            .filter(|s| !s.is_empty());
295        let required = self
296            .integration
297            .kind
298            .token_help()
299            .map(|h| h.scopes)
300            .unwrap_or(&[]);
301        let (missing, excess) = scopes.as_deref().map_or_else(Default::default, |granted| {
302            (
303                missing_scopes(required, granted),
304                excess_scopes(required, &[], granted),
305            )
306        });
307        let account: Account = response.json()?;
308        Ok(TokenCheck {
309            user: account.into_user(),
310            token_flavor: Some(if scopes.is_some() {
311                TokenFlavor::Classic
312            } else {
313                TokenFlavor::Unknown
314            }),
315            scopes,
316            missing_scopes: missing,
317            excess_scopes: excess,
318            ..Default::default()
319        })
320    }
321
322    async fn list_pull_requests(
323        &self,
324        project: &str,
325        filter: &PrFilter,
326    ) -> Result<Vec<PullRequestSummary>> {
327        let states: &[&str] = match filter.state {
328            StateFilter::Open => &["OPEN"],
329            StateFilter::Closed => &["MERGED", "DECLINED", "SUPERSEDED"],
330            StateFilter::All => &["OPEN", "MERGED", "DECLINED", "SUPERSEDED"],
331        };
332        let me = if filter.mine || filter.review_requested {
333            Some(self.my_uuid().await?)
334        } else {
335            None
336        };
337        let mut q = Vec::new();
338        if let (true, Some(me)) = (filter.mine, &me) {
339            q.push(format!("author.uuid={}", q_string(me)));
340        }
341        let rows = self
342            .pull_requests(project, states, &q, "listing Bitbucket pull requests")
343            .await?;
344        Ok(rows
345            .into_iter()
346            .map(|r| r.into_summary(project, me.as_deref()))
347            .filter(|s| !filter.review_requested || s.review_requested)
348            .collect())
349    }
350
351    async fn pull_request_for_branch(
352        &self,
353        project: &str,
354        branch: &str,
355    ) -> Result<Option<PullRequestSummary>> {
356        let q = [format!("source.branch.name={}", q_string(branch))];
357        let rows = self
358            .pull_requests(
359                project,
360                &["OPEN", "MERGED", "DECLINED", "SUPERSEDED"],
361                &q,
362                "looking up the pull request for a branch",
363            )
364            .await?;
365        Ok(best_pull_request(
366            rows.into_iter()
367                .map(|r| r.into_summary(project, None))
368                .collect(),
369        ))
370    }
371
372    async fn list_issues(
373        &self,
374        _project: &str,
375        _filter: &IssueFilter,
376    ) -> Result<Vec<IssueSummary>> {
377        Err(Error::Unsupported(ISSUES_RETIRED.to_string()))
378    }
379
380    async fn create_issue(&self, _req: &NewIssue) -> Result<CreatedIssue> {
381        Err(Error::Unsupported(ISSUES_RETIRED.to_string()))
382    }
383
384    fn conversation_caps(&self, kind: ItemKind) -> ConversationCaps {
385        ConversationCaps::bitbucket(kind)
386    }
387
388    async fn posting_identity(&self, project: &str) -> Result<PostingIdentity> {
389        self.conv_identity(project).await
390    }
391
392    async fn item_timeline(
393        &self,
394        project: &str,
395        key: &ItemKey,
396        older: Option<&PageCursor>,
397        opts: &TimelineOpts,
398    ) -> Result<TimelinePage> {
399        self.conv_timeline(project, key, older, opts).await
400    }
401
402    async fn post_item_comment(
403        &self,
404        project: &str,
405        key: &ItemKey,
406        body: &str,
407        internal: bool,
408    ) -> Result<Comment> {
409        self.conv_post(project, key, body, internal).await
410    }
411
412    async fn reply_in_discussion(
413        &self,
414        project: &str,
415        key: &ItemKey,
416        discussion_id: &str,
417        body: &str,
418    ) -> Result<Comment> {
419        self.conv_reply(project, key, discussion_id, body).await
420    }
421
422    async fn edit_item_comment(
423        &self,
424        project: &str,
425        key: &ItemKey,
426        comment_id: &str,
427        body: &str,
428    ) -> Result<Comment> {
429        self.conv_edit(project, key, comment_id, body).await
430    }
431
432    async fn delete_item_comment(
433        &self,
434        project: &str,
435        key: &ItemKey,
436        comment_id: &str,
437    ) -> Result<()> {
438        self.conv_delete(project, key, comment_id).await
439    }
440}