Skip to main content

bitbucket_cli/cli/
webhook.rs

1use std::io::{IsTerminal, Read};
2
3use anyhow::{Context, Result};
4use clap::Subcommand;
5use colored::Colorize;
6use tabled::{Table, Tabled};
7
8use super::{confirm_or_abort, output_json, parse_repo, print_json};
9use crate::api::BitbucketClient;
10use crate::models::{CreateWebhookRequest, SecretUpdate, Webhook};
11
12#[derive(Subcommand)]
13pub enum WebhookCommands {
14    /// List webhooks on a repository
15    List {
16        /// Repository in format workspace/repo-slug
17        repo: String,
18
19        /// Number of results per page (max 100)
20        #[arg(short, long, default_value = "25")]
21        limit: u32,
22    },
23
24    /// Create a webhook
25    Create {
26        /// Repository in format workspace/repo-slug
27        repo: String,
28
29        /// Destination URL the events are delivered to
30        #[arg(long)]
31        url: String,
32
33        /// Event key to subscribe to (repeatable, e.g. --event repo:push --event pullrequest:created)
34        #[arg(long = "event", value_name = "EVENT", required = true)]
35        events: Vec<String>,
36
37        /// Description of the webhook
38        #[arg(short, long)]
39        description: Option<String>,
40
41        /// Signing secret for the X-Hub-Signature HMAC. Pass `-` to read the
42        /// secret from stdin (recommended: a literal value is visible in the
43        /// process list and shell history). Omit to leave the hook unsigned;
44        /// no equivalent of `update --clear-secret` is needed at creation.
45        #[arg(long, value_name = "SECRET")]
46        secret: Option<String>,
47
48        /// Create the webhook in a disabled state
49        #[arg(long)]
50        inactive: bool,
51    },
52
53    /// View webhook details
54    View {
55        /// Repository in format workspace/repo-slug
56        repo: String,
57
58        /// Webhook UUID (the brace-wrapped UUID shown by `webhook list`)
59        uid: String,
60    },
61
62    /// Update a webhook (unset fields keep their current values)
63    Update {
64        /// Repository in format workspace/repo-slug
65        repo: String,
66
67        /// Webhook UUID (the brace-wrapped UUID shown by `webhook list`)
68        uid: String,
69
70        /// New destination URL
71        #[arg(long)]
72        url: Option<String>,
73
74        /// Replace the subscribed events (repeatable)
75        #[arg(long = "event", value_name = "EVENT")]
76        events: Vec<String>,
77
78        /// New description
79        #[arg(short, long)]
80        description: Option<String>,
81
82        /// Set/replace the signing secret for the X-Hub-Signature HMAC. Pass
83        /// `-` to read the secret from stdin (recommended: a literal value is
84        /// visible in the process list and shell history).
85        #[arg(long, value_name = "SECRET", conflicts_with = "clear_secret")]
86        secret: Option<String>,
87
88        /// Remove the configured signing secret from the webhook
89        #[arg(long)]
90        clear_secret: bool,
91
92        /// Enable or disable the webhook
93        #[arg(long, value_name = "true|false")]
94        active: Option<bool>,
95    },
96
97    /// Delete a webhook
98    Delete {
99        /// Repository in format workspace/repo-slug
100        repo: String,
101
102        /// Webhook UUID (the brace-wrapped UUID shown by `webhook list`)
103        uid: String,
104
105        /// Skip confirmation prompt
106        #[arg(short, long)]
107        yes: bool,
108    },
109}
110
111#[derive(Tabled)]
112struct WebhookRow {
113    #[tabled(rename = "UUID")]
114    uid: String,
115    #[tabled(rename = "URL")]
116    url: String,
117    #[tabled(rename = "ACTIVE")]
118    active: String,
119    #[tabled(rename = "SECRET")]
120    secret: String,
121    #[tabled(rename = "EVENTS")]
122    events: String,
123}
124
125impl WebhookCommands {
126    pub async fn run(self) -> Result<()> {
127        match self {
128            WebhookCommands::List { repo, limit } => {
129                let (workspace, repo_slug) = parse_repo(&repo)?;
130                let client = BitbucketClient::from_stored().await?;
131                let hooks = client
132                    .list_webhooks(&workspace, &repo_slug, Some(limit.clamp(1, 100)))
133                    .await?;
134
135                if output_json() {
136                    return print_json(&hooks.values);
137                }
138
139                if hooks.values.is_empty() {
140                    println!("No webhooks found in {}", repo);
141                    return Ok(());
142                }
143
144                let rows: Vec<WebhookRow> = hooks
145                    .values
146                    .iter()
147                    .map(|h| WebhookRow {
148                        uid: h.uuid.clone().unwrap_or_default(),
149                        url: h.url.clone(),
150                        active: if h.active.unwrap_or(false) {
151                            "Yes"
152                        } else {
153                            "No"
154                        }
155                        .to_string(),
156                        secret: if h.secret_set.unwrap_or(false) {
157                            "Yes"
158                        } else {
159                            "No"
160                        }
161                        .to_string(),
162                        events: h.events.join(", ").chars().take(60).collect(),
163                    })
164                    .collect();
165
166                println!("{}", Table::new(rows));
167
168                if hooks.next.is_some() {
169                    println!(
170                        "\n{} More webhooks available. Use --limit to see more.",
171                        "ℹ".blue()
172                    );
173                }
174
175                Ok(())
176            }
177
178            WebhookCommands::Create {
179                repo,
180                url,
181                events,
182                description,
183                secret,
184                inactive,
185            } => {
186                let (workspace, repo_slug) = parse_repo(&repo)?;
187                let client = BitbucketClient::from_stored().await?;
188
189                let request = CreateWebhookRequest {
190                    description,
191                    url,
192                    active: !inactive,
193                    events,
194                    secret: resolve_secret_update(secret, false)?,
195                };
196
197                let hook = client
198                    .create_webhook(&workspace, &repo_slug, &request)
199                    .await?;
200
201                if output_json() {
202                    return print_json(&hook);
203                }
204
205                println!(
206                    "{} Created webhook {} for {}",
207                    "✓".green(),
208                    hook.uuid.as_deref().unwrap_or("(no uid)").cyan(),
209                    hook.url
210                );
211
212                Ok(())
213            }
214
215            WebhookCommands::View { repo, uid } => {
216                let (workspace, repo_slug) = parse_repo(&repo)?;
217                let client = BitbucketClient::from_stored().await?;
218                let hook = client.get_webhook(&workspace, &repo_slug, &uid).await?;
219
220                if output_json() {
221                    return print_json(&hook);
222                }
223
224                println!("{}", hook.uuid.as_deref().unwrap_or(&uid).bold());
225                println!("{}", "─".repeat(50));
226
227                if let Some(desc) = &hook.description {
228                    if !desc.is_empty() {
229                        println!("{}", desc);
230                        println!();
231                    }
232                }
233
234                println!("{} {}", "URL:".dimmed(), hook.url.cyan());
235                println!(
236                    "{} {}",
237                    "Active:".dimmed(),
238                    if hook.active.unwrap_or(false) {
239                        "Yes"
240                    } else {
241                        "No"
242                    }
243                );
244                println!(
245                    "{} {}",
246                    "Secret:".dimmed(),
247                    if hook.secret_set.unwrap_or(false) {
248                        "Set"
249                    } else {
250                        "Not set"
251                    }
252                );
253
254                if hook.events.is_empty() {
255                    println!("{} (none)", "Events:".dimmed());
256                } else {
257                    println!("{}", "Events:".dimmed());
258                    for event in &hook.events {
259                        println!("  {}", event);
260                    }
261                }
262
263                Ok(())
264            }
265
266            WebhookCommands::Update {
267                repo,
268                uid,
269                url,
270                events,
271                description,
272                secret,
273                clear_secret,
274                active,
275            } => {
276                let (workspace, repo_slug) = parse_repo(&repo)?;
277
278                let secret_update = resolve_secret_update(secret, clear_secret)?;
279
280                if url.is_none()
281                    && events.is_empty()
282                    && description.is_none()
283                    && active.is_none()
284                    && secret_update == SecretUpdate::Unchanged
285                {
286                    anyhow::bail!(
287                        "Nothing to update. Pass at least one option, e.g. --url or --active."
288                    );
289                }
290
291                let client = BitbucketClient::from_stored().await?;
292
293                // PUT replaces the whole subscription, so merge the requested
294                // changes into the current state before sending.
295                let current = client.get_webhook(&workspace, &repo_slug, &uid).await?;
296                let request =
297                    build_webhook_update(current, url, events, description, active, secret_update);
298
299                let updated = client
300                    .update_webhook(&workspace, &repo_slug, &uid, &request)
301                    .await?;
302
303                if output_json() {
304                    return print_json(&updated);
305                }
306
307                println!(
308                    "{} Updated webhook {}",
309                    "✓".green(),
310                    updated.uuid.as_deref().unwrap_or(&uid).cyan()
311                );
312
313                Ok(())
314            }
315
316            WebhookCommands::Delete { repo, uid, yes } => {
317                let (workspace, repo_slug) = parse_repo(&repo)?;
318
319                if !yes
320                    && !confirm_or_abort(format!("Delete webhook {} from {}?", uid.red(), repo))?
321                {
322                    return Ok(());
323                }
324
325                let client = BitbucketClient::from_stored().await?;
326                client.delete_webhook(&workspace, &repo_slug, &uid).await?;
327
328                if output_json() {
329                    return print_json(&serde_json::json!({ "ok": true }));
330                }
331
332                println!("{} Deleted webhook {}", "✓".green(), uid);
333
334                Ok(())
335            }
336        }
337    }
338}
339
340/// Translate the `--secret` / `--clear-secret` flags into a [`SecretUpdate`].
341///
342/// `--secret <value>` sets the secret; the sentinel `--secret -` reads the
343/// secret from stdin so callers can pipe it in without exposing it in the
344/// process list or shell history. `--clear-secret` removes the secret. Passing
345/// neither leaves the secret untouched. Clap enforces that the two flags are
346/// mutually exclusive, so `secret.is_some()` takes precedence defensively.
347fn resolve_secret_update(secret: Option<String>, clear_secret: bool) -> Result<SecretUpdate> {
348    match (secret, clear_secret) {
349        (Some(value), _) if value == "-" => Ok(SecretUpdate::Set(read_secret_from_stdin()?)),
350        (Some(value), _) => Ok(SecretUpdate::Set(value)),
351        (None, true) => Ok(SecretUpdate::Clear),
352        (None, false) => Ok(SecretUpdate::Unchanged),
353    }
354}
355
356/// Read a signing secret from stdin, trimming a single trailing newline so
357/// `printf %s | ...` and `echo | ...` both work. Rejects an empty secret so a
358/// stray empty pipe can't silently create an unsigned hook the user believed
359/// was signed.
360fn read_secret_from_stdin() -> Result<String> {
361    let mut buf = String::new();
362    if std::io::stdin().is_terminal() {
363        anyhow::bail!(
364            "`--secret -` expects the secret on stdin, but stdin is a terminal. \
365             Pipe the secret in, e.g. `printf %s \"$SECRET\" | bitbucket ... --secret -`."
366        );
367    }
368    std::io::stdin()
369        .read_to_string(&mut buf)
370        .context("Failed to read secret from stdin")?;
371    let secret = buf.strip_suffix('\n').unwrap_or(&buf);
372    let secret = secret.strip_suffix('\r').unwrap_or(secret);
373    if secret.is_empty() {
374        anyhow::bail!("Secret read from stdin was empty");
375    }
376    Ok(secret.to_string())
377}
378
379/// Merge `webhook update` flags into the current subscription to produce the
380/// full replacement body Bitbucket's PUT expects. Unset flags keep the current
381/// values; a webhook with no recorded `active` state defaults to enabled.
382fn build_webhook_update(
383    current: Webhook,
384    url: Option<String>,
385    events: Vec<String>,
386    description: Option<String>,
387    active: Option<bool>,
388    secret: SecretUpdate,
389) -> CreateWebhookRequest {
390    CreateWebhookRequest {
391        description: description.or(current.description),
392        url: url.unwrap_or(current.url),
393        active: active.or(current.active).unwrap_or(true),
394        events: if events.is_empty() {
395            current.events
396        } else {
397            events
398        },
399        secret,
400    }
401}
402
403#[cfg(test)]
404mod tests {
405    use super::{build_webhook_update, resolve_secret_update};
406    use crate::models::{SecretUpdate, Webhook};
407
408    fn current() -> Webhook {
409        Webhook {
410            uuid: Some("{uid}".to_string()),
411            url: "https://old.example.com/hook".to_string(),
412            description: Some("old description".to_string()),
413            active: Some(true),
414            events: vec!["repo:push".to_string()],
415            secret_set: Some(true),
416        }
417    }
418
419    #[test]
420    fn build_webhook_update_keeps_current_values_when_flags_unset() {
421        let request = build_webhook_update(
422            current(),
423            None,
424            Vec::new(),
425            None,
426            None,
427            SecretUpdate::Unchanged,
428        );
429        assert_eq!(request.url, "https://old.example.com/hook");
430        assert_eq!(request.description.as_deref(), Some("old description"));
431        assert!(request.active);
432        assert_eq!(request.events, vec!["repo:push".to_string()]);
433        assert_eq!(request.secret, SecretUpdate::Unchanged);
434    }
435
436    #[test]
437    fn build_webhook_update_applies_changed_fields() {
438        let request = build_webhook_update(
439            current(),
440            Some("https://new.example.com/hook".to_string()),
441            vec!["pullrequest:created".to_string()],
442            Some("new description".to_string()),
443            Some(false),
444            SecretUpdate::Set("topsecret".to_string()),
445        );
446        assert_eq!(request.url, "https://new.example.com/hook");
447        assert_eq!(request.description.as_deref(), Some("new description"));
448        assert!(!request.active);
449        assert_eq!(request.events, vec!["pullrequest:created".to_string()]);
450        assert_eq!(request.secret, SecretUpdate::Set("topsecret".to_string()));
451    }
452
453    #[test]
454    fn build_webhook_update_defaults_unknown_active_state_to_enabled() {
455        let mut hook = current();
456        hook.active = None;
457        let request =
458            build_webhook_update(hook, None, Vec::new(), None, None, SecretUpdate::Unchanged);
459        assert!(request.active);
460    }
461
462    #[test]
463    fn build_webhook_update_can_clear_secret() {
464        let request =
465            build_webhook_update(current(), None, Vec::new(), None, None, SecretUpdate::Clear);
466        assert_eq!(request.secret, SecretUpdate::Clear);
467    }
468
469    #[test]
470    fn build_webhook_update_leaves_secret_unchanged_by_default() {
471        // Merging must never resurrect a plaintext secret from the read model
472        // (Bitbucket never returns one), so the default is always Unchanged.
473        let request = build_webhook_update(
474            current(),
475            Some("https://new.example.com/hook".to_string()),
476            Vec::new(),
477            None,
478            None,
479            SecretUpdate::Unchanged,
480        );
481        assert_eq!(request.secret, SecretUpdate::Unchanged);
482    }
483
484    #[test]
485    fn resolve_secret_update_sets_literal_value() {
486        let resolved = resolve_secret_update(Some("hunter2".to_string()), false).unwrap();
487        assert_eq!(resolved, SecretUpdate::Set("hunter2".to_string()));
488    }
489
490    #[test]
491    fn resolve_secret_update_clears_when_flag_set() {
492        let resolved = resolve_secret_update(None, true).unwrap();
493        assert_eq!(resolved, SecretUpdate::Clear);
494    }
495
496    #[test]
497    fn resolve_secret_update_unchanged_when_no_flags() {
498        let resolved = resolve_secret_update(None, false).unwrap();
499        assert_eq!(resolved, SecretUpdate::Unchanged);
500    }
501
502    #[test]
503    fn resolve_secret_update_literal_value_wins_over_clear() {
504        // Clap enforces mutual exclusion, but the resolver must still be
505        // deterministic if both ever arrive together: an explicit value wins.
506        let resolved = resolve_secret_update(Some("hunter2".to_string()), true).unwrap();
507        assert_eq!(resolved, SecretUpdate::Set("hunter2".to_string()));
508    }
509}