CodeSampleX

サンプル

axum-core 0.5.6: FromRequestParts

検証済みサンプル — cargo axum-core 0.5.6: FromRequestParts. rust 1 · linux alpine/x64 · docker で contract を実行し、成功しました: Method, Uri, Version, and HeaderMap implement…

sha256:06b563adcc226f473ec8ec1818967ca7eb2f6a53b6aa78c85f40e8faf4ed2b62

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux x64 cargo

検証実行環境

環境 コントラクト ステージ 実行日
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-10-19

ケース

HOW
ゴール
verify FromRequestParts in pkg:cargo/axum-core@0.5.6
パッケージ
シンボル
  • FromRequestParts
作成日
2026-10-19T13:58:11Z

コントラクト

  1. Method, Uri, Version, and HeaderMap implement FromRequestParts<S> to extract HTTP metadata without consuming the request body
  2. Custom types implement FromRequestParts<S> via async fn from_request_parts(&mut Parts, &S) returning Result<Self, Self::Rejection>
  3. FromRequestParts<S> implementations can inspect and combine the state reference &S with request parts
  4. Result<T, T::Rejection> implements FromRequestParts<S> infallibly to capture extraction success or rejection without failing extraction

ファイル

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/main.rs

ソースアーティファクトをダウンロード (tar.gz)

ソース

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[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 = "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 = "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.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"

[[package]]
name = "mime"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"

[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"

[[package]]
name = "sample-axum-core-from-request-parts"
version = "0.1.0"
dependencies = [
 "axum-core",
 "http",
]

[[package]]
name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"

[[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"
Cargo.toml
[package]
name = "sample-axum-core-from-request-parts"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
axum-core = "=0.5.6"
http = "1"
PROMPT.md
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 FromRequestParts in pkg:cargo/axum-core@0.5.6
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/axum-core@0.5.6
Demonstrate these symbols/APIs:
  - FromRequestParts

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.
csx.json
{"case":{"caseId":"case:sha256:30fe69d4213e8f88762b14b66e57226cb7d2320bb1e9ea22051a89bed0d99735","contract":["Method, Uri, Version, and HeaderMap implement FromRequestParts\u003cS\u003e to extract HTTP metadata without consuming the request body","Custom types implement FromRequestParts\u003cS\u003e via async fn from_request_parts(\u0026mut Parts, \u0026S) returning Result\u003cSelf, Self::Rejection\u003e","FromRequestParts\u003cS\u003e implementations can inspect and combine the state reference \u0026S with request parts","Result\u003cT, T::Rejection\u003e implements FromRequestParts\u003cS\u003e infallibly to capture extraction success or rejection without failing extraction"],"goal":"verify FromRequestParts in pkg:cargo/axum-core@0.5.6","kind":"HOW","packages":["pkg:cargo/axum-core@0.5.6"],"schemaVersion":1,"symbols":["FromRequestParts"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/axum-core@0.5.6"],"schemaVersion":1,"subject":"pkg:cargo/axum-core@0.5.6","symbols":["FromRequestParts"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify FromRequestParts in pkg:cargo/axum-core@0.5.6",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/axum-core@0.5.6"
  ],
  "symbols": [
    "FromRequestParts"
  ]
}
src/main.rs
use axum_core::extract::FromRequestParts;
use http::{HeaderMap, Method, Request, StatusCode, Uri, Version};
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};

#[derive(Debug, PartialEq, Eq)]
struct ApiKey(String);

impl<S> FromRequestParts<S> for ApiKey
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(
        parts: &mut http::request::Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        match parts
            .headers
            .get("x-api-key")
            .and_then(|v| v.to_str().ok())
        {
            Some(key) if !key.is_empty() => Ok(ApiKey(key.to_owned())),
            _ => Err((StatusCode::UNAUTHORIZED, "missing x-api-key")),
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
struct StatePrefixedKey(String);

impl FromRequestParts<String> for StatePrefixedKey {
    type Rejection = StatusCode;

    async fn from_request_parts(
        parts: &mut http::request::Parts,
        state: &String,
    ) -> Result<Self, Self::Rejection> {
        let key = ApiKey::from_request_parts(parts, state)
            .await
            .map_err(|(status, _)| status)?;
        Ok(StatePrefixedKey(format!("{}:{}", state, key.0)))
    }
}

fn block_on<F: Future>(fut: F) -> F::Output {
    let mut fut = pin!(fut);
    let waker = Waker::noop();
    let mut cx = Context::from_waker(waker);
    loop {
        if let Poll::Ready(val) = fut.as_mut().poll(&mut cx) {
            return val;
        }
    }
}

fn main() {
    let req = Request::builder()
        .method(Method::POST)
        .uri("http://localhost/items?page=2")
        .version(Version::HTTP_11)
        .header("x-api-key", "secret-123")
        .body(())
        .unwrap();
    let (mut parts, _) = req.into_parts();

    // Built-in FromRequestParts implementations on request parts
    let method = block_on(Method::from_request_parts(&mut parts, &())).unwrap();
    assert_eq!(method, Method::POST);

    let uri = block_on(Uri::from_request_parts(&mut parts, &())).unwrap();
    assert_eq!(uri.path(), "/items");
    assert_eq!(uri.query(), Some("page=2"));

    let version = block_on(Version::from_request_parts(&mut parts, &())).unwrap();
    assert_eq!(version, Version::HTTP_11);

    let headers = block_on(HeaderMap::from_request_parts(&mut parts, &())).unwrap();
    assert_eq!(headers.get("x-api-key").unwrap(), "secret-123");

    // Custom FromRequestParts implementation
    let extracted = block_on(ApiKey::from_request_parts(&mut parts, &())).unwrap();
    assert_eq!(extracted, ApiKey("secret-123".to_owned()));

    // State-aware FromRequestParts implementation
    let state = "prod".to_owned();
    let prefixed = block_on(StatePrefixedKey::from_request_parts(&mut parts, &state)).unwrap();
    assert_eq!(prefixed, StatePrefixedKey("prod:secret-123".to_owned()));

    // Rejection on missing header and Result<T, T::Rejection> blanket implementation
    let req_missing = Request::builder()
        .uri("http://localhost/items")
        .body(())
        .unwrap();
    let (mut parts_missing, _) = req_missing.into_parts();

    let err = block_on(ApiKey::from_request_parts(&mut parts_missing, &())).unwrap_err();
    assert_eq!(err, (StatusCode::UNAUTHORIZED, "missing x-api-key"));

    let res_ok: Result<ApiKey, (StatusCode, &'static str)> = block_on(
        <Result<ApiKey, <ApiKey as FromRequestParts<()>>::Rejection> as FromRequestParts<()>>::from_request_parts(
            &mut parts,
            &(),
        ),
    )
    .unwrap();
    assert_eq!(res_ok, Ok(ApiKey("secret-123".to_owned())));

    let res_err: Result<ApiKey, (StatusCode, &'static str)> = block_on(
        <Result<ApiKey, <ApiKey as FromRequestParts<()>>::Rejection> as FromRequestParts<()>>::from_request_parts(
            &mut parts_missing,
            &(),
        ),
    )
    .unwrap();
    assert_eq!(res_err, Err((StatusCode::UNAUTHORIZED, "missing x-api-key")));
}

オリジンシーダー

匿名