brake 2026.8.3

A brake on breaking API changes. Checks OpenAPI, protobuf and GraphQL contracts for backward compatibility, hermetically.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
use std::fs;
use std::path::{Path, PathBuf};

use serde::Deserialize;
use thiserror::Error;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
    pub defaults: Defaults,
    pub contracts: Vec<ContractConfig>,
}

impl Config {
    pub fn from_path(path: &Path) -> Result<Self, ConfigError> {
        let contents = fs::read_to_string(path).map_err(|source| ConfigError::ReadFile {
            path: path.to_path_buf(),
            source,
        })?;
        Self::parse(&contents)
    }

    pub fn parse(contents: &str) -> Result<Self, ConfigError> {
        let raw: RawConfig = toml::from_str(contents).map_err(ConfigError::ParseToml)?;
        raw.validate()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Defaults {
    pub compatibility: Compatibility,
    pub baseline: Option<Baseline>,
}

impl Default for Defaults {
    fn default() -> Self {
        Self {
            compatibility: Compatibility::WireJson,
            baseline: None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContractConfig {
    pub name: String,
    pub format: ContractFormat,
    pub source: PathBuf,
    pub compatibility: Option<Compatibility>,
    pub baseline: Option<Baseline>,
    pub allow: Vec<Suppression>,
    pub generated: Option<GeneratedConfig>,
}

impl ContractConfig {
    pub fn effective_compatibility(&self, defaults: &Defaults) -> Compatibility {
        self.compatibility.unwrap_or(defaults.compatibility)
    }

    pub fn effective_baseline<'a>(&'a self, defaults: &'a Defaults) -> Option<&'a Baseline> {
        self.baseline.as_ref().or(defaults.baseline.as_ref())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Compatibility {
    Wire,
    WireJson,
    Surface,
    Strict,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ContractFormat {
    Openapi,
    Proto,
    Graphql,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Baseline {
    File(PathBuf),
    /// A ref and an explicit path. The only shape that takes a path, and the
    /// reason to prefer the others — see `design/02-contract-gates.md` §2.1.
    Git {
        spec: String,
    },
    GitMergeBase {
        reference: String,
    },
    /// A named release tag. The path comes from `source`.
    Tag {
        name: String,
    },
    /// The newest tag matching this glob that HEAD descends from.
    LatestTag {
        pattern: String,
    },
    /// Any revision — a commit, a branch, a tag.
    Rev {
        rev: String,
    },
}

impl Baseline {
    pub fn strategy_name(&self) -> &'static str {
        match self {
            Self::File(_) => "file",
            Self::Git { .. } => "git",
            Self::GitMergeBase { .. } => "git-merge-base",
            Self::Tag { .. } => "tag",
            Self::LatestTag { .. } => "latest-tag",
            Self::Rev { .. } => "rev",
        }
    }

    /// Does this baseline answer "has the published API broken since we
    /// shipped?" rather than "is this change safe to merge?"
    ///
    /// The distinction is not cosmetic: a release baseline does not forgive
    /// what is already on the trunk, so it is the wrong default for a commit
    /// hook and the right one for a release gate.
    #[must_use]
    pub fn is_release_baseline(&self) -> bool {
        matches!(
            self,
            Self::Tag { .. } | Self::LatestTag { .. } | Self::Rev { .. }
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Suppression {
    pub rule: String,
    pub endpoint: Option<String>,
    pub field: Option<String>,
    pub reason: String,
    pub expires: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GeneratedConfig {
    pub command: String,
}

#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("failed to read config file {path}: {source}")]
    ReadFile {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("failed to parse brake.toml: {0}")]
    ParseToml(toml::de::Error),
    #[error("invalid brake.toml: {0}")]
    Validation(String),
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawConfig {
    #[serde(default)]
    defaults: RawDefaults,
    #[serde(default, rename = "contract")]
    contracts: Vec<RawContract>,
}

impl RawConfig {
    fn validate(self) -> Result<Config, ConfigError> {
        let defaults = self.defaults.validate("defaults")?;
        let mut contracts = Vec::with_capacity(self.contracts.len());
        for contract in self.contracts {
            contracts.push(contract.validate()?);
        }
        Ok(Config {
            defaults,
            contracts,
        })
    }
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawDefaults {
    compatibility: Option<Compatibility>,
    baseline: Option<RawBaseline>,
}

impl RawDefaults {
    fn validate(self, context: &str) -> Result<Defaults, ConfigError> {
        Ok(Defaults {
            compatibility: self.compatibility.unwrap_or(Compatibility::WireJson),
            baseline: self.baseline.map(|raw| raw.validate(context)).transpose()?,
        })
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawContract {
    name: String,
    format: ContractFormat,
    source: PathBuf,
    compatibility: Option<Compatibility>,
    baseline: Option<RawBaseline>,
    #[serde(default)]
    allow: Vec<RawSuppression>,
    generated: Option<RawGenerated>,
}

impl RawContract {
    fn validate(self) -> Result<ContractConfig, ConfigError> {
        if self.name.trim().is_empty() {
            return Err(ConfigError::Validation(
                "contract name cannot be empty".into(),
            ));
        }
        if self.source.as_os_str().is_empty() {
            return Err(ConfigError::Validation(format!(
                "contract `{}` has an empty source path",
                self.name
            )));
        }

        let mut allow = Vec::with_capacity(self.allow.len());
        for suppression in self.allow {
            allow.push(suppression.validate(&self.name)?);
        }

        Ok(ContractConfig {
            name: self.name.clone(),
            format: self.format,
            source: self.source,
            compatibility: self.compatibility,
            baseline: self
                .baseline
                .map(|raw| raw.validate(&format!("contract `{}`", self.name)))
                .transpose()?,
            allow,
            generated: self
                .generated
                .map(|raw| raw.validate(&self.name))
                .transpose()?,
        })
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawGenerated {
    command: String,
}

impl RawGenerated {
    fn validate(self, contract_name: &str) -> Result<GeneratedConfig, ConfigError> {
        if self.command.trim().is_empty() {
            return Err(ConfigError::Validation(format!(
                "contract `{contract_name}` generated.command cannot be empty"
            )));
        }
        Ok(GeneratedConfig {
            command: self.command,
        })
    }
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawBaseline {
    file: Option<PathBuf>,
    git: Option<String>,
    #[serde(rename = "git-merge-base")]
    git_merge_base: Option<String>,
    tag: Option<String>,
    #[serde(rename = "latest-tag")]
    latest_tag: Option<String>,
    rev: Option<String>,
}

impl RawBaseline {
    fn validate(self, context: &str) -> Result<Baseline, ConfigError> {
        // Table-driven so adding a shape cannot forget the arity check, which
        // is what stops `{ tag = "v1", rev = "abc" }` from silently picking one.
        let candidates: [(&str, Option<String>); 5] = [
            ("git", self.git),
            ("git-merge-base", self.git_merge_base),
            ("tag", self.tag),
            ("latest-tag", self.latest_tag),
            ("rev", self.rev),
        ];

        let mut chosen: Option<(&str, String)> = None;
        let mut set = usize::from(self.file.is_some());
        for (key, value) in candidates {
            let Some(value) = value else { continue };
            set += 1;
            if value.trim().is_empty() {
                return Err(ConfigError::Validation(format!(
                    "{context} baseline `{key}` cannot be empty"
                )));
            }
            chosen.get_or_insert((key, value));
        }

        if set != 1 {
            return Err(ConfigError::Validation(format!(
                "{context} baseline must set exactly one of `file`, `git`, `git-merge-base`, \
                 `tag`, `latest-tag`, or `rev`{}",
                if set > 1 { ", and it sets several" } else { "" }
            )));
        }

        if let Some(file) = self.file {
            if file.as_os_str().is_empty() {
                return Err(ConfigError::Validation(format!(
                    "{context} baseline file path cannot be empty"
                )));
            }
            return Ok(Baseline::File(file));
        }

        let (key, value) = chosen.expect("exactly one is set and it is not `file`");
        Ok(match key {
            "git" => Baseline::Git { spec: value },
            "git-merge-base" => Baseline::GitMergeBase { reference: value },
            "tag" => Baseline::Tag { name: value },
            "latest-tag" => Baseline::LatestTag { pattern: value },
            "rev" => Baseline::Rev { rev: value },
            other => unreachable!("unhandled baseline key `{other}`"),
        })
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawSuppression {
    rule: String,
    endpoint: Option<String>,
    field: Option<String>,
    reason: String,
    expires: Option<Expires>,
}

/// `expires`, however it was written.
///
/// TOML has a native date type, so `expires = 2026-09-01` without quotes is
/// the natural thing to write — and deserialising straight into `String`
/// rejected it with serde's `invalid type: map, expected a string`, which
/// tells a reader nothing about what to do. Both spellings are accepted and
/// normalised, because the tool knows perfectly well what was meant.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Expires {
    Text(String),
    Date(toml::value::Datetime),
}

impl std::fmt::Display for Expires {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Text(text) => formatter.write_str(text),
            // `Datetime`'s own rendering is the TOML spelling, which for a
            // local date is already YYYY-MM-DD.
            Self::Date(date) => write!(formatter, "{date}"),
        }
    }
}

impl RawSuppression {
    fn validate(self, contract_name: &str) -> Result<Suppression, ConfigError> {
        if self.rule.trim().is_empty() {
            return Err(ConfigError::Validation(format!(
                "contract `{contract_name}` suppression rule cannot be empty"
            )));
        }
        if self.reason.trim().is_empty() {
            return Err(ConfigError::Validation(format!(
                "contract `{contract_name}` suppression for rule `{}` must include a non-empty reason",
                self.rule
            )));
        }

        // An unreadable date silently never expires, which turns a
        // time-boxed exception into a permanent one.
        let expires = self.expires.map(|expires| expires.to_string());
        if let Some(expires) = &expires
            && crate::rules::parse_date(expires).is_none()
        {
            return Err(ConfigError::Validation(format!(
                "contract `{contract_name}` suppression for rule `{}` has an unreadable \
                 `expires` value `{expires}`; use YYYY-MM-DD",
                self.rule
            )));
        }
        if crate::rules::catalogue::lookup(&self.rule).is_none() {
            return Err(ConfigError::Validation(format!(
                "contract `{contract_name}` suppresses unknown rule `{}`; \
                 run `brake explain <rule-id>` to see the catalogue",
                self.rule
            )));
        }

        Ok(Suppression {
            rule: self.rule,
            endpoint: self.endpoint,
            field: self.field,
            reason: self.reason,
            expires,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn expires_accepts_both_spellings_of_a_date() {
        // TOML has a native date type, so writing one unquoted is the natural
        // thing to do. Rejecting it with serde's `invalid type: map, expected
        // a string` told a reader nothing about what to do instead.
        let with = |expires: &str| {
            format!(
                "[[contract]]\nname=\"c\"\nformat=\"openapi\"\nsource=\"a.yaml\"\n\
                 [[contract.allow]]\nrule=\"endpoint-removed\"\nreason=\"r\"\n\
                 expires={expires}\n"
            )
        };

        for spelling in ["\"2026-09-01\"", "2026-09-01"] {
            let config = Config::parse(&with(spelling))
                .unwrap_or_else(|error| panic!("`expires={spelling}` should parse: {error}"));
            assert_eq!(
                config.contracts[0].allow[0].expires.as_deref(),
                Some("2026-09-01"),
                "both spellings must normalise to the same date"
            );
        }
    }

    #[test]
    fn expires_still_rejects_something_that_is_not_a_date() {
        let config = Config::parse(
            "[[contract]]\nname=\"c\"\nformat=\"openapi\"\nsource=\"a.yaml\"\n\
             [[contract.allow]]\nrule=\"endpoint-removed\"\nreason=\"r\"\n\
             expires=\"soon\"\n",
        );
        let error = config.expect_err("`soon` is not a date").to_string();
        assert!(error.contains("YYYY-MM-DD"), "{error}");
    }

    #[test]
    fn parses_defaults_contract_and_suppression() {
        let config = Config::parse(
            r#"
            [defaults]
            compatibility = "wire-json"
            baseline = { file = "api/default-openapi.baseline.yaml" }

            [[contract]]
            name = "payments"
            format = "openapi"
            source = "api/payments-openapi.yaml"

            [[contract.allow]]
            rule = "response-field-removed"
            endpoint = "GET /payments/{id}"
            field = "legacy_reference"
            reason = "Removed after deprecation window"
            expires = "2026-09-01"
        "#,
        )
        .expect("config should parse");

        assert_eq!(config.defaults.compatibility, Compatibility::WireJson);
        assert_eq!(
            config.defaults.baseline,
            Some(Baseline::File(PathBuf::from(
                "api/default-openapi.baseline.yaml"
            )))
        );
        assert_eq!(config.contracts.len(), 1);
        assert_eq!(config.contracts[0].name, "payments");
        assert_eq!(config.contracts[0].allow.len(), 1);
        assert!(config.contracts[0].generated.is_none());
    }

    #[test]
    fn suppression_requires_reason() {
        let error = Config::parse(
            r#"
            [[contract]]
            name = "payments"
            format = "openapi"
            source = "api/payments-openapi.yaml"

            [[contract.allow]]
            rule = "response-field-removed"
            endpoint = "GET /payments/{id}"
            field = "legacy_reference"
        "#,
        )
        .expect_err("suppression without reason must fail");

        assert!(error.to_string().contains("reason"));
    }

    #[test]
    fn baseline_requires_exactly_one_strategy() {
        let error = Config::parse(
            r#"
            [defaults]
            baseline = { file = "a.yaml", git = "origin/main:api/a.yaml" }
        "#,
        )
        .expect_err("multiple baseline strategies must fail");

        assert!(error.to_string().contains("exactly one"));
    }

    #[test]
    fn default_compatibility_is_wire_json() {
        let config = Config::parse(
            r#"
            [[contract]]
            name = "ledger"
            format = "openapi"
            source = "api/ledger-openapi.yaml"
        "#,
        )
        .expect("config should parse");

        assert_eq!(config.defaults.compatibility, Compatibility::WireJson);
        assert_eq!(
            config.contracts[0].effective_compatibility(&config.defaults),
            Compatibility::WireJson
        );
    }

    #[test]
    fn parses_generated_command() {
        let config = Config::parse(
            r#"
            [[contract]]
            name = "payments"
            format = "openapi"
            source = "api/payments-openapi.yaml"
            generated = { command = "echo generated" }
        "#,
        )
        .expect("config should parse");

        assert_eq!(
            config.contracts[0]
                .generated
                .as_ref()
                .expect("generated config")
                .command,
            "echo generated"
        );
    }
}