Skip to main content

bitbucket_cli/models/
webhook.rs

1use serde::{Deserialize, Serialize};
2
3use super::user::User;
4
5/// A repository webhook subscription.
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct Webhook {
8    /// Server-assigned identifier, a UUID wrapped in braces (e.g. `{1a2b-...}`).
9    pub uuid: Option<String>,
10    /// Destination URL the events are delivered to.
11    pub url: String,
12    pub description: Option<String>,
13    pub active: Option<bool>,
14    /// Event keys this hook subscribes to (e.g. `repo:push`).
15    #[serde(default)]
16    pub events: Vec<String>,
17    /// Whether a signing secret is configured on this hook. Bitbucket returns
18    /// this flag on reads but never the secret value itself.
19    #[serde(default)]
20    pub secret_set: Option<bool>,
21}
22
23/// How a webhook subscription's signing secret should be handled when sending
24/// a create/replace body to Bitbucket.
25///
26/// Bitbucket never returns the plaintext secret on reads, so the update flow
27/// (which does a GET-then-PUT merge) must distinguish "leave the existing
28/// secret untouched" from "clear it". Omitting the `secret` field entirely
29/// preserves the current secret; sending `null` clears it.
30#[derive(Debug, Clone, PartialEq, Eq, Default)]
31pub enum SecretUpdate {
32    /// Do not send the `secret` field; keep whatever secret is configured.
33    #[default]
34    Unchanged,
35    /// Send `"secret": null` to remove the configured secret.
36    Clear,
37    /// Send `"secret": "<value>"` to set/replace the secret.
38    Set(String),
39}
40
41/// Body for creating (POST) or replacing (PUT) a webhook subscription.
42///
43/// Bitbucket's PUT replaces the whole subscription, so updates send a full
44/// body built by merging the current hook with the changed fields.
45#[derive(Debug, Clone, Serialize, Deserialize)]
46#[non_exhaustive]
47pub struct CreateWebhookRequest {
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub description: Option<String>,
50    pub url: String,
51    pub active: bool,
52    pub events: Vec<String>,
53    /// Signing secret handling. Serialized as follows:
54    /// - `Unchanged` -> field omitted (keeps the existing secret)
55    /// - `Clear`     -> `"secret": null` (removes the secret)
56    /// - `Set(v)`    -> `"secret": "v"` (sets/replaces the secret)
57    #[serde(
58        default,
59        skip_deserializing,
60        skip_serializing_if = "SecretUpdate::is_unchanged",
61        serialize_with = "serialize_secret"
62    )]
63    pub secret: SecretUpdate,
64}
65
66impl SecretUpdate {
67    fn is_unchanged(&self) -> bool {
68        matches!(self, SecretUpdate::Unchanged)
69    }
70}
71
72/// Serialize the `secret` field. Only called when the value is not
73/// `Unchanged` (that case is skipped via `skip_serializing_if`), so this maps
74/// `Clear` to JSON `null` and `Set(v)` to the string value.
75fn serialize_secret<S>(secret: &SecretUpdate, serializer: S) -> Result<S::Ok, S::Error>
76where
77    S: serde::Serializer,
78{
79    match secret {
80        SecretUpdate::Clear => serializer.serialize_none(),
81        SecretUpdate::Set(value) => serializer.serialize_some(value),
82        // Unreachable because `skip_serializing_if` filters this variant out
83        // before serialization. Keep the match total (serialize as null rather
84        // than panicking in a serializer) but assert the invariant in debug.
85        SecretUpdate::Unchanged => {
86            debug_assert!(false, "Unchanged should be skipped by skip_serializing_if");
87            serializer.serialize_none()
88        }
89    }
90}
91
92/// A branch restriction rule on a repository.
93#[derive(Debug, Clone, Serialize, Deserialize)]
94pub struct BranchRestriction {
95    pub id: Option<u64>,
96    /// Rule kind (e.g. `push`, `force`, `delete`, `require_approvals_to_merge`).
97    pub kind: String,
98    /// Branch pattern the rule applies to (glob, e.g. `main` or `release/*`).
99    pub pattern: Option<String>,
100    /// How `pattern` is interpreted (`glob` or `branching_model`).
101    pub branch_match_kind: Option<String>,
102    /// Numeric parameter for kinds that need one (e.g. required approval count).
103    pub value: Option<u64>,
104    /// Users exempt from the rule (for kinds like `push`).
105    pub users: Option<Vec<User>>,
106}
107
108/// A user's explicit permission on a repository.
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct UserPermission {
111    pub user: Option<User>,
112    /// Permission level: `read`, `write`, or `admin`.
113    pub permission: String,
114}
115
116/// A group's explicit permission on a repository.
117#[derive(Debug, Clone, Serialize, Deserialize)]
118pub struct GroupPermission {
119    pub group: Option<GroupRef>,
120    /// Permission level: `read`, `write`, or `admin`.
121    pub permission: String,
122}
123
124/// Minimal reference to a workspace group as embedded in permission entries.
125#[derive(Debug, Clone, Serialize, Deserialize)]
126pub struct GroupRef {
127    pub name: Option<String>,
128    pub slug: Option<String>,
129}
130
131#[cfg(test)]
132mod tests {
133    use super::{CreateWebhookRequest, SecretUpdate, Webhook};
134
135    #[test]
136    fn create_webhook_request_omits_unset_description() {
137        let request = CreateWebhookRequest {
138            description: None,
139            url: "https://example.com/hook".to_string(),
140            active: true,
141            events: vec!["repo:push".to_string()],
142            secret: SecretUpdate::Unchanged,
143        };
144
145        let json = serde_json::to_value(&request).unwrap();
146        assert_eq!(
147            json,
148            serde_json::json!({
149                "url": "https://example.com/hook",
150                "active": true,
151                "events": ["repo:push"],
152            })
153        );
154    }
155
156    #[test]
157    fn create_webhook_request_includes_description_when_set() {
158        let request = CreateWebhookRequest {
159            description: Some("CI trigger".to_string()),
160            url: "https://example.com/hook".to_string(),
161            active: false,
162            events: vec![],
163            secret: SecretUpdate::Unchanged,
164        };
165
166        let json = serde_json::to_value(&request).unwrap();
167        assert_eq!(json["description"], "CI trigger");
168        assert_eq!(json["active"], false);
169    }
170
171    #[test]
172    fn create_webhook_request_omits_secret_when_unchanged() {
173        let request = CreateWebhookRequest {
174            description: None,
175            url: "https://example.com/hook".to_string(),
176            active: true,
177            events: vec!["repo:push".to_string()],
178            secret: SecretUpdate::Unchanged,
179        };
180
181        let json = serde_json::to_value(&request).unwrap();
182        assert!(
183            json.get("secret").is_none(),
184            "secret must be omitted when unchanged, got {json}"
185        );
186    }
187
188    #[test]
189    fn create_webhook_request_sends_secret_string_when_set() {
190        let request = CreateWebhookRequest {
191            description: None,
192            url: "https://example.com/hook".to_string(),
193            active: true,
194            events: vec!["repo:push".to_string()],
195            secret: SecretUpdate::Set("s3cr3t".to_string()),
196        };
197
198        let json = serde_json::to_value(&request).unwrap();
199        assert_eq!(json["secret"], "s3cr3t");
200    }
201
202    #[test]
203    fn create_webhook_request_sends_null_secret_when_cleared() {
204        let request = CreateWebhookRequest {
205            description: None,
206            url: "https://example.com/hook".to_string(),
207            active: true,
208            events: vec!["repo:push".to_string()],
209            secret: SecretUpdate::Clear,
210        };
211
212        let json = serde_json::to_value(&request).unwrap();
213        assert!(
214            json.get("secret").is_some(),
215            "cleared secret must send the field, got {json}"
216        );
217        assert!(
218            json["secret"].is_null(),
219            "cleared secret must serialize to null, got {}",
220            json["secret"]
221        );
222    }
223
224    #[test]
225    fn webhook_deserializes_without_events() {
226        let webhook: Webhook =
227            serde_json::from_str(r#"{ "url": "https://example.com/hook" }"#).unwrap();
228        assert!(webhook.events.is_empty());
229        assert_eq!(webhook.uuid, None);
230        assert_eq!(webhook.secret_set, None);
231    }
232
233    #[test]
234    fn webhook_deserializes_secret_set_flag() {
235        let webhook: Webhook =
236            serde_json::from_str(r#"{ "url": "https://example.com/hook", "secret_set": true }"#)
237                .unwrap();
238        assert_eq!(webhook.secret_set, Some(true));
239    }
240
241    #[test]
242    fn webhook_never_reexposes_returned_secret() {
243        // Bitbucket create/update responses may echo a plaintext `secret`.
244        // The read model must drop it so it can never leak back out through
245        // `--output json`. This guards against a future `#[serde(flatten)]`
246        // catch-all silently re-surfacing the value.
247        let webhook: Webhook = serde_json::from_str(
248            r#"{ "url": "https://example.com/hook", "secret": "leaked", "secret_set": true }"#,
249        )
250        .unwrap();
251
252        let json = serde_json::to_value(&webhook).unwrap();
253        assert!(
254            json.get("secret").is_none(),
255            "the plaintext secret must never be re-serialized, got {json}"
256        );
257    }
258}