footing 0.4.1

Feature-gated foundations for Rust backend services
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
use std::borrow::Cow;

use thiserror::Error;
use utoipa::openapi::{
    Components, OpenApi, RefOr, Required,
    path::{Operation, Parameter, ParameterIn, PathItem},
};

use crate::{
    http::{
        EndpointContract, EndpointContractRegistry, EndpointContractSnapshot,
        EndpointContractValidationError, EndpointPagination, IDEMPOTENCY_KEY_HEADER_NAME,
        IdempotencyRequestPolicy,
    },
    result::{ClassifyError, ErrorKind},
};

/// Operation extension containing a versioned footing endpoint contract.
pub const CONTRACT_EXTENSION: &str = "x-footing-contract";

/// Mismatch between an endpoint registry and the documented application routes.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum OpenApiContractError {
    /// The registry itself is invalid.
    #[error(transparent)]
    InvalidContracts(#[from] EndpointContractValidationError),
    /// A registered contract has no corresponding OpenAPI operation.
    #[error("endpoint contract {method} {path} has no OpenAPI operation")]
    UndocumentedEndpoint {
        /// HTTP method of the missing operation.
        method: &'static str,
        /// Literal route pattern, including parameter names.
        path: String,
    },
    /// An OpenAPI operation has no matching contract.
    #[error("OpenAPI operation {method} {path} has no endpoint contract")]
    OperationWithoutContract {
        /// HTTP method of the unexpected operation.
        method: &'static str,
        /// Documented path.
        path: String,
    },
    /// A path item has no operations that can be reconciled.
    #[error("OpenAPI path {path} contains no operations")]
    EmptyPathItem {
        /// Documented path.
        path: String,
    },
    /// A path item uses references or methods that cannot be reconciled.
    #[error("OpenAPI path {path}: {reason}")]
    UnsupportedPathItem {
        /// Documented path.
        path: String,
        /// Description of the unsupported path item.
        reason: &'static str,
    },
    /// Existing footing metadata disagrees with the registry.
    #[error("OpenAPI operation {method} {path} has conflicting footing metadata")]
    ConflictingMetadata {
        /// HTTP method of the conflicting operation.
        method: &'static str,
        /// Documented path.
        path: String,
    },
    /// A parameter required by a footing contract is missing or contradictory.
    #[error("OpenAPI operation {method} {path}: parameter {name} {reason}")]
    InvalidParameter {
        /// HTTP method of the operation.
        method: &'static str,
        /// Documented path.
        path: String,
        /// Name of the contract parameter.
        name: &'static str,
        /// Description of the mismatch.
        reason: &'static str,
    },
    /// Serializing the contract metadata failed.
    #[error("failed to serialize OpenAPI contract metadata")]
    Serialization(#[from] serde_json::Error),
}

impl ClassifyError for OpenApiContractError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::Serialization(_) => ErrorKind::Internal,
            _ => ErrorKind::Validation,
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidContracts(_) => "openapi_invalid_contracts",
            Self::UndocumentedEndpoint { .. } => "openapi_undocumented_endpoint",
            Self::OperationWithoutContract { .. } => "openapi_operation_without_contract",
            Self::EmptyPathItem { .. } => "openapi_empty_path_item",
            Self::UnsupportedPathItem { .. } => "openapi_unsupported_path_item",
            Self::ConflictingMetadata { .. } => "openapi_conflicting_metadata",
            Self::InvalidParameter { .. } => "openapi_invalid_contract_parameter",
            Self::Serialization(_) => "openapi_contract_serialization_failed",
        })
    }
}

/// Checks exact method/path coverage and documented footing request policies.
///
/// Cursor/offset contracts require their query parameters; idempotency contracts
/// require a header with the matching requiredness. Operation parameters override
/// path-level parameters, and header names are compared case-insensitively.
/// Custom pagination bounds are installed with [`super::OpenApiRoute`].
///
/// This validates documentation coverage, not the router or its authorization
/// behavior. [`super::OpenApiRouter::into_parts_with_stack`] and
/// [`crate::http::EndpointRouter`] bind contracts to actual Axum registrations
/// and validate their middleware policies. Template names
/// must match literally; `/items/{id}` and `/items/{key}` are different contracts.
/// OpenAPI TRACE operations have no counterpart in footing and are rejected.
/// Referenced path items, QUERY and additional operations are unsupported and
/// rejected rather than excluded from coverage checks.
pub fn validate_contracts<P: Copy + 'static>(
    document: &OpenApi,
    registry: &EndpointContractRegistry<'_, P>,
) -> Result<(), OpenApiContractError> {
    registry.validate()?;
    for (path, item) in &document.paths.paths {
        validate_supported_path_item(item).map_err(|reason| {
            OpenApiContractError::UnsupportedPathItem {
                path: path.clone(),
                reason,
            }
        })?;
    }
    for endpoint in registry.endpoints() {
        let method = endpoint.method().as_str();
        let path = endpoint.path().as_str();
        let (item, operation) = document
            .paths
            .paths
            .get(path)
            .and_then(|item| {
                operations(item)
                    .into_iter()
                    .find_map(|(candidate, operation)| {
                        (candidate == method)
                            .then_some(operation)
                            .flatten()
                            .map(|operation| (item, operation))
                    })
            })
            .ok_or_else(|| OpenApiContractError::UndocumentedEndpoint {
                method,
                path: path.to_owned(),
            })?;
        validate_parameters(endpoint, item, operation, document.components.as_ref())?;
    }
    for (path, item) in &document.paths.paths {
        let operations = operations(item);
        if operations.iter().all(|(_, operation)| operation.is_none()) {
            return Err(OpenApiContractError::EmptyPathItem { path: path.clone() });
        }
        for (method, operation) in operations {
            if operation.is_some()
                && !registry.endpoints().iter().any(|endpoint| {
                    endpoint.method().as_str() == method && endpoint.path().as_str() == path
                })
            {
                return Err(OpenApiContractError::OperationWithoutContract {
                    method,
                    path: path.clone(),
                });
            }
        }
    }
    Ok(())
}

