Exemplo
axum-macros 0.5.1: FromRequest
Amostra verificada para cargo axum-macros 0.5.1: FromRequest. O contrato rodou em rust 1 · linux alpine/x64 · docker e passou.
sha256:f90ef6d4e8f20da5661a9fd48789abc9c0be95374d01715a8352734b57c0a5e8
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 1
- Chaves de assinatura que o compilaram
- 1
Ambiente declarado
linux x64 cargo
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b… |
2026-11-16 |
Caso
HOW- Objetivo
- verify FromRequest in pkg:cargo/axum-macros@0.5.1
- Pacotes
- Símbolos
-
- FromRequest
- Criado
- 2026-11-16T23:58:23Z
Contrato
- #[derive(axum_macros::FromRequest)] on a struct extracts all leading FromRequestParts fields (including field-level #[from_request(via(State))]) before consuming the request body with the final FromRequest field
- #[from_request(state(AppState))] binds the generated FromRequest implementation to a concrete state type instead of a generic state parameter
- #[from_request(rejection(CustomRejection))] converts field rejections into CustomRejection via From, requiring From<Infallible> when infallible part extractors such as Method are present alongside fallible body extractors
- Container-level #[from_request(via(Wrapper))] on Type delegates whole-request extraction to Wrapper<Type>: FromRequest<S> rather than Wrapper<InnerField>
Arquivos
- Cargo.lock
- Cargo.toml
- PROMPT.md
- csx.json
- spec.json
- src/lib.rs
- test/contract.rs
Código-fonte
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "axum"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
"axum-core",
"bytes",
"futures-util",
"http",
"http-body",
"http-body-util",
"itoa",
"matchit",
"memchr",
"mime",
"percent-encoding",
"pin-project-lite",
"serde_core",
"sync_wrapper",
"tower",
"tower-layer",
"tower-service",
]
[[package]]
name = "axum-core"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"http-body-util",
"mime",
"pin-project-lite",
"sync_wrapper",
"tower-layer",
"tower-service",
]
[[package]]
name = "axum-macros"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "bytes"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
name = "futures-task"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
[[package]]
name = "futures-util"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"slab",
]
[[package]]
name = "http"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
dependencies = [
"bytes",
"itoa",
]
[[package]]
name = "http-body"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
dependencies = [
"bytes",
"http",
]
[[package]]
name = "http-body-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"pin-project-lite",
]
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "matchit"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "mime"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "sample"
version = "0.1.0"
dependencies = [
"axum",
"axum-macros",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
[[package]]
name = "tower"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
dependencies = [
"futures-core",
"futures-util",
"pin-project-lite",
"sync_wrapper",
"tower-layer",
"tower-service",
]
[[package]]
name = "tower-layer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
[[package]]
name = "tower-service"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[package]
name = "sample"
version = "0.1.0"
edition = "2021"
publish = false
[[test]]
name = "contract"
path = "test/contract.rs"
[dependencies]
axum-macros = "=0.5.1"
axum = { version = "=0.8.9", default-features = false }
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: verify FromRequest in pkg:cargo/axum-macros@0.5.1
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:cargo/axum-macros@0.5.1
Demonstrate these symbols/APIs:
- FromRequest
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:29f1ba0982b4eba0086a4f739872683df08caa4f5035a56a054099f90744e039","contract":["#[derive(axum_macros::FromRequest)] on a struct extracts all leading FromRequestParts fields (including field-level #[from_request(via(State))]) before consuming the request body with the final FromRequest field","#[from_request(state(AppState))] binds the generated FromRequest implementation to a concrete state type instead of a generic state parameter","#[from_request(rejection(CustomRejection))] converts field rejections into CustomRejection via From, requiring From\u003cInfallible\u003e when infallible part extractors such as Method are present alongside fallible body extractors","Container-level #[from_request(via(Wrapper))] on Type delegates whole-request extraction to Wrapper\u003cType\u003e: FromRequest\u003cS\u003e rather than Wrapper\u003cInnerField\u003e"],"goal":"verify FromRequest in pkg:cargo/axum-macros@0.5.1","kind":"HOW","packages":["pkg:cargo/axum-macros@0.5.1"],"schemaVersion":1,"symbols":["FromRequest"]},"contractCommand":["cargo","test","--test","contract","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/axum-macros@0.5.1"],"schemaVersion":1,"subject":"pkg:cargo/axum-macros@0.5.1","symbols":["FromRequest"],"verifierAdapter":"cargo@1"}
{
"schemaVersion": 1,
"goal": "verify FromRequest in pkg:cargo/axum-macros@0.5.1",
"kind": "HOW",
"packages": [
"pkg:cargo/axum-macros@0.5.1"
],
"symbols": [
"FromRequest"
]
}
use std::convert::Infallible;
use axum::extract::rejection::StringRejection;
use axum::extract::{FromRequest, Request, State};
use axum::http::{HeaderMap, Method, StatusCode, Uri};
use axum::response::{IntoResponse, Response};
use axum_macros::FromRequest;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AppState {
pub tag: &'static str,
}
#[derive(Debug, PartialEq, Eq)]
pub struct CustomRejection(pub &'static str);
impl From<Infallible> for CustomRejection {
fn from(err: Infallible) -> Self {
match err {}
}
}
impl From<StringRejection> for CustomRejection {
fn from(_: StringRejection) -> Self {
Self("invalid utf-8 body")
}
}
impl IntoResponse for CustomRejection {
fn into_response(self) -> Response {
(StatusCode::UNPROCESSABLE_ENTITY, self.0).into_response()
}
}
#[derive(Debug, FromRequest)]
#[from_request(state(AppState))]
pub struct PayloadExtractor {
#[from_request(via(State))]
pub state: AppState,
pub method: Method,
pub uri: Uri,
pub headers: HeaderMap,
pub body: String,
}
#[derive(Debug, PartialEq, Eq, FromRequest)]
#[from_request(rejection(CustomRejection))]
pub struct CheckedBody {
pub method: Method,
pub body: String,
}
pub struct Trimmed<T>(pub T);
impl<S: Send + Sync, T: From<String>> FromRequest<S> for Trimmed<T> {
type Rejection = StringRejection;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let raw = String::from_request(req, state).await?;
Ok(Trimmed(T::from(raw.trim().to_owned())))
}
}
#[derive(Debug, PartialEq, Eq, FromRequest)]
#[from_request(via(Trimmed))]
pub struct TrimmedNote(pub String);
impl From<String> for TrimmedNote {
fn from(value: String) -> Self {
Self(value)
}
}
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
use axum::body::Body;
use axum::extract::{FromRequest, Request};
use axum::http::{Method, StatusCode};
use axum::response::IntoResponse;
use sample::{AppState, CheckedBody, CustomRejection, PayloadExtractor, TrimmedNote};
fn poll_ready<F: Future>(mut fut: F) -> F::Output {
fn clone(_: *const ()) -> RawWaker {
RawWaker::new(std::ptr::null(), &VTABLE)
}
fn noop(_: *const ()) {}
static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, noop, noop, noop);
let waker = unsafe { Waker::from_raw(RawWaker::new(std::ptr::null(), &VTABLE)) };
let mut cx = Context::from_waker(&waker);
let fut = unsafe { Pin::new_unchecked(&mut fut) };
match fut.poll(&mut cx) {
Poll::Ready(out) => out,
Poll::Pending => panic!("expected in-memory request extraction to complete immediately"),
}
}
#[test]
fn struct_extractor_combines_parts_state_and_final_body() {
let state = AppState { tag: "alpha" };
let req = Request::builder()
.method(Method::POST)
.uri("/items/42")
.header("x-trace", "t-100")
.body(Body::from("payload-data"))
.unwrap();
let extracted = poll_ready(PayloadExtractor::from_request(req, &state))
.expect("valid request must extract");
assert_eq!(extracted.state, AppState { tag: "alpha" });
assert_eq!(extracted.method, Method::POST);
assert_eq!(extracted.uri.path(), "/items/42");
assert_eq!(
extracted.headers.get("x-trace").and_then(|v| v.to_str().ok()),
Some("t-100")
);
assert_eq!(extracted.body, "payload-data");
let bad_req = Request::builder()
.method(Method::POST)
.uri("/items/42")
.body(Body::from(vec![0xff, 0xfe]))
.unwrap();
let err = poll_ready(PayloadExtractor::from_request(bad_req, &state))
.expect_err("invalid utf-8 body must reject");
assert_eq!(err.into_response().status(), StatusCode::BAD_REQUEST);
}
#[test]
fn custom_rejection_maps_field_errors_and_accepts_valid_requests() {
let ok_req = Request::builder()
.method(Method::PUT)
.uri("/check")
.body(Body::from("clean"))
.unwrap();
let ok = poll_ready(CheckedBody::from_request(ok_req, &()))
.expect("valid utf-8 body must extract");
assert_eq!(
ok,
CheckedBody {
method: Method::PUT,
body: "clean".to_owned(),
}
);
let bad_req = Request::builder()
.method(Method::PUT)
.uri("/check")
.body(Body::from(vec![0xc3, 0x28]))
.unwrap();
let err = poll_ready(CheckedBody::from_request(bad_req, &()))
.expect_err("invalid utf-8 body must convert into CustomRejection");
assert_eq!(err, CustomRejection("invalid utf-8 body"));
assert_eq!(err.into_response().status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[test]
fn container_via_delegates_to_wrapper_around_self() {
let req = Request::builder()
.method(Method::POST)
.uri("/notes")
.body(Body::from(" trimmed text \n"))
.unwrap();
let note = poll_ready(<TrimmedNote as FromRequest<()>>::from_request(req, &()))
.expect("via(Trimmed) must extract TrimmedNote");
assert_eq!(note, TrimmedNote("trimmed text".to_owned()));
}
Seeder de origem
anônimo