/// Validates coverage and annotates each operation with its endpoint contract.
///
/// Takes ownership so errors never expose a partially annotated document.
/// Existing operation metadata, parameters, schemas, security, and responses
/// are preserved. Conflicting `x-footing-contract` values are rejected; applying
/// the same contracts again is idempotent. The schema version follows
/// [`EndpointContractSnapshot::SCHEMA_VERSION`]. Each extension contains
/// `schema_version` and a `contract` object in the endpoint snapshot format.
pub fn annotate_contracts<P: Copy + 'static>(
    mut document: OpenApi,
    registry: &EndpointContractRegistry<'_, P>,
    permission_to_string: impl Fn(P) -> String,
) -> Result<OpenApi, OpenApiContractError> {
    validate_contracts(&document, registry)?;
    for endpoint in registry.endpoints() {
        let method = endpoint.method().as_str();
        let path = endpoint.path().as_str();
        let contract = serde_json::to_value(endpoint.document(&permission_to_string))?;
        let metadata = serde_json::Value::Object(serde_json::Map::from_iter([
            (
                "schema_version".to_owned(),
                EndpointContractSnapshot::SCHEMA_VERSION.into(),
            ),
            ("contract".to_owned(), contract),
        ]));
        let operation = document
            .paths
            .paths
            .get_mut(path)
            .and_then(|item| operation_mut(item, method))
            .ok_or_else(|| OpenApiContractError::UndocumentedEndpoint {
                method,
                path: path.to_owned(),
            })?;
        let extensions = operation.extensions.get_or_insert_default();
        if extensions
            .get(CONTRACT_EXTENSION)
            .is_some_and(|existing| existing != &metadata)
        {
            return Err(OpenApiContractError::ConflictingMetadata {
                method,
                path: path.to_owned(),
            });
        }
        extensions.insert(CONTRACT_EXTENSION.to_owned(), metadata);
    }
    Ok(document)
}

pub(super) fn validate_supported_path_item(item: &PathItem) -> Result<(), &'static str> {
    if item.ref_path.is_some() || item.query.is_some() || !item.additional_operations.is_empty() {
        return Err("registered paths must inline supported HTTP operations");
    }
    Ok(())
}

pub(super) fn operations(item: &PathItem) -> [(&'static str, Option<&Operation>); 8] {
    [
        ("GET", item.get.as_ref()),
        ("PUT", item.put.as_ref()),
        ("POST", item.post.as_ref()),
        ("DELETE", item.delete.as_ref()),
        ("OPTIONS", item.options.as_ref()),
        ("HEAD", item.head.as_ref()),
        ("PATCH", item.patch.as_ref()),
        ("TRACE", item.trace.as_ref()),
    ]
}

pub(super) fn operations_mut(item: &mut PathItem) -> impl Iterator<Item = &mut Operation> {
    let PathItem {
        get,
        put,
        post,
        delete,
        options,
        head,
        patch,
        trace,
        query,
        additional_operations,
        ..
    } = item;
    [get, put, post, delete, options, head, patch, trace, query]
        .into_iter()
        .filter_map(Option::as_mut)
        .chain(additional_operations.values_mut())
}

fn validate_parameters<P: Copy + 'static>(
    endpoint: &EndpointContract<P>,
    item: &PathItem,
    operation: &Operation,
    components: Option<&Components>,
) -> Result<(), OpenApiContractError> {
    let check = |name: &'static str, location: ParameterIn, required: Option<Required>| {
        let invalid = |reason| OpenApiContractError::InvalidParameter {
            method: endpoint.method().as_str(),
            path: endpoint.path().as_str().to_owned(),
            name,
            reason,
        };
        let matches = |parameter: &Cow<'_, Parameter>| {
            parameter.parameter_in == location
                && if location == ParameterIn::Header {
                    parameter.name.eq_ignore_ascii_case(name)
                } else {
                    parameter.name == name
                }
        };
        let find = |parameters: Option<&Vec<RefOr<Parameter>>>| {
            let parameters = parameters
                .into_iter()
                .flatten()
                .map(|parameter| resolve_parameter(parameter, components).map_err(invalid))
                .collect::<Result<Vec<_>, _>>()?;
            let mut matching = parameters.into_iter().filter(matches);
            let found = matching.next();
            if matching.next().is_some() {
                Err(invalid("is duplicated"))
            } else {
                Ok(found.map(|parameter| parameter.required.clone()))
            }
        };
        let inherited = find(item.parameters.as_ref())?;
        let actual = find(operation.parameters.as_ref())?.or(inherited);
        match (actual, required) {
            (None, None) => Ok(()),
            (Some(_), None) => Err(invalid("is documented for a disabled contract")),
            (None, Some(_)) => Err(invalid("is missing")),
            (Some(actual), Some(required)) if actual == required => Ok(()),
            (Some(_), Some(Required::True)) => Err(invalid("must be required")),
            (Some(_), Some(Required::False)) => Err(invalid("must be optional")),
        }
    };
    let required = match endpoint.idempotency() {
        IdempotencyRequestPolicy::Disabled => None,
        IdempotencyRequestPolicy::HeaderOptional => Some(Required::False),
        IdempotencyRequestPolicy::Required => Some(Required::True),
    };
    check(IDEMPOTENCY_KEY_HEADER_NAME, ParameterIn::Header, required)?;
    let pagination: &[&str] = match endpoint.pagination() {
        EndpointPagination::None => &[],
        EndpointPagination::Cursor => &["page_size", "cursor", "include_total"],
        EndpointPagination::Offset => &["page", "page_size"],
    };
    for &name in pagination {
        check(name, ParameterIn::Query, Some(Required::False))?;
    }
    Ok(())
}

pub(super) fn resolve_parameter<'a>(
    mut parameter: &'a RefOr<Parameter>,
    components: Option<&'a Components>,
) -> Result<Cow<'a, Parameter>, &'static str> {
    let mut description = None;
    // A valid chain cannot visit more components than the document contains.
    for _ in 0..=components.map_or(0, |components| components.parameters.len()) {
        match parameter {
            RefOr::T(parameter) => {
                let mut parameter = Cow::Borrowed(parameter);
                if let Some(description) = description {
                    parameter.to_mut().description = Some(description);
                }
                return Ok(parameter);
            }
            RefOr::Ref(reference) => {
                // The outermost Reference Object takes precedence over both
                // aliases and the target's description when inlining.
                if description.is_none() && !reference.description.is_empty() {
                    description = Some(reference.description.clone());
                }
                let name = parameter_component_name(&reference.ref_location)?;
                parameter = components
                    .and_then(|components| components.parameters.get(&name))
                    .ok_or("references a missing parameter component")?;
            }
        }
    }
    Err("contains a cyclic parameter reference")
}

fn parameter_component_name(reference: &str) -> Result<String, &'static str> {
    let fragment = reference
        .strip_prefix('#')
        .ok_or("must reference a local parameter component")?;
    // RFC 6901 section 6: URI-decode the fragment before interpreting its
    // JSON Pointer tokens. Reject malformed escapes instead of treating them
    // as literal component names.
    for (index, byte) in fragment.bytes().enumerate() {
        if byte == b'%'
            && !fragment
                .as_bytes()
                .get(index + 1..index + 3)
                .is_some_and(|hex| hex.iter().all(u8::is_ascii_hexdigit))
        {
            return Err("contains invalid percent encoding in a parameter reference");
        }
    }
    let pointer = percent_encoding::percent_decode_str(fragment)
        .decode_utf8()
        .map_err(|_| "contains invalid UTF-8 in a parameter reference")?;
    let token = pointer
        .strip_prefix("/components/parameters/")
        .filter(|token| !token.contains('/'))
        .ok_or("must reference a local parameter component")?;
    if !token
        .split('~')
        .skip(1)
        .all(|part| part.starts_with(['0', '1']))
    {
        return Err("contains invalid JSON Pointer escaping in a parameter reference");
    }
    Ok(token.replace("~1", "/").replace("~0", "~"))
}

fn operation_mut<'a>(item: &'a mut PathItem, method: &str) -> Option<&'a mut Operation> {
    match method {
        "GET" => item.get.as_mut(),
        "PUT" => item.put.as_mut(),
        "POST" => item.post.as_mut(),
        "DELETE" => item.delete.as_mut(),
        "OPTIONS" => item.options.as_mut(),
        "HEAD" => item.head.as_mut(),
        "PATCH" => item.patch.as_mut(),
        _ => None,
    }
}