# Rust These guides give instructions to configure a production Rust project. They show how to control changes and build releases. They show how to record what a release contains. They also give the procedure for security incidents. Compare these procedures with the legal, contractual, and regulatory requirements for your organization. US federal buyers commonly use the [NIST Secure Software Development Framework (SSDF)](https://doi.org/10.6028/NIST.SP.800-218) to examine supplier practices. The [EU Cyber Resilience Act (CRA)](https://eur-lex.europa.eu/eli/reg/2024/2847/oj) specifies requirements for commercial products on the EU market. Use these guides as examples. Do a compliance assessment for the applicable requirements. ## Contents - [Enterprise readiness guide](enterprise-readiness.md) — Project controls, owners, and records for adopters - [Secure development lifecycle](secure-development.md) — Threat models, secure defaults, Rust safety checks, and SSDF - [Project configuration](scaffolding.md) — Cargo metadata, Rust edition, toolchain, and lints - [Code quality checks](code-quality.md) — Format, lint, documentation, and API compatibility checks - [Testing strategy](testing.md) — Test types, test tools, and tests for `unsafe` code - [Supply chain security](supply-chain.md) — Dependency checks with `cargo-deny`, `cargo-vet`, and `cargo-audit` - [Security scanning](security-scanning.md) — Scans for secrets, vulnerabilities, workflow errors, and `unsafe` code - [Minimum supported Rust version](msrv.md) — Version policy, Cargo Resolver v3, and CI checks - [CI/CD pipeline](ci-cd.md) — GitHub Actions jobs, test platforms, and action versions - [Release automation](releases.md) — Release pull requests, Trusted Publishing, and release verification - [Dependency management](dependencies.md) — Dependabot, minimum publication age, and the lockfile - [Local development](local-dev.md) — Tool installation, `justfile`, and contributor instructions - [Security policy](security-policy.md) — Private vulnerability reports, response times, and RustSec advisories - [Project governance](governance.md) — Roles, licenses, repository rules, and the code of conduct ### Application guides - [CLI and TUI applications](cli-tui.md) — Argument parsing, terminal recovery, output streams, and binary distribution - [Desktop GUI applications](desktop-gui.md) — Framework selection, thread safety, security capabilities, accessibility, and code signing - [Web UI (WebAssembly) applications](web-ui-wasm.md) — WASM frameworks, bundle optimization, Content Security Policy, and browser tests - [Web API services](web-api.md) — HTTP frameworks, middleware limits, RFC 9457 errors, SQLx offline builds, and containers - [Embedded applications](embedded.md) — `no_std` HALs, ESP32 and AVR targets, Embassy and RTIC, memory safety, and firmware testing ## Agent skills You can install these guides as [skills.sh](https://skills.sh/) agent skills: ```bash # Install all skills interactively npx skills add kerryhatcher/rusty-dev # Or install specific skills npx skills add kerryhatcher/rusty-dev --skill rust-dev --skill rust-embedded ``` | Skill | Scope | |-------|-------| | [`rust-dev`](skills/rust-dev/SKILL.md) | General production Rust setup, lints, MSRV, testing, supply-chain security, CI/CD, and releases | | [`rust-cli-tui`](skills/rust-cli-tui/SKILL.md) | CLI and TUI applications (`clap`, `ratatui`, `crossterm`, `cargo-dist`) | | [`rust-desktop-gui`](skills/rust-desktop-gui/SKILL.md) | Desktop GUI applications (Tauri v2, Iced, `egui`, Slint, GPUI, AccessKit, code signing) | | [`rust-web-ui-wasm`](skills/rust-web-ui-wasm/SKILL.md) | Web UI / WebAssembly applications (Leptos, Dioxus, Yew, `wasm-bindgen`, CSP) | | [`rust-web-api`](skills/rust-web-api/SKILL.md) | Web API services (`axum`, `tower-http`, `sqlx`, RFC 9457, `cargo-chef` containers) | | [`rust-embedded`](skills/rust-embedded/SKILL.md) | Embedded firmware (`embedded-hal`, `esp-hal`, `avr-hal`, Embassy, RTIC, `probe-rs`, `defmt`) | ## Minimum release requirements Before you give a release to an organization, make sure that the project has these controls. - Publish a policy that identifies the supported versions. - Give a private channel for vulnerability reports. - Enable branch protection for the default branch. - Review the inputs that continuous integration (CI) uses. - Pin GitHub Actions to full commit SHAs. - Commit the lockfile. - Set rules for dependencies, licenses, advisories, and minimum publication age. - If you publish to crates.io, use OIDC Trusted Publishing. Give these files and instructions with the release. - Publish a software bill of materials (SBOM) with the minimum elements that CISA specifies for 2026. - Publish build provenance attestations. - Publish checksums. - Give adopters the commands to check the release files. For a list of the records for each control, refer to the [enterprise readiness guide](enterprise-readiness.md). ## Source documents - [NIST SP 800-218: Secure Software Development Framework (SSDF)](https://doi.org/10.6028/NIST.SP.800-218) - [ANSSI Secure Rust Guidelines](https://anssi-fr.github.io/rust-guide/) - [OpenSSF Best Practices Badge](https://www.bestpractices.dev/), [OpenSSF Scorecard](https://scorecard.dev/), and [OpenSSF OSPS Baseline](https://baseline.openssf.org/) - [SLSA v1.2 specification](https://slsa.dev/spec/v1.2/) - [CISA 2026 Minimum Elements for a Software Bill of Materials (SBOM)](https://www.cisa.gov/sbom) - [CISA Software Acquisition Guide for Government Enterprise Consumers](https://www.cisa.gov/resources-tools/resources/software-acquisition-guide-government-enterprise-consumers) --- # Enterprise Readiness Guide Give adopters records that show how the project controls risks. The records must identify the persons responsible for each control. They must give instructions to examine a release and manage incidents. 1. Publish the maintainer and security roles, `CODEOWNERS`, release approvers, and support policy. 2. Link each release to its immutable source commit and protected CI build. Give the locked dependency versions, SHA-256 checksums, SBOM, Trusted Publishing provenance, and SLSA attestations. 3. Record the supported platforms, minimum supported Rust version (MSRV) policy, secure defaults, privilege limits, resource limits, and upgrade instructions. 4. Give the private channel for vulnerability reports. Give response times and the escalation procedure for regulatory or service-level obligations. Record the GitHub and RustSec disclosure process. Record corrective actions after an incident. Safe Rust prevents many memory-safety defects. Other controls are necessary for `unsafe` code, foreign function interfaces (FFI), and access control. Use controls for integer wraparound, denial of service, CI workflow security, and third-party crates. ## Project maturity stages | Stage | Minimum result | Records for adopters | | --- | --- | --- | | 1. Foundation | License terms, build instructions, and support policy | `README.md`, `LICENSE-MIT`, `LICENSE-APACHE`, `CONTRIBUTING.md`, minimum supported Rust version (MSRV), and platform tiers | | 2. Controlled development | Reviews and deterministic builds | GitHub Rulesets, `CODEOWNERS`, full commit SHAs for CI actions, `zizmor`, `--locked`, and `#[expect]` | | 3. Secure supply chain | Dependency audits and minimum publication age | `Cargo.lock`, Cargo `global-min-publish-age`, Dependabot, `deny.toml`, and `cargo vet --locked` | | 4. Release verification | Release files that adopters can check | `release-plz` pull requests, crates.io OIDC Trusted Publishing, `cargo-auditable`, CISA 2026 SBOM, `SHA256SUMS`, and SLSA v1.2 attestations | | 5. Maintenance | Support and incident response | `SECURITY.md`, `GOVERNANCE.md`, `SUPPORT.md`, scheduled scans, RustSec advisories, and deprecation notices | Complete stages 1 to 3 for a public repository. Before you offer the project for production infrastructure, complete stages 4 and 5. ## What to publish in the repository | File | Owner | Information | | --- | --- | --- | | `README.md` | Maintainers | Purpose, supported operating systems and architectures, MSRV, setup, checks, and safe limits | | `LICENSE-MIT`, `LICENSE-APACHE`, and notices | Governance or legal team | Patent rights, redistribution rights, and third-party notices | | `SECURITY.md` | Security response owner | Private reports, supported versions, initial response times, CRA obligations, and RustSec procedure | | `SUPPORT.md` or `README.md` | Maintainers | Supported releases, maintenance period, community and commercial support, and deprecation policy | | `GOVERNANCE.md` | Project lead | Decision rules, maintainer roles, crates.io team ownership, and emergency access | | `CONTRIBUTING.md`, `AGENTS.md`, and `CODEOWNERS` | Maintainers | Local checks, instructions for contributors and coding agents, license terms, and mandatory reviews | | `CHANGELOG.md` and release notes | `release-plz` | Changes that affect users, MSRV changes, migration steps, and security fixes | | `docs/security/` | Security lead | Threat model, cryptography (such as `rustls` and `zeroize`), `unsafe` code, foreign function interfaces, and deployment controls | Do not publish a personal email address or phone number without consent. Use GitHub private vulnerability reporting, team accounts, and role email addresses. These channels stay available when a maintainer leaves. ## Repository and organization controls Use GitHub Rulesets and Organization Security Configurations to apply the controls. - Make pull requests, status checks, conversation resolution, and linear history mandatory. Make Code Owner review mandatory for sensitive paths. Dismiss previous approvals when new commits change a pull request. Limit updates to `v*` tags to the release GitHub App. - Make phishing-resistant multi-factor authentication mandatory for organization members. Give each team only the necessary permissions. Assign crates.io ownership to a GitHub team (`github:org:team`). Use crates.io OIDC Trusted Publishing. - Set `permissions: contents: read` at the top of the workflow. Use each action's full 40-character commit SHA. Check the workflow with `zizmor`. Enable Secret Scanning Push Protection. Use protected GitHub environments for release credentials and OIDC. ## Release records For each production release, publish and keep these records. 1. **Source and changes.** Give the immutable `vX.Y.Z` tag and the `CHANGELOG.md` entry. Include the API and MSRV check results. 2. **Binaries and checksums.** Build binaries with `cargo auditable build --release --locked`. Include `SHA256SUMS`. 3. **SBOM.** Use CycloneDX (`cargo-cyclonedx`) or SPDX 2.3 (`cargo-sbom`). Use the target and features of the release. Exclude development dependencies. Include component hashes, licenses, and the SBOM tool name. Record the transitive dependencies and how the tool made the SBOM. 4. **Build and source provenance.** Use GitHub Artifact Attestations (`actions/attest-build-provenance@v4`). Link each artifact digest to the repository, commit, and release workflow. Give the instructions for `gh attestation verify`. 5. **CI and audit results.** Include successful test logs for each platform. Include results from `cargo-deny` and `cargo-audit`. Give the records of `cargo-vet` exemptions and their time limits. ## Apply the controls to a project ### 1. Project inventory and owners Make an inventory of crates, binaries, container images, registries, platforms, maintainers, secrets, workflows, and downstream users. Name a release owner. Name a security response owner. Assign crates.io ownership to a GitHub team. ### 2. License, support, and governance Add `LICENSE-MIT` and `LICENSE-APACHE`. Add `SECURITY.md`. Enable GitHub private vulnerability reporting. Add `CONTRIBUTING.md`, `AGENTS.md`, and `CODEOWNERS`. Publish the support and MSRV policies. ### 3. Repository controls Enable branch rulesets and `v*` tag rulesets. Enable immutable releases. Enable Secret Scanning Push Protection. Set only the necessary workflow permissions. Make full commit SHAs mandatory for actions. Check workflows with `zizmor`. Configure Dependabot `groups:` and `cooldown:`. ### 4. Build controls Set `edition = "2024"`. Select a rolling MSRV policy. Commit `Cargo.lock`. Set Cargo's `global-min-publish-age`. Configure `[lints]` and use `#[expect(..., reason = "...")]` for exceptions. Use `--locked` in CI and `just ci` recipes where applicable. ### 5. Dependency and release checks Enable `cargo-audit` and `cargo-deny`. Configure `cargo-vet` with peer audits and exemptions with time limits. Use `cargo vet --locked` in CI. Configure releases with `release-plz` and crates.io OIDC Trusted Publishing. Use `cargo-auditable` for binaries. Generate a CISA 2026 SBOM. Add build attestations with `actions/attest-build-provenance@v4`. ### 6. Tests and incident response Select tests that apply to the threat model. Tools include `proptest`, `cargo-fuzz`, `cargo-mutants`, Miri, and Kani. Do an exercise for private disclosure and RustSec submission. Review `cargo-vet` and `deny.toml` expiration dates each quarter. Add a regression check after each incident. ## Procurement and regulatory references Keep records that link the repository controls to the applicable frameworks. - **US federal procurement.** Refer to NIST SP 800-218 (SSDF v1.1), SP 800-218A, and the SP 800-218 Rev. 1 draft (SSDF v1.2). Use the final v1.1 as the reference until NIST publishes the final v1.2. OMB Memorandum M-26-05 replaced the general attestation requirement in M-22-18 and M-23-16. The policy now uses risk to determine the applicable requirements. An agency can make CISA attestations and SBOMs mandatory in a contract. Refer to CISA's July 2026 Minimum Elements for SBOMs. Get legal or compliance review before you sign an attestation. - **European Union.** Article 14 of the Cyber Resilience Act (CRA) sets 24-hour and 72-hour reporting deadlines for actively exploited vulnerabilities. These obligations started on September 11, 2026. Refer to the CRA for CE marking, software lifecycle, and SBOM obligations. Refer to the CRA also for Open-Source Software Steward obligations. These obligations apply from December 11, 2027. Use SBOMs, `cargo-auditable`, and coordinated disclosure to help examine the effects in 24 hours or less. - **Public project records.** The [OpenSSF Best Practices Badge](https://www.bestpractices.dev/), [OpenSSF Scorecard](https://scorecard.dev/), and [OpenSSF OSPS Baseline](https://baseline.openssf.org/) give adopters information about project controls. ## Source documents - [NIST SP 800-218: Secure Software Development Framework (SSDF)](https://doi.org/10.6028/NIST.SP.800-218) & [SP 800-218 Rev. 1 (SSDF v1.2 draft)](https://csrc.nist.gov/pubs/sp/800/218/r1/ipd) - [CISA 2026 Minimum Elements for a Software Bill of Materials (SBOM)](https://www.cisa.gov/sbom) - [CISA Software Acquisition Guide for Government Enterprise Consumers](https://www.cisa.gov/resources-tools/resources/software-acquisition-guide-government-enterprise-consumers) - [EU Cyber Resilience Act (Regulation (EU) 2024/2847)](https://eur-lex.europa.eu/eli/reg/2024/2847/oj) - [SLSA v1.2 specification](https://slsa.dev/spec/v1.2/) - [OpenSSF Best Practices Badge](https://www.bestpractices.dev/), [OpenSSF Scorecard](https://scorecard.dev/), & [OpenSSF OSPS Baseline](https://baseline.openssf.org/) - [GitHub Rulesets](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/about-rulesets) --- # Secure Development Lifecycle Use security controls from design through release and maintenance. Keep design decisions, test results, and release records. This guide uses the **NIST SSDF (SP 800-218)** and the **ANSSI Secure Rust Guidelines** for Edition 2024 Rust projects. ## Secure design for Rust - Before you write code, make a threat model. Identify assets, trust boundaries, attacker capabilities, and entry points for untrusted input. Identify privilege changes, dependencies, and resource exhaustion risks. Update the threat model when the architecture, protocols, or deployment boundaries change. - Make network listeners, destructive file operations, telemetry, weak algorithms, and elevated privileges opt-in. Fail closed if authentication, authorization, or validation fails. - Limit operating system privileges, public APIs, enabled features, dependencies, and data retention. For filesystem isolation, use a capability API such as [`cap-std`](https://docs.rs/cap-std) when possible. Its `Dir` handles use facilities such as `openat2` or `O_RESOLVE_BENEATH`. A capability API can prevent path traversal and races during symlink resolution without manual checks of path strings. - Set limits before you parse external input. Limit payload size, allocation, recursion depth, decompression ratio, timeouts, and concurrency. Do not use `unwrap`, `expect`, or unchecked slice indexing on untrusted input. - Check integer arithmetic. By default, `+`, `-`, and `*` panic on overflow in debug builds. In release builds, the value wraps. Use `.checked_*()`, `.saturating_*()`, or `TryFrom` for security-sensitive sizes, offsets, and quotas. If a panic or abort is safer than wraparound, set `overflow-checks = true` in `[profile.release]`. - Set `unsafe_code = "forbid"` in `[lints.rust]` when the crate uses only safe Rust. If `unsafe` is necessary in a reviewed module, set `unsafe_code = "deny"` in `[lints.rust]`. Use `#[allow(unsafe_code)]` only on that module. Give the module a small safe interface. Keep the Edition 2024 checks for `unsafe_op_in_unsafe_fn`, `unsafe extern`, and `#[unsafe(...)]` active. Set `clippy::undocumented_unsafe_blocks = "deny"`. - Use reviewed cryptographic libraries. Do not write new cryptographic primitives or TLS implementations. If possible, use a memory-safe TLS library such as [`rustls`](https://docs.rs/rustls) with `aws-lc-rs` or `ring`. Clear key material on drop with [`zeroize`](https://docs.rs/zeroize) or [`secrecy`](https://docs.rs/secrecy). Compare digests and tokens in constant time with [`subtle`](https://docs.rs/subtle). - Apply the same controls to code from coding agents and persons. Use human peer review, threat model checks, license and provenance checks, and CI security checks. Refer to NIST SP 800-218A. ## Development and release checks | When | Actions | Records | | --- | --- | --- | | Design or major change | Make a threat model. Review trust boundaries and resource limits. | Architecture decision record, issue, or `docs/security/threat-model.md` | | Each change | Get an independent review. Check the format, Clippy lints, tests, and locked dependencies. | Pull request, CI results, and review record | | Change to a trust boundary | Add negative tests and `proptest` checks. Add `cargo-fuzz` targets for parsers and decoders. | Tests, fuzz corpus, and scheduled fuzz tests | | `unsafe` or FFI change | Get Code Owner review. Document the invariant in a `// SAFETY:` comment. Use Miri, sanitizers, or Kani. | Review approval and job log | | Dependency or workflow change | Examine licenses, sources, advisories, and minimum publication age. Update the audit records. Check workflows with `zizmor`. | Pull request, `deny.toml`, and `supply-chain/` | | Release | Build with `cargo-auditable` and `--locked`. Publish with OIDC. Add an SBOM, SHA-256 checksums, and SLSA provenance. | Protected release workflow and release files | | Incident or defect | Assess the defect. Correct the cause. Coordinate disclosure with GitHub and RustSec. | Advisory and regression test | ## Tests for security properties Select the test method for the type of failure. - Use `proptest` to check invariants with random inputs. Make sure that parsers do not panic and that serialization preserves data. Check for quota overflow and make sure that access checks fail closed. - Use coverage-guided fuzzing for binary formats, network frames, archive extractors, and foreign function interfaces. Use `cargo-fuzz` with `libFuzzer`. Schedule the tests in CI or use OSS-Fuzz. Keep the initial test inputs in Git. - Use `cargo-mutants` to check that the suite finds missing authorization checks, boundary checks, and error branches. - Use `cargo +nightly miri test` to find aliasing and pointer provenance defects in `unsafe` Rust. Use LLVM sanitizers (`ASAN`, `TSAN`, and `UBSAN`) at C interfaces. Use [Kani](https://model-checking.github.io/kani/) to check for panics and undefined behavior in critical state machines that the model covers. ## Rust-specific policy decisions Record the values and conditions for these policies in the repository documentation. | Topic | Policy | | --- | --- | | `unsafe` | Locations that can use `unsafe`, Code Owner review, `// SAFETY:` comments, and Miri checks | | Foreign function interface (FFI) | Tier 1 targets, pure-Rust alternatives (such as `rustls` and `miniz_oxide`), C compiler flags, ABI checks, and CVE ownership | | Arithmetic and panics | Overflow checks, for example `checked_*` or `[profile.release] overflow-checks`. Rules for untrusted input and the choice of panic abort or unwind. | | Features | Necessary default features, security effects of optional features, and feature combinations for CI | | Network and files | Timeouts, payload limits, TLS 1.2 and 1.3 policy (`rustls`), directory access with `cap-std`, and removal of secrets from logs | | Dependencies | Permitted registries, minimum publication age, rolling MSRV, and `cargo vet` exemption expiration dates | ## SSDF crosswalk The NIST SSDF has four groups. The table shows controls for each group. | SSDF group | Controls for a Rust project | | --- | --- | | **Prepare the Organization (PO)** | Roles and procedures in `GOVERNANCE.md`, `SECURITY.md`, `AGENTS.md`, and `CODEOWNERS`. Threat model, lints, MSRV, and `unsafe` policy. | | **Protect the Software (PS)** | Rulesets, multi-factor authentication, Push Protection, full commit SHAs for actions, `zizmor`, read-only tokens, and crates.io OIDC Trusted Publishing | | **Produce Well-Secured Software (PW)** | Safe defaults, Edition 2024, Clippy, `proptest`, `cargo-fuzz`, Miri, and Kani. Dependency audits, minimum publication age, `cargo-auditable`, an SBOM, and SLSA provenance. | | **Respond to Vulnerabilities (RV)** | Private reports, CRA and service-level deadlines, scheduled scans, `cargo audit bin`, RustSec disclosure, and regression tests | ## Source documents - [NIST SP 800-218: Secure Software Development Framework (SSDF v1.1)](https://doi.org/10.6028/NIST.SP.800-218), [SP 800-218 Rev. 1 (SSDF v1.2 draft)](https://csrc.nist.gov/pubs/sp/800/218/r1/ipd), & [SP 800-218A](https://doi.org/10.6028/NIST.SP.800-218A) - [ANSSI Secure Rust Guidelines](https://anssi-fr.github.io/rust-guide/) - [CISA Secure by Design](https://www.cisa.gov/securebydesign) - [Rust Fuzz Book](https://rust-fuzz.github.io/book/) - [Kani Rust Verifier](https://model-checking.github.io/kani/) - [The Rustonomicon: Unsafe Rust](https://doc.rust-lang.org/nomicon/) --- # Project Configuration `Cargo.toml` records the crate metadata, Rust edition, lints, and requirements for dependencies. Set these values when you create the crate. ## The `Cargo.toml` template ```toml [package] name = "my-crate" version = "0.1.0" edition = "2024" rust-version = "1.96" description = "A short, clear description of what this crate does" license = "MIT OR Apache-2.0" repository = "https://github.com/you/my-crate" readme = "README.md" keywords = ["cli", "tool", "productivity"] categories = ["command-line-utilities"] exclude = ["docs/", "assets/", ".github/", "justfile"] ``` ### Key fields | Field | Purpose | |-------|---------| | `edition` | Set the value to `"2024"`. Rust 1.85 added support for this edition. It enables the 2024 format defaults, `unsafe_op_in_unsafe_fn` warnings, `unsafe extern` blocks, and `#[unsafe(...)]` attributes. Cargo selects Resolver v3 by default if the root package uses Edition 2024. In a virtual workspace, set `resolver = "3"` in `[workspace]`. Refer to the [MSRV guide](msrv.md#how-cargo-resolver-v3-uses-the-msrv). | | `rust-version` | Set the minimum supported Rust version (MSRV). For example, set `"1.96"` for an N-4 policy when stable is `1.100`. Cargo Resolver v3 and CI use this value. Refer to the [MSRV guide](msrv.md). | | `license` | Set the value to `"MIT OR Apache-2.0"`. For `cargo publish`, a license and a description are necessary. Refer to [Licensing](#licensing). | | `repository` | Set the URL of the source repository. `cargo publish` gives a warning when `repository`, `homepage`, and `documentation` are all absent. Crates.io uses the URL for provenance links. | | `keywords` and `categories` | Specify applicable values to help users find the crate on crates.io. Each field can contain up to five values. | | `exclude` | Specify the files that Cargo must omit from the `.crate` archive. Use `cargo package --list` to examine the file list. | ## Toolchain pinning (`rust-toolchain.toml`) `rust-version` identifies the earliest toolchain that the crate supports. Use `rust-toolchain.toml` to set the versions of `rustc`, `rustfmt`, and Clippy for developers and continuous integration (CI). ```toml # rust-toolchain.toml [toolchain] channel = "1.100.0" components = ["rustfmt", "clippy"] ``` Update `channel` when you select a new Rust release. Dependabot does not update `rust-toolchain.toml`. Renovate can update this file. In the CI job for the MSRV, set `RUSTUP_TOOLCHAIN` to the MSRV. This value has priority over `rust-toolchain.toml`. Refer to [Enforcing MSRV in CI](msrv.md#enforcing-msrv-in-ci). To use the latest stable version automatically, set `channel = "stable"`. You can also omit `rust-toolchain.toml` if the default toolchain is stable. ## Lints Configure the `rustc` and Clippy lints in `Cargo.toml`. ```toml [lints.rust] unsafe_code = "forbid" unused_crate_dependencies = "warn" [lints.clippy] all = { level = "warn", priority = -1 } pedantic = { level = "warn", priority = -1 } allow_attributes = "warn" allow_attributes_without_reason = "warn" dbg_macro = "warn" todo = "warn" undocumented_unsafe_blocks = "warn" ``` If the workspace has more than one crate, define `[workspace.lints.rust]` in the root `Cargo.toml`. Define `[workspace.lints.clippy]` in the same file. Set `workspace = true` in the `[lints]` section of each member crate. ```toml [lints] workspace = true ``` ### Lint groups and priorities - Set `priority = -1` for the `all` and `pedantic` groups. Individual lints at the default priority of `0` can then override the group settings. - Do not make the Clippy `nursery` group mandatory in CI. Its experimental lints can give false positives or change in a stable Rust release. - Select individual `restriction` lints for your policy. Examples include `dbg_macro`, `todo`, and `undocumented_unsafe_blocks`. - Set `unused_crate_dependencies = "warn"` to identify dependencies that your code does not import. Cargo 1.100 also gives diagnostics for unused dependencies. Use `-D warnings` in CI. With this flag, a Clippy warning causes the check to fail. ```bash cargo clippy --all-targets --all-features --locked -- -D warnings ``` ### Lint exceptions with `#[expect]` If a lint does not apply to an item, add a `#[expect]` attribute. Set its `reason` value. Rust 1.81 or later supports the attribute. The Clippy lints `allow_attributes` and `allow_attributes_without_reason` enforce this policy. ```rust #[expect( clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "clamp(0.0, 100.0) guarantees the value fits in u8 with no truncation or sign loss" )] let pct = used.clamp(0.0, 100.0) as u8; ``` `#[expect]` causes an `unfulfilled_lint_expectations` warning if the original lint no longer applies. Remove the exception when you get this warning. `#[allow]` stays in the code without a warning when the original lint no longer applies. ## Restrict `unsafe` code Set `unsafe_code = "forbid"` in `[lints.rust]`. As an alternative, add `#![forbid(unsafe_code)]` at the crate root. The compiler rejects `unsafe` blocks. It also rejects these blocks in macro expansions. Some foreign function interfaces (FFIs) or low-level primitives make `unsafe` necessary. If `unsafe` is necessary in a reviewed module, set `unsafe_code = "deny"` in `[lints.rust]`. Use `#[allow(unsafe_code)]` only on that module. The compiler rejects this exception when the lint level is `"forbid"`. Keep the Edition 2024 warning `unsafe_op_in_unsafe_fn` active. Set `clippy::undocumented_unsafe_blocks = "deny"` to make a `// SAFETY:` comment mandatory for each `unsafe` block. ## Dependency declarations Declare the dependencies in `Cargo.toml`. ```toml [dependencies] # This range permits 1.x updates. It excludes 2.0. # Cargo Resolver v3 gives priority to versions that support package.rust-version. serde = { version = "1", features = ["derive"] } # Disable default features if only some of the features are necessary. toml = { version = "0.8", default-features = false, features = ["parse"] } # The rust_backend feature uses miniz_oxide in place of libz-sys. # It removes the need for a C toolchain and an unsafe FFI call to libz-sys. flate2 = { version = "1", default-features = false, features = ["rust_backend"] } ``` ### Dependency rules 1. Use standard Semantic Versioning ranges, for example `"1"` and `"0.8"`. 2. Do not set a maximum minor version with a constraint such as ` # Code Quality Checks Do the code quality checks before you merge changes into `main`. Use the `just` recipes locally. Continuous integration (CI) does the same checks and uses `--locked` where applicable. ## Formatting: `rustfmt` ```bash # Do the CI format check. The command does not change files. cargo fmt --check # Format the local files. cargo fmt ``` With `edition = "2024"` in `Cargo.toml`, `rustfmt` uses the 2024 format rules. If you must keep the previous format during an edition change, set `style_edition` in `rustfmt.toml`. Use the same version of `rustfmt` locally and in CI. Specify the version in [`rust-toolchain.toml`](scaffolding.md#toolchain-pinning-rust-toolchaintoml). CI uses `cargo fmt --check`. The check fails if a file has an incorrect format. Before you push a change, use `just fmt-fix` or configure your editor to format on save. ## Linting: `clippy` and `rustc` ```bash # Start Clippy for all targets and features. cargo clippy --all-targets --all-features --locked -- -D warnings ``` With `-D warnings`, a warning causes the lint check to fail. The `[lints]` section in `Cargo.toml` sets the lint policy. ```toml [lints.rust] unsafe_code = "forbid" unused_crate_dependencies = "warn" [lints.clippy] all = { level = "warn", priority = -1 } pedantic = { level = "warn", priority = -1 } allow_attributes = "warn" allow_attributes_without_reason = "warn" dbg_macro = "warn" todo = "warn" undocumented_unsafe_blocks = "warn" ``` ### Lint groups and priorities - `[lints.rust]` sets compiler lints. Examples include `unsafe_code = "forbid"` and `unused_crate_dependencies = "warn"`. - `clippy::all` and `clippy::pedantic` check for defects, performance issues, and Rust style. Set their priority to `-1`. An individual lint at priority `0` can then override these settings. - Select individual `restriction` lints for the project. Examples include `allow_attributes`, `allow_attributes_without_reason`, `dbg_macro`, `todo`, and `undocumented_unsafe_blocks`. - Do not make experimental `nursery` lints mandatory in CI. They can give false positives after a Rust update. ### Lint exceptions with `#[expect]` Do not use `#[allow(...)]` without a `reason` value. If a lint does not apply to an item, add `#[expect(..., reason = "...")]` to that item. Rust 1.81 or later supports this attribute. ```rust #[expect( clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "clamp(0.0, 100.0) guarantees the value fits in u8 without truncation or sign loss" )] let pct = used.clamp(0.0, 100.0) as u8; ``` The compiler and Clippy give these diagnostics. - `clippy::allow_attributes_without_reason` reports an attribute without a `reason` value. - If the original lint no longer applies, `rustc` gives an `unfulfilled_lint_expectations` warning. Remove the exception when this occurs. ## Documentation and API compatibility checks ### Documentation checks with `rustdoc` ```bash RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked ``` This command treats rustdoc warnings as errors. Examples include warnings for broken links and incorrect HTML in doc comments. The CI check occurs before docs.rs builds the release. ### API compatibility: `cargo-semver-checks` For a published library, use [`cargo-semver-checks`](https://github.com/obi1kenobi/cargo-semver-checks). The command compares the current `rustdoc` JSON with the latest crates.io release. It can identify changes such as removal of a public item or stricter trait bounds. It can also identify removal of an auto trait such as `Send` or `Sync`. ```bash # Use the latest crates.io release as the default baseline. cargo semver-checks # Use the merge base with main to check only the changes from this branch. # A comparison with origin/main can report new items on main as removed. # If the pull request title has the ! marker, use major in place of minor. git fetch origin main cargo semver-checks --baseline-rev "$(git merge-base HEAD origin/main)" --release-type minor ``` `cargo-semver-checks` rejects the `--locked` flag. The CI [`semver` job](ci-cd.md#semver--public-api-compatibility-libraries) compares each pull request with its base commit. The job permits intentional incompatible changes only if the pull request title contains the Conventional Commits `!` marker. ## The `justfile` Use the `justfile` to give developers and CI the same commands. The comments give the purpose of each recipe. ```makefile # Show the recipes by default. default: @just --list # Do the format check without changes to files. fmt: cargo fmt --check # Format the files. fmt-fix: cargo fmt # Lint all targets and features. Treat warnings as errors. lint: cargo clippy --all-targets --all-features --locked -- -D warnings # Build the API documentation. Include the check for broken links. doc: RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked # Start the tests. If the crate has no src/lib.rs, omit cargo test --doc. test: cargo nextest run --locked cargo test --doc --locked # Start all checks. The command stops if a recipe fails. ci: fmt lint doc test audit msrv deny trivy zizmor vet geiger ``` ## Check reference | Recipe | Command | Purpose | |------|---------|------------------| | `just fmt` | `cargo fmt --check` | Consistent 2024-edition formatting | | `just lint` | `cargo clippy --all-targets --all-features --locked -- -D warnings` | Correctness, style, documented `#[expect]` reasons | | `just doc` | `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` | Valid API docs and intra-doc links | | `just test` | `cargo nextest run --locked && cargo test --doc --locked` | Functional correctness and executable doc examples | | `just audit` | `cargo audit` | Known RustSec advisories in `Cargo.lock` | | `just msrv` | `cargo msrv verify` | Compatibility with declared `rust-version` | | `just deny` | `cargo deny check` | Licenses, banned crates, duplicates, sources | | `just trivy` | `trivy fs --scanners vuln,secret --exit-code 1 --skip-dirs target .` | Filesystem vulnerabilities and leaked secrets | | `just zizmor` | `zizmor .github/workflows` | GitHub Actions workflow security flaws | | `just vet` | `cargo vet --locked` | Supply-chain audit and exemption policy | | `just geiger` | `-cargo geiger` | Unsafe usage metrics (informational) | ## Tool installation Use [`cargo-binstall`](https://github.com/cargo-bins/cargo-binstall) to install prebuilt tools. To compile the tools from source, use `cargo install --locked`. ```bash # Install cargo-binstall before you install prebuilt tools. cargo install cargo-binstall --locked cargo binstall -y just cargo-nextest cargo-semver-checks cargo-audit cargo-msrv cargo-deny cargo-vet zizmor cargo-geiger # To compile from source, use the lockfile from each tool's package. cargo install --locked just cargo-nextest cargo-semver-checks cargo-audit cargo-msrv cargo-deny cargo-vet zizmor cargo-geiger # trivy: https://trivy.dev/latest/getting-started/installation/ ``` ## Further reading - [rustfmt documentation](https://github.com/rust-lang/rustfmt) - [Clippy documentation](https://doc.rust-lang.org/clippy/) - [Rustc lint expectations (`#[expect]`)](https://doc.rust-lang.org/rustc/lints/levels.html#expecting-a-lint) - [cargo-semver-checks](https://github.com/obi1kenobi/cargo-semver-checks) - [just documentation](https://just.systems/man/en/) --- # Testing Strategy Use different types of tests to find regressions, panics, and changes in behavior before a release. Line coverage shows which code the tests execute. ## Test commands For each test binary, `cargo test` uses one process for all tests. Changes to global state or environment variables can affect other tests in that process. Use [`cargo-nextest`](https://nexte.st/) for the main test suite. If the crate has a library target, use `cargo test --doc` for doctests. ```bash cargo nextest run --locked # If the package has a library target (src/lib.rs), start the doctests. # If the package has only a binary target, omit this command. cargo test --doc --locked ``` ### Why `cargo-nextest`? - `cargo-nextest` uses one operating system process for each test. A panic, abort, working directory change, or thread leak stays in that process. - `cargo-nextest` can complete tests up to three times faster on multi-core runners. It also gives slow-test warnings, detects leaks, and writes JUnit XML. - `cargo test --doc --locked` compiles and executes the applicable examples in the API documentation of a library target. ## Unit tests Put unit tests in a `mod tests` block next to the code. ```rust // src/config.rs #[cfg(test)] mod tests { use super::*; #[test] fn name_defaults_when_missing() { let cfg: Config = serde_json::from_str("{}").unwrap(); assert_eq!(cfg.display_name(), "default"); } #[test] fn name_uses_configured_value_when_present() { let cfg: Config = serde_json::from_str(r#"{"name":"alpha"}"#).unwrap(); assert_eq!(cfg.display_name(), "alpha"); } } ``` ### Rules for unit tests 1. Write assertions for inputs and outputs. A test in `mod tests` can call private functions in the parent module. 2. If possible, use one test for each behavior. For example, `name_defaults_when_missing` checks the default for a missing name. 3. Add tests for empty strings, zero, limit values, incorrect UTF-8, incorrect types, and missing fields. 4. Add a test for each fallback branch. 5. If an assertion compares exact floating-point values, add `#[expect(clippy::float_cmp, reason = "...")]`. In `reason`, record why the test uses exact equality. ## Integration and CLI tests Put integration tests in `tests/`. These tests use the public API or start the compiled binary. ```rust // tests/cli.rs use std::io::Write; use std::process::{Command, Stdio}; #[test] fn valid_input_prints_configured_name() { let mut cmd = Command::new(env!("CARGO_BIN_EXE_my-crate")); cmd.env_clear() .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); let mut child = cmd.spawn().expect("failed to spawn binary"); child .stdin .take() .expect("child stdin handle") .write_all(br#"{"name":"alpha"}"#) .expect("failed to write to child stdin"); let output = child.wait_with_output().expect("failed to wait on child"); assert!(output.status.success()); assert_eq!(String::from_utf8_lossy(&output.stdout), "alpha\n"); } ``` ### Integration test methods - Use `env!("CARGO_BIN_EXE_")`, [`assert_cmd`](https://docs.rs/assert_cmd), or [`snapbox`](https://docs.rs/snapbox) to start the test binary that Cargo compiled. - Use [`insta`](https://insta.rs/) to save snapshots for large JSON, diagnostic messages, or CLI output. Review snapshots with `cargo insta review`. - Set the environment on the child `Command`. Use `.env()`, `.env_remove()`, or `.env_clear()` for `HOME`, `XDG_CONFIG_HOME`, `APPDATA`, and application variables. - Do not call `std::env::set_var` or `std::env::remove_var` in multithreaded tests. In Edition 2024, these functions are `unsafe`. Changes to process-wide environment variables can cause a race condition. - Use `tempfile::tempdir()` in filesystem tests. It removes a temporary directory when its handle goes out of scope. ## Property-based testing Use [`proptest`](https://docs.rs/proptest) for parsers, state machines, and calculations at limits. It generates many inputs and reduces a failure to a small example. For example, `any::()` can generate `NaN` and `±Infinity`. ```rust use proptest::prelude::*; proptest! { #[test] fn percent_stays_within_0_to_100(used in any::(), total in any::()) { let pct = compute_percent(used, total); prop_assert!((0..=100).contains(&pct)); } } ``` ## Mutation testing, coverage, and `unsafe` verification - [`cargo-mutants`](https://mutants.rs/) changes the code and checks if the test suite detects the change. For example, it can change `<` to `<=`, remove a branch, or make a function return early. Use it at intervals or for a change with `cargo mutants --in-diff git.diff`. This can identify defects in a test suite with high line coverage. - [`cargo-llvm-cov`](https://github.com/taiki-e/cargo-llvm-cov) measures code coverage. Use `cargo llvm-cov nextest` to find error paths and edge cases that the tests do not execute. - If the crate contains `unsafe` blocks, use `cargo +nightly miri test` in CI. Miri can identify aliasing violations, uninitialized reads, and incorrect pointer provenance. For critical invariants, you can use bounded model checking with [Kani](https://model-checking.github.io/kani/). ## Regression tests 1. Write a regression test that detects the defect. 2. Make sure that the test fails before the code correction. 3. Correct the code. 4. Make sure that the test gives a satisfactory result. Include the test and the code change in the same pull request. ### Never panic on untrusted input A panic on malformed external input can cause a denial of service. `unwrap`, `expect`, and a slice index outside its limits can cause panics. Add tests for hostile, truncated, empty, and incorrectly typed inputs. Make sure that each test gives the expected exit code. Make sure that the output contains no Rust panic backtrace. ```rust #[test] fn invalid_json_returns_usage_error_without_panicking() { let out = run_with_stdin("not json"); assert_eq!(out.status.code(), Some(2)); let stderr = String::from_utf8_lossy(&out.stderr); assert!(stderr.contains("invalid configuration")); assert!(!stderr.contains("panicked at")); } ``` ### Configuration priority Use this order of priority for configuration. 1. Command-line flags 2. Environment variables 3. Configuration file 4. Default values Add a test for each pair of sources to make sure that the higher-priority source takes effect. ## Further reading - [The Rust Book: Writing Automated Tests](https://doc.rust-lang.org/book/ch11-00-testing.html) - [cargo-nextest documentation](https://nexte.st/) - [proptest book](https://proptest-rs.github.io/proptest/) - [cargo-mutants documentation](https://mutants.rs/) - [Miri: Undefined Behavior detector for Rust](https://github.com/rust-lang/miri) --- # Supply Chain Security A direct or transitive crate can add a vulnerability or a malicious build script. It can also add a dependency with no maintainer or copyleft license obligations. Use `cargo-deny`, `cargo-vet`, and `cargo-audit` to check dependencies. Set a minimum publication age to give reviewers time to identify a malicious release. Commit `deny.toml`, `supply-chain/`, and `Cargo.lock`. Use `--locked` in CI and release builds. This makes the builds use the dependency versions from the review. ## `cargo-deny`: advisories, licenses, bans, and sources [`cargo-deny`](https://embarkstudios.github.io/cargo-deny/) uses `deny.toml` to check dependency versions, advisories, licenses, and sources. This example uses `cargo-deny` 0.20 or later. ```toml # deny.toml [graph] targets = [ "x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", "aarch64-apple-darwin", "x86_64-pc-windows-msvc", ] all-features = true [output] feature-depth = 1 # This check identifies vulnerabilities, unsound crates, and crates with no maintainer. [advisories] unmaintained = "workspace" unsound = "all" yanked = "deny" # Set an expiration date for each advisory exception. ignore-expiry = "90d" ignore = [ # { id = "RUSTSEC-YYYY-NNNN", reason = "Not reachable; upstream fix tracked in #123", expiry = "60d" } ] # This list identifies the permitted SPDX licenses. [licenses] confidence-threshold = 0.93 allow = [ "MIT", "Apache-2.0", "Apache-2.0 WITH LLVM-exception", "Unicode-3.0", "BSD-3-Clause", ] [licenses.private] ignore = false # This check identifies duplicate versions, wildcards, C wrappers, and crates that overlap std. [bans] multiple-versions = "warn" wildcards = "deny" allow-wildcard-paths = true # Permit private path dependencies in this workspace only. highlight = "all" deny = [ { crate = "openssl-sys", use-instead = "rustls" }, ] # Identify crates that std or core replaces, for example lazy_static and once_cell. [bans.std-replacements] scope = "workspace" # Permit packages from crates.io only. [sources] unknown-registry = "deny" unknown-git = "deny" allow-registry = ["https://github.com/rust-lang/crates.io-index"] [sources.allow-org] github = [] gitlab = [] bitbucket = [] ``` ### Dependency checks | Section | Command | Conditions that the check identifies | |---------|---------|--------------------------------------| | `[advisories]` | `cargo deny check advisories` | RustSec CVEs, unsound crates, yanked versions, crates with no maintainer, and expired exceptions | | `[licenses]` | `cargo deny check licenses` | SPDX licenses outside the permitted list, such as copyleft licenses | | `[bans]` | `cargo deny check bans` | Wildcard dependencies, duplicate versions, prohibited C wrappers (such as `openssl-sys`), and crates that `std` replaces | | `[sources]` | `cargo deny check sources` | Git repositories or registries that the policy does not permit | ## `cargo-vet` audits [`cargo-vet`](https://mozilla.github.io/cargo-vet/) checks that each third-party crate in `Cargo.lock` has an audit or an exemption. Your team can do its own audit or import an audit from another organization. An exemption applies to a specific version. ```toml # supply-chain/config.toml [cargo-vet] version = "0.10" # Import audit records from Google, Mozilla, ISRG, and Bytecode Alliance. [imports.google] url = "https://raw.githubusercontent.com/google/rust-crate-audits/main/audits.toml" [imports.mozilla] url = "https://raw.githubusercontent.com/mozilla/supply-chain/main/audits.toml" [imports.isrg] url = "https://raw.githubusercontent.com/divviup/libprio-rs/main/supply-chain/audits.toml" [imports.bytecode-alliance] url = "https://raw.githubusercontent.com/bytecodealliance/wasmtime/main/supply-chain/audits.toml" [policy.my-crate] audit-as-crates-io = false # Exemptions for specific versions with no external audit. [[exemptions.my-small-dep]] version = "0.4.2" criteria = "safe-to-deploy" notes = "Reviewed by @owner on 2026-11-01; revisit by 2027-02-01 (#42)" ``` ### Audit criteria | Criteria | Meaning | |----------|---------| | `safe-to-deploy` | The crate is safe for use in release binaries. It has no malicious code or severe defects that prevent safe use. | | `safe-to-run` | The crate is safe for local development and CI. It will not send secrets to unauthorized recipients or give unauthorized access to a computer. | ### Audit procedure 1. Use `cargo vet init`. The command creates `supply-chain/` and adds exemptions for current dependencies. These exemptions identify audits that are still necessary. 2. Use `cargo vet suggest` to identify small changes for review. 3. Examine a version change with `cargo vet diff `. 4. Record an audit with `cargo vet certify`. If you trust a publisher, you can record that decision with `cargo vet trust`. 5. If you accept the risk of an unaudited version, add an exemption. In `notes`, identify the owner. Give the conditions for the exemption and the review date. 6. After dependency updates, use `cargo vet prune` to remove exemptions that do not apply. 7. Use `cargo vet --locked` in CI. With `--locked`, the command uses the reviewed `supply-chain/imports.lock`. Without it, the command can download remote `audits.toml` files during the build. ```text supply-chain/ ├── config.toml # Policy, trusted imports, and documented exemptions ├── audits.toml # Audits from your maintainers └── imports.lock # Versions of audits that --locked uses ``` ## `cargo-audit`: RustSec advisory & binary scanning [`cargo-audit`](https://github.com/rustsec/rustsec) compares `Cargo.lock` with the [RustSec Advisory Database](https://rustsec.org). It can also check binaries that you compile with `cargo-auditable`. ```bash # Audit Cargo.lock locally or in CI. cargo audit # To audit a release binary, configure cargo-audit with binary-scanning. cargo audit bin target/release/my-crate ``` Both `cargo deny check advisories` and `cargo audit` use RustSec for `Cargo.lock`. The checks give different results. - With the example `deny.toml`, `cargo deny check advisories` fails for vulnerabilities, unsound crates, yanked versions, and direct workspace dependencies with no maintainer. - `cargo audit` fails for vulnerabilities. It gives warnings for `unmaintained` and `unsound` advisories. Use `--deny warnings` to make these warnings cause failure. The command does not report a crate only because a newer version is available. - Crates.io keeps a yanked version available for current lockfiles. New dependency selections usually exclude it. Block yanked versions in CI. - `cargo audit bin` checks binaries that you compile with `cargo-auditable`. The check can operate without the source or the lockfile. ## Supply chain checks in CI Use `cargo-audit` and `cargo-deny` in the `security` job. Use `cargo vet --locked` in the `vet` job. Pin GitHub Actions to full commit SHAs. ```yaml jobs: security: runs-on: ubuntu-latest permissions: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11 with: tool: cargo-audit,cargo-deny - run: cargo audit - run: cargo deny check vet: runs-on: ubuntu-latest permissions: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11 with: tool: cargo-vet - run: cargo vet --locked ``` Set a minimum publication age with [Dependabot and Cargo](dependencies.md). The interval gives reviewers time to find a malicious release before it enters the lockfile. ## Further reading - [cargo-deny documentation](https://embarkstudios.github.io/cargo-deny/) - [cargo-vet documentation](https://mozilla.github.io/cargo-vet/) - [RustSec Advisory Database & cargo-audit](https://rustsec.org) - [NIST SP 800-218 SSDF](https://doi.org/10.6028/NIST.SP.800-218) --- # Security Scanning Scan the repository for vulnerabilities and secrets. Check the workflows for security defects. Record the use of `unsafe` code in the dependency tree. ## Secret protection and filesystem scans ### GitHub Push Protection CI scanners examine a commit after the push. If a secret becomes public in a branch or pull request, replace it immediately. An unauthorized person can use the secret to get access to the service. Enable **GitHub Secret Scanning and Push Protection**. The option is in **Settings**, under **Security and quality**, in **Advanced Security**. GitHub blocks pushes that contain recognizable tokens or keys. For an additional local check, you can use a pre-commit scanner such as [`gitleaks`](https://github.com/gitleaks/gitleaks). ### Repository & lockfile scanning: Trivy [Trivy](https://trivy.dev) scans the repository for known vulnerabilities and secrets in files. The scan includes `Cargo.lock`, containerfiles, scripts, and configuration files. ```bash trivy fs --scanners vuln,secret --exit-code 1 --skip-dirs target . ``` - `--scanners vuln,secret` selects vulnerability and secret scans. - `--exit-code 1` gives a failure exit code when the scan finds a problem. - `--skip-dirs target` omits compiled files and decreases the scan time. > **Caution.** Make sure that the scanner action uses a full 40-character > commit SHA from its source repository. > Set the Trivy binary version in `version:`. Use a read-only job with no > secrets for each scan. A malicious scanner can get credentials from runner > memory or environment variables. > > In March 2026, attackers published Trivy `v0.69.4` with malicious code. They > also moved more than 75 action tags to malicious code (`CVE-2026-33634`). ## CI workflow static analysis: `zizmor` A workflow defect can let an attacker steal release credentials. Examples include a template injection, an action without a fixed commit SHA, or too many permissions for `pull_request_target`. Use [`zizmor`](https://docs.zizmor.sh/) to check `.github/workflows/` locally. Use the same check in CI. ```bash zizmor .github/workflows ``` ## Checks for `unsafe` code ### 1. Compiler and Clippy checks Start with `unsafe_code = "forbid"` in `[lints.rust]`: ```toml [lints.rust] unsafe_code = "forbid" ``` If `unsafe` is necessary, keep the Edition 2024 warning `unsafe_op_in_unsafe_fn` active. Set `clippy::undocumented_unsafe_blocks = "deny"`. Clippy then rejects an `unsafe` block that has no `// SAFETY:` comment for its invariant. ### 2. Dependency-tree `unsafe` metrics (`cargo-geiger` and alternatives) [`cargo-geiger`](https://github.com/geiger-rs/cargo-geiger) counts `unsafe` functions, expressions, traits, and implementations in the crate and its transitive dependencies. ```makefile # Ignore cargo-geiger failure exit codes because this recipe gives information only. geiger: -cargo geiger ``` ### How to use the results - Use the counts to identify changes for review. Do not use the counts as a limit for the check result. A count does not show how well reviewers examined the code. Examine unexpected increases after a dependency change. - `cargo-geiger` has many dependencies. New Rust syntax can make a scanner update necessary. For a smaller syntax scanner, use [`cargo-issafe`](https://crates.io/crates/cargo-issafe) or [`cargo-trust`](https://github.com/ids1024/cargo-trust). - For call-graph analysis of `unsafe`, filesystem, and network operations, you can use [`cargo-scan`](https://github.com/PLSysSec/cargo-scan). ## Security scans in CI ```yaml jobs: security: runs-on: ubuntu-latest permissions: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11 with: tool: just,cargo-audit,cargo-deny,cargo-geiger - run: cargo audit - run: cargo deny check - uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 with: version: "v0.76.2" scan-type: fs scanners: vuln,secret exit-code: "1" skip-dirs: target - uses: zizmorcore/zizmor-action@45d7276c9ca790aabd705e31ca99c6185c3e76dd # v0.8.1 with: advanced-security: false - run: just geiger ``` ## Further reading - [Trivy documentation](https://trivy.dev) - [zizmor documentation](https://docs.zizmor.sh/) - [GitHub Secret Scanning & Push Protection](https://docs.github.com/en/code-security/secret-scanning/introduction/about-push-protection) - [cargo-geiger](https://github.com/geiger-rs/cargo-geiger) --- # Minimum Supported Rust Version The minimum supported Rust version (MSRV) is the earliest toolchain on which the crate builds and gives satisfactory test results. Cargo Resolver v3 uses the MSRV to select dependency versions. A continuous integration (CI) job does the checks on that toolchain. ## MSRV policy Rust makes a stable release at six-week intervals. Rust does not maintain long-term support branches or add security fixes to previous stable releases. For example, when Rust publishes `1.100.0`, upstream support for `1.99.x` ends. A fixed MSRV can keep users on compilers without security fixes. It also limits access to changes in the language and the standard library. Select a policy for your project. Record the policy in `README.md`. | Project type | Recommended MSRV | Example when stable is `1.100` | |--------------|------------------|--------------------------------| | Applications and command-line tools | The latest stable release or two releases earlier (N-2, approximately three months) | `"1.98"` to `"1.100"` | | General libraries | Four releases before the latest stable release (N-4, approximately six months) | `"1.96"` | | Base libraries and libraries in Linux packages | The minimum for the Rust edition or the toolchain of the target Linux distribution | `"1.85"` to `"1.92"` | Set `rust-version` in `Cargo.toml`. ```toml [package] edition = "2024" rust-version = "1.96" ``` If you use a workspace, set `rust-version = "1.96"` in `[workspace.package]`. Set `rust-version.workspace = true` in each member crate. ## How Cargo Resolver v3 uses the MSRV Cargo selects Resolver v3 by default if the root package uses Rust Edition 2024. In a virtual workspace, the editions of member crates do not set the resolver. For Resolver v3 in a virtual workspace, set `resolver = "3"` in `[workspace]`. To use Resolver v3, use Rust 1.84 or a newer version. Resolver v3 sets `incompatible-rust-versions` to `"fallback"` by default. When you use `cargo add` or `cargo update`, Cargo reads the `package.rust-version` value of each candidate dependency. For example, the latest dependency version can make Rust `1.99` necessary. For a crate with `rust-version = "1.96"`, Cargo usually selects the latest dependency version that supports `1.96`. To examine newer versions without the MSRV limit, use `cargo update --ignore-rust-version`. To read the metadata for a crate, use `cargo info `. ### Resolver limits The `fallback` policy gives priority to versions that support the MSRV. The continuous integration (CI) check is necessary for these cases. 1. No version in the permitted range supports the MSRV. Cargo can select a version that cannot build with the MSRV. 2. Workspace crates share a dependency version. The shared version can be incompatible with the MSRV of one or more crates. 3. A dependency has no `package.rust-version` value. Cargo cannot use the MSRV to select a version of that dependency. If a dependency becomes incompatible with the MSRV, set an upper version limit for that dependency. Add a comment that gives the condition for removal of the limit. ## Local MSRV check Use [`cargo-msrv`](https://github.com/foresterre/cargo-msrv) to check the toolchain in `rust-version`. As an alternative, use `cargo hack check --rust-version` with [`cargo-hack`](https://github.com/taiki-e/cargo-hack). ```bash cargo msrv verify # If you do not know the MSRV, use this command. # cargo msrv find ``` ### In the `justfile` ```makefile # Check the toolchain in rust-version in Cargo.toml. msrv: cargo msrv verify ``` ## Enforcing MSRV in CI The CI job starts the full test suite on the toolchain in `rust-version`. It uses `--locked` to use the dependency versions in `Cargo.lock`. ```yaml jobs: msrv: name: msrv (1.96) runs-on: ubuntu-latest env: # Use Rust 1.96 instead of the version in rust-toolchain.toml. RUSTUP_TOOLCHAIN: "1.96" steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: "1.96" - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - run: cargo test --all-features --locked ``` ### Full test suite `cargo check` does not link binaries or start tests. Standard library behavior, `const` evaluation, or a dependency with no `rust-version` can cause a failure during a build or test on the MSRV. For a published library, you can also check the lowest permitted versions of direct dependencies. Use `cargo +nightly update -Z direct-minimal-versions` before you build the library. ## Increase the MSRV 1. Make sure that the new MSRV agrees with the version policy. For example, the policy can permit an increase to N-4 in a minor release only. 2. Set `rust-version` in `Cargo.toml`. 3. Put the new MSRV in the `msrv` job name. 4. Set `env.RUSTUP_TOOLCHAIN` in the job to the new MSRV. 5. Set the toolchain action's `with.toolchain` input to the new MSRV. 6. Update `AGENTS.md`. 7. If the previous MSRV limited dependency versions, use `cargo update`. 8. Commit these changes together. If `Cargo.lock` changes, include it in the commit. Use a commit title that agrees with your Semantic Versioning policy. For example, use `chore: bump MSRV to 1.96`. ## Further reading - [The Cargo Book: MSRV-aware Resolver (`rust-version`)](https://doc.rust-lang.org/cargo/reference/resolver.html#rust-version) - [The Cargo Book: `cargo info`](https://doc.rust-lang.org/cargo/commands/cargo-info.html) - [cargo-msrv documentation](https://github.com/foresterre/cargo-msrv) - [Rust Release Channel & Platform Support](https://doc.rust-lang.org/rustc/platform-support.html) --- # CI/CD Pipeline The continuous integration (CI) pipeline checks quality, compatibility, and security for each change. It starts jobs on each target operating system. Jobs have read-only permissions by default. The workflow uses full commit SHAs for GitHub Actions. ## Workflow configuration 1. Put the test, lint, SemVer, MSRV, security, and supply-chain checks in different jobs. The jobs can operate in parallel. A format error does not stop the Windows test job or the security job. 2. Use Linux, macOS, and Windows in the test matrix. The matrix can find differences in paths, newlines, file locks, and environment variables. 3. Use `concurrency` to cancel a previous pull request job after a new push. Do not cancel jobs for `main`. 4. Use `Swatinem/rust-cache` to cache `~/.cargo` and applicable files in `target/`. This can decrease elapsed CI time by 50 to 80 percent. 5. Scan `.github/workflows/` with `zizmor`. The scan can identify template injection and actions without full commit SHAs. It can also identify tokens that have more permissions than necessary. ## The CI workflow ```yaml name: CI on: push: branches: [main] pull_request: # Mandatory checks must report a result to the merge queue. # Each merge group uses a different ref. Thus, a new group cannot cancel its checks. merge_group: schedule: # The weekly scan finds new advisories when there are no recent changes. - cron: "0 6 * * 1" concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} env: CARGO_TERM_COLOR: always # Give jobs read-only access by default. # Give write or OIDC permissions only to release and attestation jobs on protected refs. permissions: contents: read jobs: test: name: test (${{ matrix.os }}) strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11 with: tool: cargo-nextest - run: cargo nextest run --all-features --locked # If the package has no library target (src/lib.rs), omit the doctest command. - run: cargo test --doc --all-features --locked lint: name: lint & doc runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable components: rustfmt, clippy - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - run: cargo fmt --check - run: cargo clippy --all-targets --all-features --locked -- -D warnings - name: Check rustdoc and intra-doc links env: RUSTDOCFLAGS: -D warnings run: cargo doc --no-deps --all-features --locked msrv: name: msrv (1.96) runs-on: ubuntu-latest env: # Use Rust 1.96 instead of the version in rust-toolchain.toml. RUSTUP_TOOLCHAIN: "1.96" steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: "1.96" - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - run: cargo test --all-features --locked security: name: security runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11 with: tool: just,cargo-audit,cargo-deny,cargo-geiger - run: cargo audit - run: cargo deny check - uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 with: version: "v0.76.2" scan-type: fs scanners: vuln,secret exit-code: "1" skip-dirs: target - uses: zizmorcore/zizmor-action@45d7276c9ca790aabd705e31ca99c6185c3e76dd # v0.8.1 with: advanced-security: false - run: just geiger vet: name: vet runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11 with: tool: cargo-vet - run: cargo vet --locked ``` ### The `semver` workflow (`.github/workflows/semver.yml`) The `semver` check uses the pull request title. Its workflow starts again when the title changes. Keep the `edited` trigger in the semver workflow to prevent title and description changes from starting the full test matrix. ```yaml name: SemVer on: pull_request: # Use edited to start the check again when the pull request title changes. # A change from feat!: to feat: can change the result. types: [opened, edited, reopened, synchronize] # Mandatory checks must report a result to the merge queue. # The job skips the check and reports success because CI checks each pull request. # In queue settings, enable "Only merge non-failing pull requests". merge_group: concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true permissions: contents: read jobs: semver: name: semver if: github.event_name == 'pull_request' runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 # the baseline commit must exist locally persist-credentials: false - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11 with: tool: cargo-semver-checks - name: Check API changes against the base branch env: BASE_SHA: ${{ github.event.pull_request.base.sha }} # Read the title from the environment. Do not insert it into shell code. TITLE: ${{ github.event.pull_request.title }} run: | # The ! marker tells reviewers about an intentional incompatible change. # release-plz selects the version for that change. # Without the marker, the public API must stay compatible. release_type=minor if [[ "$TITLE" =~ ^[a-z]+(\([^\)]*\))?!: ]]; then release_type=major fi cargo semver-checks --baseline-rev "$BASE_SHA" --release-type "$release_type" ``` ## Job breakdown ### `test` — cross-platform nextest + doctests The job uses Linux, macOS, and Windows. With `fail-fast: false`, a failure on one platform does not stop the tests on the other platforms. The job uses `cargo nextest run --all-features --locked` with one process for each test. It uses `cargo test --doc --all-features --locked` for documentation examples. ### `lint` — formatting, clippy, and rustdoc The job uses these commands. - `cargo fmt --check` - `cargo clippy --all-targets --all-features --locked -- -D warnings` - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` ### `semver` — public API compatibility (libraries) The [`semver` workflow](#the-semver-workflow-githubworkflowssemveryml) starts again when the pull request title changes. The `cargo-semver-checks` command compares the pull request with its base commit (`--baseline-rev`). A comparison with crates.io could reject all pull requests after an intentional incompatible change until the next release. For an intentional incompatible change, add `!` to the pull request title. Refer to [Commit conventions](releases.md#commit-conventions). The job uses `--release-type major` when the title contains `!`. The title shows the change to reviewers. `release-plz` increases the major version in the next release pull request, or the minor version for `0.x`. If the title has no `!`, the job uses `--release-type minor`. The job fails when it finds an incompatible change. `cargo-semver-checks` can miss some changes, such as some return-type changes. Reviewers must also check that the title has the marker when necessary. The job checks pull requests. A merge-queue job skips the check and reports success. If you use GitHub Merge Queue, enable **Only merge non-failing pull requests**. Otherwise, a pull request with a failed check can merge as part of a group. At release time, `release-plz` checks the published crate (`semver_check = true`). If the repository publishes only binaries, you can omit this job. ### `msrv` — MSRV enforcement The workflow sets the MSRV directly. The job starts the full test suite with `--locked` on that toolchain. If you change `rust-version` in `Cargo.toml`, update the workflow in the same commit. Refer to [Increase the MSRV](msrv.md#increase-the-msrv). ### `security` — advisories, licenses, secrets, workflow linting, and `unsafe` The job uses these checks. - `cargo audit` and `cargo deny check`. - Trivy filesystem scans for vulnerabilities and secrets (`vuln,secret`). The workflow uses the full commit SHA for the scanner action. - `zizmor` checks `.github/workflows/`. - `just geiger` gives an informational report on `unsafe` code. ### `vet` — locked supply-chain trust verification The job uses `cargo vet --locked`. The command uses the reviewed `supply-chain/imports.lock` and does not download new audit records. ## Pinning action versions and auditing workflows For each GitHub Action, use the full 40-character commit SHA. Add a comment with the version. ```yaml - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 ``` A person with access to an upstream action repository can move a tag such as `@v1` or `@v0.36.0`. In March 2026, attackers moved more than 75 tags of the Trivy actions to code that could steal credentials (`CVE-2026-33634`). Workflows that used the affected tags started the malicious code. Workflows with unaffected commit SHAs continued to use their original code. To find the correct commit SHA, resolve the version tag in the action repository. ```bash gh api repos/actions/checkout/commits/v7.0.1 --jq .sha ``` Use these workflow security controls. - Enable the GitHub Actions policy that makes full commit SHAs mandatory. - Limit which third-party actions and reusable workflows can operate. - If the job does not push commits, set `persist-credentials: false` in `actions/checkout`. `zizmor` can report an absent setting under `artipacked`. - Make sure that the actions support Node 24. GitHub removed Node 20 from its hosted runners in September 2026. - Block access to secrets and write tokens from untrusted forks. `actions/checkout@v7` also blocks unsafe fork checkouts with the `pull_request_target` trigger. ## Records and scheduled checks Pull request checks occur when code changes. A weekly `schedule` check can find new RustSec advisories in a repository without recent changes. A new advisory can also cause all open pull requests to fail. If necessary, put the advisory scan in its own daily workflow. Record the response to each alert. Keep release job logs, checksums, SBOMs, provenance attestations, and test reports for the support or contractual period. Do not publish logs with sensitive data or raw memory dumps as public artifacts. ## Further reading - [GitHub Actions secure use reference](https://docs.github.com/en/actions/reference/security/secure-use) - [zizmor: static security analysis for GitHub Actions](https://docs.zizmor.sh/) - [cargo-nextest in CI](https://nexte.st/docs/ci-features/) - [cargo-semver-checks](https://github.com/obi1kenobi/cargo-semver-checks) - [Swatinem/rust-cache](https://github.com/Swatinem/rust-cache) - [taiki-e/install-action](https://github.com/taiki-e/install-action) --- # Release Automation Use a protected continuous integration (CI) workflow to create each release tag, crates.io package, and binary. The workflow calculates the version, generates the changelog, and updates the lockfile. It builds binaries, publishes the crate, and generates an SBOM and provenance attestations. A person must review the release pull request before the merge. ## Release automation with `release-plz` [`release-plz`](https://release-plz.dev/) supports Cargo workspaces. It uses [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) and [`cargo-semver-checks`](https://github.com/obi1kenobi/cargo-semver-checks). 1. If `cargo-semver-checks` finds an incompatible change in a public API, `release-plz` selects the version for an incompatible change. It records the API change in the release pull request. This also applies when the original pull request title uses `fix:` or `feat:`. 2. `release-plz` updates `Cargo.toml`, `Cargo.lock`, and `CHANGELOG.md` in the release pull request. CI checks these files before the merge. The release tag then points to a commit that already contains the new lockfile. 3. `release-plz` supports crates.io OIDC Trusted Publishing. It exchanges a temporary GitHub OIDC token with crates.io. It does not store a long-term `CARGO_REGISTRY_TOKEN` secret. ### Commit conventions | Prefix | Usual version change | Example | |--------|----------------------|---------| | `fix:` | Patch (`0.1.x` or `1.0.x`) | `fix: degrade wrong-typed JSON fields to None` | | `feat:` | Minor (`1.x.0`) | `feat: add TOML config file support` | | `!:` | Major (`x.0.0`), or minor for `0.x`. A release check that finds an incompatible API change gives the same result. | `feat!: require structured Error return` | Set `release_commits` in `release-plz.toml`. With this filter, a commit with `docs:`, `chore:`, `ci:`, `refactor:`, or `test:` enters the changelog. That commit cannot cause a release pull request by itself. Without the filter, `release-plz` updates the package for each commit and opens a release pull request for a patch release. To publish a dependency fix in its own release, use `fix(deps): …` in the pull request title. For example, use this type for a security fix in a binary's `Cargo.lock`. Add `!` to the commit header for each incompatible change. Examples are `feat!:` and `refactor(api)!:`. Conventional Commits also permits a `BREAKING CHANGE:` footer. In this configuration, `release_commits` reads the header. The squash merge does not copy the footer to `main`. A footer alone can cause an incorrect minor or patch release. The CI [`semver` job](ci-cd.md#semver--public-api-compatibility-libraries) fails if it finds an incompatible API change and the title lacks `!`. The job can miss some changes to parameters or return types. It does not check changes in behavior or in the command-line interface. Review those changes for the necessary `!` marker. For the complete format, refer to the [Conventional Commits 1.0.0 specification](https://www.conventionalcommits.org/en/v1.0.0/#specification). ### Enforcing the convention `release-plz` uses the commit messages to calculate versions and generate the changelog. Apply these controls to make the commit messages agree with Conventional Commits. 1. Enable squash merges only. Use only the pull request title in the commit message. Each commit on `main` then uses the title that CI checks. If the latest branch commit has `[skip ci]`, GitHub skips the `pull_request` workflows. The mandatory `pr-title` check gives no result. To start the check again, push a commit without that marker. `zizmor` can report a security issue if you use `pull_request_target`. ```bash gh api -X PATCH repos/OWNER/REPO \ -F allow_squash_merge=true -F allow_merge_commit=false -F allow_rebase_merge=false \ -f squash_merge_commit_title=PR_TITLE -f squash_merge_commit_message=BLANK ``` `BLANK` keeps the pull request description out of the commit. A `[skip ci]` marker can stop the workflows for a push to `main` if the marker becomes part of the commit. This includes the release workflow. Thus, use `!` in the title to mark an incompatible change. The squash merge does not copy a `BREAKING CHANGE:` footer from the description. GitHub uses these settings to set the default message in the merge dialog. Review the message before you merge. On GitHub Enterprise Cloud, you can also enforce the format on `main` with the **commit message pattern** restriction in a ruleset. 2. Check the pull request title in CI. This workflow uses no third-party actions and has no token permissions. ```yaml # .github/workflows/pr-title.yml name: PR title on: pull_request: # The edited event starts the check again after a title change. # The synchronize event starts the check for the latest commit. types: [opened, edited, reopened, synchronize] # Mandatory checks must report a result to the merge queue. # The job reports success because CI checks each pull request title. # In queue settings, enable "Only merge non-failing pull requests". merge_group: permissions: {} jobs: pr-title: name: pr-title runs-on: ubuntu-latest steps: - name: Check PR title follows Conventional Commits if: github.event_name == 'pull_request' env: # Read the title from an environment variable. # Do not insert the title into shell code. TITLE: ${{ github.event.pull_request.title }} run: | spec='See https://www.conventionalcommits.org/en/v1.0.0/' pattern='^(feat|fix|docs|chore|ci|refactor|test)(\([A-Za-z0-9._/-]+\))?!?: [^[:space:]].*$' if [[ ! "$TITLE" =~ $pattern ]]; then echo "::error title=PR title is not a Conventional Commit::Use '[(scope)][!]: ', e.g. 'feat(cli): add --json output'. $spec" exit 1 fi # The title becomes the commit message on main. # A skip marker in the message can stop CI and release workflows. skip='\[(skip ci|ci skip|no ci|skip actions|actions skip)\]' if [[ "${TITLE,,}" =~ $skip ]]; then echo "::error title=PR title contains a workflow skip marker::Remove it; it would skip CI and releases on main." exit 1 fi ``` Make `pr-title` a mandatory check in the branch ruleset. Refer to [Project governance](governance.md#branch-and-tag-protection-with-github-rulesets). If you use GitHub Merge Queue, enable **Only merge non-failing pull requests**. Otherwise, a pull request with a failed title check can merge in a group. The merge-group workflow does not check the titles again. 3. Configure automated pull request titles. `release-plz` uses `chore: release v…` or `chore(): release v…` for one package in a workspace. The check accepts the two formats. Set the Dependabot `commit-message` option. Refer to [Dependabot groups and minimum publication age](dependencies.md#dependabot-groups-and-minimum-publication-age). Use the same types in the pattern, `CONTRIBUTING.md`, and `AGENTS.md`. With merge commits or rebase merges, each branch commit becomes part of `main`. If you permit these merges, check each commit message with a tool such as [`commitlint`](https://commitlint.js.org/) or [`cocogitto`](https://docs.cocogitto.io/). ### Configuration (`release-plz.toml`) ```toml # release-plz.toml [workspace] changelog_update = true dependencies_update = false # Dependabot updates external dependencies. git_release_enable = true # Create a GitHub release when the job publishes the tag. git_release_draft = true # Keep a draft until you upload the binaries and SBOMs. pr_labels = ["release"] # Open release pull requests for features, fixes, and incompatible changes (type!:). # Other commits enter the changelog. release_commits = "^((feat|fix)[(!:]|[a-z]+(\\([^)]*\\))?!:)" semver_check = true # Use cargo-semver-checks to calculate new versions. [[package]] name = "my-crate" git_tag_name = "v{{ version }}" ``` ### Release pull request procedure Do not manually edit `version` in `Cargo.toml`. Do not manually edit `CHANGELOG.md`. The release pull request updates the files. After a release pull request merges, `release-plz release` publishes the code on `main`. The `release-pr` job updates the release pull request after each push to `main`. If a change merges after the job, the version and changelog can omit that change. For example, an incompatible change could enter a minor release. > **Caution.** Do not select **Update branch** on the release pull request. > This control merges `main` into the pull request without a new version > calculation or changelog. Let `release-plz` update the release pull request. 1. Make sure that **Require branches to be up to date** is active. Refer to [Project governance](governance.md#branch-and-tag-protection-with-github-rulesets). 2. Wait for the `release-pr` job for the latest `main` commit to complete. 3. Examine the new version and changelog. 4. If you use a merge queue, add the release pull request only when the queue is empty. Other pull requests in the queue can add changes that the release job did not use to calculate the version. 5. When the release pull request is current, merge it. ### First crate release Publish the first release of a new crate name manually. For example, publish `0.1.0`. You can then configure Trusted Publishing on crates.io. Later releases use OIDC. ## Crates.io OIDC Trusted Publishing setup Configure **Trusted Publishing** before you automate releases. This procedure lets the workflow publish without a long-term crates.io API token. 1. Open the crate page on [crates.io](https://crates.io). 2. Select **Settings**. 3. Select **Trusted Publishing**. 4. Add a GitHub configuration. 5. Set **Repository owner** to the GitHub repository owner. 6. Set **Repository name** to the GitHub repository name. 7. Set **Workflow filename** to `release.yml`. 8. Set **Environment** to `release`. 9. In the GitHub repository settings, open **Environments**. 10. Create a protected environment with the name `release`. 11. Limit deployments to the `main` branch. 12. If reviewers are necessary, add the reviewers to the environment. If a custom workflow uses `cargo publish` directly, use `rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9`. This action exchanges the OIDC JWT for a temporary `CARGO_REGISTRY_TOKEN`. ## The release workflow (`.github/workflows/release.yml`) ```yaml name: Release on: push: branches: [main] permissions: contents: read jobs: # Open or update the release pull request after each merge to main. release-pr: name: release-pr if: ${{ !startsWith(github.event.head_commit.message, 'chore(release):') }} # Update one release pull request at a time. The job checks for the latest commit. concurrency: group: release-plz-${{ github.ref }} cancel-in-progress: false # Keep each pending job in the queue. Thus, a new job cannot replace a pending job. # actionlint 1.7.12 and earlier do not recognize queue (rhysd/actionlint#654). queue: max runs-on: ubuntu-latest permissions: contents: write pull-requests: write steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 persist-credentials: false - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 id: app-token with: client-id: ${{ vars.RELEASE_APP_CLIENT_ID }} private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} # Give the token only the permissions for the release branch and pull request. permission-contents: write permission-pull-requests: write # Jobs can operate in a different sequence from pushes. # If main has a newer commit, skip this job. # The job for the latest commit updates the release pull request. - name: Check this run is for the latest main commit id: fresh env: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} RUN_SHA: ${{ github.sha }} run: | head=$(gh api "repos/$REPO/commits/main" --jq .sha) if [ "$head" = "$RUN_SHA" ]; then latest=true; else latest=false; fi echo "latest=$latest" >> "$GITHUB_OUTPUT" - name: Update Release PR if: steps.fresh.outputs.latest == 'true' uses: release-plz/action@66b324fd6c72d05d2a08568492ecdd62bfb8a62b # v0.5.148 with: command: release-pr env: GITHUB_TOKEN: ${{ steps.app-token.outputs.token }} # After a release pull request merges to main, publish to crates.io with OIDC. # Create the Git tag and GitHub release. release: name: release runs-on: ubuntu-latest environment: release outputs: releases_created: ${{ steps.rp.outputs.releases_created }} releases: ${{ steps.rp.outputs.releases }} permissions: contents: write id-token: write # crates.io Trusted Publishing uses this permission. steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 persist-credentials: false - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 id: app-token with: client-id: ${{ vars.RELEASE_APP_CLIENT_ID }} private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} # The release job publishes Git tags and GitHub releases. # It reads pull requests to find the release and identify contributors. permission-contents: write permission-pull-requests: read - name: Release crates and tag id: rp uses: release-plz/action@66b324fd6c72d05d2a08568492ecdd62bfb8a62b # v0.5.148 with: command: release env: GITHUB_TOKEN: ${{ steps.app-token.outputs.token }} # Do not set CARGO_REGISTRY_TOKEN. release-plz uses OIDC automatically. ``` ### GitHub App token for the release workflow Commits, pull requests, and tags from the default `GITHUB_TOKEN` do not start the specified CI or tag workflows. Use `actions/create-github-app-token@v3` to get a temporary installation token. The token lets CI check the release pull request before the merge. It also lets a new release tag start applicable workflows. Give the GitHub App read and write access to **Contents** and **Pull requests**. These are the minimum permissions for the app in the `release-plz` configuration. For each job, select only the necessary permissions with the `permission-*` inputs. If you omit these inputs, the token gets all permissions of the app installation. `zizmor` reports this condition under [`github-app`](https://docs.zizmor.sh/audits/#github-app). ## Cross-platform binary builds and `cargo-auditable` If you publish compiled command-line or service binaries, use current native GitHub-hosted runners. GitHub Actions no longer has `macos-14`. ```yaml build-binaries: name: build (${{ matrix.target }}) needs: release if: ${{ needs.release.outputs.releases_created == 'true' }} runs-on: ${{ matrix.runner }} permissions: contents: write id-token: write attestations: write artifact-metadata: write strategy: fail-fast: false matrix: include: - runner: ubuntu-22.04 target: x86_64-unknown-linux-gnu archive_ext: tar.gz - runner: ubuntu-22.04-arm target: aarch64-unknown-linux-gnu archive_ext: tar.gz - runner: macos-15 target: aarch64-apple-darwin archive_ext: tar.gz - runner: windows-latest target: x86_64-pc-windows-msvc archive_ext: zip - runner: windows-11-arm target: aarch64-pc-windows-msvc archive_ext: zip ``` ### Target platforms and libraries - GNU binaries from `ubuntu-22.04` link to an earlier version of `glibc` than binaries from `ubuntu-24.04`. This can make the binaries compatible with earlier Linux distributions. For static Linux binaries without `glibc`, use `x86_64-unknown-linux-musl` or `aarch64-unknown-linux-musl`. - Rust moved Intel macOS (`x86_64-apple-darwin`) to Tier 2 in Rust 1.90. The Rust project builds standard library files for this target. The project no longer does automated tests on Intel macOS. If you build for this target from `macos-15`, record the Tier 2 support level in `README.md`. - To generate installers, use [`dist`](https://github.com/axodotdev/cargo-dist) with `release-plz`. The tool can generate shell and PowerShell installers, Homebrew formulas, and MSI packages. Its previous name was `cargo-dist`. ### Dependency records with `cargo-auditable` Compile each release binary with [`cargo-auditable`](https://github.com/rust-secure-code/cargo-auditable). ```bash cargo auditable build --release --locked --target "${{ matrix.target }}" ``` `cargo-auditable` adds a compressed dependency manifest to the `dep-v0` section of the binary. Thus, `cargo audit bin`, Trivy, Grype, and OSV-Scanner can check a deployed binary without the source code or `Cargo.lock`. ## Release files and verification Put each binary in an archive with `README.md`, `LICENSE-MIT`, and `LICENSE-APACHE`. Put all release archives in `dist/`. In the binary crate directory, set `TARGET` to the target triple for the release build. Use the same feature options for `cargo cyclonedx` and the build. These options include `--features`, `--no-default-features`, and `--all-features`. ```bash mkdir -p dist cargo cyclonedx --format json --describe binaries --target "$TARGET" --target-in-filename mv -- ./*.cdx.json dist/ ``` `cargo cyclonedx` writes each SBOM next to its crate manifest. For a workspace, copy the SBOMs for the release binaries from the member directories to `dist/`. For a workspace with more than one crate, you can also generate an SPDX 2.3 JSON SBOM. ```bash cargo sbom --output-format spdx_json_2_3 > dist/my-crate-sbom.spdx.json ``` When `dist/` contains all release archives and SBOMs, make the checksum file. This Bash example uses file names without the `dist/` path. Thus, adopters can check the files in their download directory. ```bash ( set -e cd dist shopt -s nullglob archives=(*.tar.gz *.zip) sboms=(*.cdx.json *.spdx.json) (( ${#archives[@]} > 0 && ${#sboms[@]} > 0 )) sha256sum -- "${archives[@]}" "${sboms[@]}" > SHA256SUMS ) ``` ### Meeting CISA's 2026 Minimum Elements for an SBOM Use **CISA's July 2026 Minimum Elements for a Software Bill of Materials** for the SBOM. Include component hashes, licenses, and information about the SBOM tool. Give the transitive dependencies and the conditions under which the tool generated the SBOM. Generate the SBOM from the dependency tree that the release builds use with `--locked`. Record the target triple in the release notes. Record the Cargo features in the release notes. Attach the SBOM and `SHA256SUMS` to the GitHub release. ### Build provenance attestations and immutable releases Use `actions/attest@v4` to attest each release archive and SBOM. The attestation links the file to the repository, commit SHA, and release workflow. `actions/attest-build-provenance@v4` uses `actions/attest` internally. ```yaml - name: Attest release artifacts uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 with: subject-path: | dist/*.tar.gz dist/*.zip dist/*.cdx.json dist/*.spdx.json ``` 1. On GitHub, open the repository **Settings**. 2. Under **General**, go to **Releases**. 3. Select **Enable release immutability**. 4. Set `git_release_draft = true` in `release-plz.toml`. 5. Upload all platform archives, SBOMs, and `SHA256SUMS` to the draft release. > **Caution.** Make sure that the draft contains all release files before you > publish it. After publication, GitHub prevents changes to the tag and the > release files. GitHub also prevents uploads to the release. 6. Add a `publish-release` job under `jobs` in the release workflow. 7. Put `release` and all jobs that upload release files in `needs`. Publication starts only after these jobs succeed. If a different job uploads the SBOMs or `SHA256SUMS`, include that job in `needs` too. The example uses `build-binaries` for file uploads. The publication job waits for all targets in the build matrix. It publishes the draft for each tag that `release-plz` reports. If you do not have a `build-binaries` job, omit it from `needs`. Keep `release` and each job that uploads release files in `needs`. ```yaml publish-release: needs: [release, build-binaries] if: ${{ needs.release.outputs.releases_created == 'true' }} runs-on: ubuntu-latest permissions: contents: write steps: - name: Publish draft releases shell: bash env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} RELEASES: ${{ needs.release.outputs.releases }} run: | tags=$(jq -er '.[].tag' <<< "$RELEASES") while IFS= read -r tag; do gh release edit "$tag" --draft=false done <<< "$tags" ``` The example uses the default `GITHUB_TOKEN` to publish the drafts. This token does not start workflows that use `on: release`. If publication must start another workflow, use a GitHub App installation token with `contents: write` for `GH_TOKEN`. Give adopters the verification commands in `README.md` or the release notes. ```bash sha256sum --check SHA256SUMS gh release verify v0.2.0 --repo YOUR_ORGANIZATION/YOUR_REPOSITORY gh attestation verify ./my-crate-0.2.0-x86_64-unknown-linux-gnu.tar.gz \ --owner YOUR_ORGANIZATION \ --signer-workflow YOUR_ORGANIZATION/YOUR_REPOSITORY/.github/workflows/release.yml ``` ## Further reading - [release-plz documentation](https://release-plz.dev/) - [crates.io Trusted Publishing (OIDC) guide](https://crates.io/docs/trusted-publishing) - [Conventional Commits 1.0.0 specification](https://www.conventionalcommits.org/en/v1.0.0/) - [cargo-auditable documentation](https://github.com/rust-secure-code/cargo-auditable) - [cargo-cyclonedx](https://github.com/CycloneDX/cyclonedx-rust-cargo) & [cargo-sbom](https://crates.io/crates/cargo-sbom) - [CISA Software Bill of Materials (SBOM) resources](https://www.cisa.gov/sbom) - [GitHub Artifact Attestations](https://docs.github.com/en/actions/concepts/security/artifact-attestations) --- # Dependency Management Each dependency can add a security risk. Use Dependabot to group updates and set a minimum publication age. Use Cargo to select versions that support the minimum supported Rust version (MSRV). Enable only the necessary features. ## Dependabot groups and minimum publication age [Dependabot](https://docs.github.com/en/code-security/dependabot) opens pull requests for updates that meet the dependency policy. ```yaml # .github/dependabot.yml version: 2 updates: - package-ecosystem: "cargo" directory: "/" schedule: interval: "weekly" commit-message: prefix: "chore" # release_commits excludes titles such as "chore(deps): bump …". include: "scope" cooldown: default-days: 7 semver-major-days: 14 semver-minor-days: 7 semver-patch-days: 3 groups: cargo-minor-and-patch: update-types: - "minor" - "patch" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" commit-message: prefix: "ci" # PR title "ci(deps): bump …" include: "scope" cooldown: default-days: 7 groups: actions: patterns: - "*" ``` ### Purposes of `groups:` and `cooldown:` - With only `interval: "weekly"`, Dependabot opens a different pull request for each outdated crate. Use `groups:` to put minor and patch updates in one weekly pull request. Review major updates in different pull requests. - Use `cooldown:` to give reviewers time to find malicious releases before Dependabot selects them. An interval of three to seven days is an example. Security advisory updates can ignore this interval automatically. ### Updates that Dependabot can make - Dependabot updates dependencies in `Cargo.toml` and `Cargo.lock`. For GitHub Actions, it updates the commit SHA and the version comment. - Dependabot opens security update pull requests immediately. This also applies to transitive dependencies that appear only in `Cargo.lock`. - Dependabot does not update `rust-toolchain.toml`. To update this file automatically, use [Renovate](https://docs.renovatebot.com/). ## Cargo minimum publication age (Rust 1.100 or later) Dependabot's minimum publication age applies to Dependabot only. A manual `cargo update` or a new transitive dependency can select a recent release. Set the same minimum age in `.cargo/config.toml`. Cargo 1.100 added this option. ```toml # .cargo/config.toml [registry] global-min-publish-age = "7 days" ``` If a necessary security patch is newer than the minimum age, examine the advisory. Then use this command to select the patch. ```bash CARGO_RESOLVER_INCOMPATIBLE_PUBLISH_AGE=allow cargo update -p '' --precise '' ``` Replace `` and `` with the crate name and patch version. The override applies to all versions that Cargo selects for this command. Examine new transitive versions in the `Cargo.lock` diff. ## Version requirements ### Standard Semantic Versioning ranges ```toml [dependencies] serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } flate2 = { version = "1", default-features = false, features = ["rust_backend"] } ``` Standard Cargo ranges such as `"1"` and `"0.8"` permit compatible updates. They exclude the next incompatible version. - Use standard ranges in published libraries. Cargo Resolver v3 gives priority to dependencies that support `package.rust-version`. - Use a minor-version upper limit such as `<1.2` only for a known defect or missing MSRV metadata. Record why the limit is necessary. An upper limit can prevent a user from using one dependency version or getting a security fix. - Set the lowest version that has the APIs your library uses. For example, if an API first appears in Serde 1.0.200, set `"1.0.200"`. - To check the lower limits for direct dependencies, use `cargo +nightly update -Z direct-minimal-versions`. Then build the library. ## Dependency maintenance ### Unused dependencies Each dependency adds code to compile and review. It can also add vulnerabilities or `unsafe` code. 1. If 30 to 50 lines of standard library code are sufficient, write the function in the crate. 2. Examine the dependency tree with `cargo tree`. 3. Examine duplicate versions with `cargo tree -d`. 4. Set `unused_crate_dependencies = "warn"` in `[lints.rust]`. Cargo 1.100 gives diagnostics for unused dependencies. You can also use `cargo-machete` for workspaces with multiple targets. `Cargo.toml`. ### Default features and pure-Rust backends ```toml flate2 = { version = "1", default-features = false, features = ["rust_backend"] } reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json"] } ``` If only some features are necessary, disable the default features. When possible, use a pure-Rust backend such as `miniz_oxide` or `rustls`. You can then build without a C toolchain. It can also decrease the amount of `unsafe` code at the foreign function interface (FFI). ### New dependencies If you add a dependency, show why it is necessary in the commit message or pull request. Give the license, maintenance status, and `cargo vet` audit or exemption status. ## Lockfile management ### When to commit `Cargo.lock` - For an application, command-line tool, or service, commit `Cargo.lock`. Use `--locked` in CI and release builds. - For a library, usually commit `Cargo.lock`. This gives CI and MSRV checks a fixed set of dependency versions. It also supports `git bisect`. Cargo `new --lib` no longer adds the lockfile to `.gitignore` as of Rust 1.75. - Cargo uses the dependencies' `Cargo.toml` files to select versions for users of a published library. It ignores the dependencies' lockfiles. - If you commit a library lockfile, add a scheduled, non-blocking CI job on `stable`. Use `CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS=allow cargo update` in that job. Then start the tests with `cargo test`. The job can identify compatibility problems with new dependencies, including versions above the library's MSRV. ### Updates to `Cargo.lock` 1. Use `cargo update` when you plan an update, or review a grouped Dependabot pull request. 2. Examine the changes in `Cargo.lock` with `cargo vet diff` or `git diff Cargo.lock`. 3. Start the checks with `just ci` after each lockfile change. ## Further reading - [Dependabot options reference (`groups` and `cooldown`)](https://docs.github.com/en/code-security/dependabot/working-with-dependabot/dependabot-options-reference) - [The Cargo Book: Specifying Dependencies](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html) - [The Cargo Book: Resolver MSRV-aware version selection](https://doc.rust-lang.org/cargo/reference/resolver.html#rust-version) - [Rust Blog: Committing Lockfiles](https://blog.rust-lang.org/2023/08/29/committing-lockfiles/) --- # Local Development Contributors and coding agents can install prebuilt tools after they clone the repository. The local tools do the same checks as continuous integration (CI). ## The `justfile` The `justfile` gives contributors one place to find development commands. Use `just` to see the recipes. Use `just ci` to start the full check suite. ```makefile # Show the recipes by default. Use just ci to start all checks. default: @just --list # Do the format check without changes to files. fmt: cargo fmt --check # Format the files. fmt-fix: cargo fmt # Lint all targets and features. Treat warnings as errors. lint: cargo clippy --all-targets --all-features --locked -- -D warnings # Build the API documentation. Include the check for broken links. doc: RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked # Start the tests. If the crate has no src/lib.rs, omit cargo test --doc. test: cargo nextest run --locked cargo test --doc --locked # Compare the public API with the merge base of main. CI uses the same baseline. # This comparison excludes changes that main got after the two branches diverged. # If the pull request title has the ! marker, use just semver major. semver release_type="minor": git fetch origin main cargo semver-checks --baseline-rev "$(git merge-base HEAD origin/main)" --release-type {{release_type}} # Check dependencies against the RustSec advisory database. audit: cargo audit # Do the MSRV check. msrv: cargo msrv verify # Check licenses, banned crates, duplicate versions, and dependency sources. deny: cargo deny check # Scan the filesystem for known vulnerabilities and hardcoded secrets. trivy: trivy fs --scanners vuln,secret --exit-code 1 --skip-dirs target . # Audit GitHub Actions workflows for security vulnerabilities. zizmor: zizmor .github/workflows # Check the dependency tree with the audit records in the lockfile. vet: cargo vet --locked # Report the amount of unsafe code. The hyphen makes just ignore failure exit codes. geiger: -cargo geiger # Start all checks. The command stops if a recipe fails. ci: fmt lint doc test audit msrv deny trivy zizmor vet geiger ``` ### What `just` does - `just` shows each recipe with its comment. - `just` operates on Linux, macOS, and Windows. - The recipes use `--locked` where applicable. Thus, local checks use the same dependency versions as CI. - `just ci` stops when a check fails. Add [`rust-toolchain.toml`](scaffolding.md#toolchain-pinning-rust-toolchaintoml) to the repository. When you first use Cargo, `rustup` installs the compiler, `rustfmt`, and Clippy versions from that file. ## `AGENTS.md` and `CLAUDE.md` Put the project instructions for coding agents in `AGENTS.md`. To use the same instructions in Claude Code, add `@AGENTS.md` to `CLAUDE.md`. ```markdown # Project Instructions for Coding Agents ## Checks Start the checks with `just ci` before you report that a change is complete. The command stops when a check fails. Use `just fmt` to check the format. Use `just fmt-fix` to change the format. ## Project requirements - Do not use `unwrap` or `expect` on external data. If the input is malformed, truncated, or empty, return a structured `Result` error or use a safe fallback. - Use Rust Edition 2024. The minimum supported Rust version (MSRV) is 1.96. CI checks the `rust-version` in `Cargo.toml` against the N-4 policy. To use an API from a newer Rust version, first increase the MSRV in its own pull request. - If you add a dependency, give the reason in the pull request. Add a `cargo vet` audit or an exemption with an expiration date. ## Code standards - `[lints.clippy]` enables the `all` and `pedantic` groups and specific restriction lints. CI uses `-D warnings`. - If a lint does not apply to an item, use `#[expect(clippy::..., reason = "...")]` on that item. Do not use `#[allow]` without a `reason` value. - Put unit tests in `mod tests` next to the code. Put integration tests in `tests/`. Add a regression test for each bug fix. ## Pull requests - Create a branch from `main`. Repository rulesets block direct pushes to `main`. - Use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) for commit messages and pull request titles. Examples include `feat:`, `fix:`, `docs:`, `chore:`, `ci:`, `refactor:`, and `test:`. - `release-plz` uses the commit messages and `cargo-semver-checks` to calculate the next version and generate the changelog. - Do not manually edit `version` in `Cargo.toml`. Do not manually edit `CHANGELOG.md`. `release-plz` updates the two files in a release pull request. ``` Example `CLAUDE.md` ```markdown @AGENTS.md ``` ## The `CONTRIBUTING.md` file Include this information in `CONTRIBUTING.md`. 1. Link to issues with the `good first issue` label. 2. Give the commands to install tools with `cargo-binstall`. 3. Give the purpose of each `just` recipe in a table. 4. Record the lint, test, panic, and dependency policies. 5. Give the pull request and release procedures. Include [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/), branch rulesets, and release pull requests from `release-plz`. 6. Record that contributors submit changes under `MIT OR Apache-2.0`. ### Tool installation with `cargo-binstall` Use [`cargo-binstall`](https://github.com/cargo-bins/cargo-binstall) to install prebuilt tools. With `cargo install`, Cargo compiles the tools from source. ```bash cargo install cargo-binstall --locked cargo binstall -y just cargo-nextest cargo-semver-checks cargo-audit cargo-msrv cargo-deny cargo-vet zizmor cargo-geiger # To compile from source, use the lockfile from each tool's package. cargo install --locked just cargo-nextest cargo-semver-checks cargo-audit cargo-msrv cargo-deny cargo-vet zizmor cargo-geiger # trivy: https://trivy.dev/latest/getting-started/installation/ ``` ## The `.gitignore` file Commit `Cargo.lock` for applications. For libraries, refer to [Lockfile management](dependencies.md#lockfile-management). ```gitignore # Files from Cargo debug target # rustfmt backups **/*.rs.bk # MSVC Windows debug symbols *.pdb # Compiler error dumps rustc-ice-*.txt # Mutation test and coverage files **/mutants.out*/ lcov.info # Local settings for coding agents and editors .claude/settings.local.json ``` ## Further reading - [just documentation](https://just.systems/man/en/) - [AGENTS.md specification](https://agents.md/) - [Claude Code documentation](https://code.claude.com/docs/en/overview) - [cargo-binstall](https://github.com/cargo-bins/cargo-binstall) - [Conventional Commits 1.0.0 specification](https://www.conventionalcommits.org/en/v1.0.0/) - [GitHub: Setting guidelines for repository contributors](https://docs.github.com/en/communities/setting-up-your-project-for-healthy-contributions/setting-guidelines-for-repository-contributors) --- # Security Policy Use `SECURITY.md` to give researchers a private channel for vulnerability reports. State the response times and supported versions. Give the procedure for coordinated disclosure with RustSec. ## The `SECURITY.md` file Put `SECURITY.md` in the repository root. GitHub shows this file in the **Security** tab. ### Reporting a vulnerability ```markdown # Security Policy ## Reporting a vulnerability Do not report vulnerabilities in public GitHub issues. Use one of these private channels. - Use [GitHub private vulnerability reporting](https://github.com/you/my-crate/security/advisories/new) when possible. GitHub keeps the severity assessment, private fork, CVE assignment, and advisory in one place. - Send an email to **security@example.com**. Use `my-crate security` as the subject. Include this information in the report. - The affected version or commit SHA - The target operating system and architecture - The necessary configuration or Cargo features - The security effects - The smallest example that shows the defect ``` ### Response expectations and regulatory timelines ```markdown ## Response times | Action | Target time | | ------ | ----------- | | Confirm receipt of the report | In 3 business days or less | | Do the initial severity assessment | In 7 business days or less | | Publish a fix or give a mitigation plan with dates | In 30 days or less. We give priority to active exploitation. | ``` Set response times that are possible for your maintainers. #### EU Cyber Resilience Act (CRA) Article 14 reporting obligations started on September 11, 2026. They apply to commercial manufacturers that put products with digital elements on the EU market. They cover actively exploited vulnerabilities and severe incidents. Use ENISA's Single Reporting Platform. The reporting period starts when you first know about the vulnerability or incident. Send an early warning as soon as possible. The maximum time is 24 hours from the start of the reporting period. If the early warning does not contain the necessary information, send a notification as soon as possible. The maximum time is 72 hours from the start of the reporting period. If the earlier reports do not contain the necessary information, send a final report. - For a vulnerability, send it in 14 days or less after a corrective or mitigating measure becomes available. - For an incident, send it in one month or less after you send the incident notification. For provisions on open-source projects and Open-Source Software Stewards, refer to the [EU Cyber Resilience Act](https://eur-lex.europa.eu/eli/reg/2024/2847/oj). These provisions give information about applicability, fines, and the December 11, 2027 start date. If the crate has commercial support or generates revenue, include the reporting deadlines in the response procedure. ### Supported versions ```markdown ## Supported versions | Version | Support status | | ------- | -------------- | | Latest minor release (`0.4.x` or `1.2.x`) | We support this release. | | Older releases | Install the latest release. | ``` Most open-source crates apply fixes to the latest release line only. If an agreement includes older releases, identify each branch in the policy. Give the end date for support of each branch. ### Coordinated disclosure and RustSec ```markdown ## Disclosure 1. Do a test of the fix in a private temporary GitHub fork. 2. Publish a release with the fix. 3. Publish a [GitHub Security Advisory](https://github.com/you/my-crate/security/advisories). 4. If applicable, request a CVE ID through GitHub. 5. If the vulnerability affects a crate on crates.io, submit a [RustSec advisory](https://github.com/rustsec/advisory-db). Include a link to the GitHub advisory. Give the affected versions and the versions that contain the fix. 6. If download of an affected version can cause serious harm, yank that version on crates.io. `cargo audit` and `cargo deny` read RustSec advisories. These tools can give alerts to developers during CI checks. We publish the name of a reporter only with explicit permission. ``` ### Scope notes ```markdown ## Scope notes This policy applies to these types of defects. - Memory unsafety or arbitrary code execution - Privilege escalation or a defect that lets a user bypass authentication or authorization - A path that gives access outside the permitted directory - Incorrect use of cryptography - A panic or denial of service from untrusted input in a library or server CI uses `cargo audit` and `cargo deny` to check transitive dependencies for public advisories. If the dependency has a new fix, open a public issue or pull request. ``` ## Enable GitHub private vulnerability reporting 1. Open the repository on GitHub. 2. Select **Settings**. 3. In the left sidebar under **Security and quality**, select **Advanced Security**. 4. Under **Private vulnerability reporting**, select **Enable**. 5. If you want a report form, add `.github/VULNERABILITY_REPORT.yml`. Include fields for the affected version, target triple, Cargo features, and an example of the defect. Organization owners can use Organization Security Configurations to enable private vulnerability reporting for all current and future public repositories. ## Further reading - [GitHub: Privately reporting a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability) - [RustSec Advisory Database](https://github.com/rustsec/advisory-db) - [EU Cyber Resilience Act (Regulation (EU) 2024/2847)](https://eur-lex.europa.eu/eli/reg/2024/2847/oj) --- # Project Governance Governance documents identify who makes decisions and who has access to project resources. They give the procedures for community standards and for changes to maintainer roles. ## Governance and continuity (`GOVERNANCE.md`) When the project has more than one maintainer or a downstream production user, add `GOVERNANCE.md`. Include this information. - Give the requirements for reviewers and maintainers. Give the procedure for a maintainer to move to emeritus status. - Select a decision procedure, for example consensus, a maintainer vote, or a decision by the project lead. Record architecture decisions in `docs/adr/`. - Set expert review requirements in `CODEOWNERS`. Include workflows, dependency policy, security policy, cryptography, authentication, and `unsafe` or FFI modules. Examples of paths are `.github/workflows/`, `deny.toml`, `supply-chain/`, and `SECURITY.md`. - Name the release and security roles. Use team accounts and role email addresses. Record an emergency access procedure with a time limit and a log of each use. - Give ownership of the organization to two or more persons. Use phishing-resistant multi-factor authentication (MFA) for owners. - Give crate ownership to a GitHub team with `cargo owner --add github:your-org:maintainers`. Use crates.io OIDC Trusted Publishing. With this method, the workflow does not use a maintainer's personal API token. Publish a support policy in `SUPPORT.md` or `README.md`. Give the supported release branches, minimum supported Rust version (MSRV) policy, Tier 1 platforms, help channels, and deprecation notice periods. ## Code of Conduct (`CODE_OF_CONDUCT.md`) Use the [Contributor Covenant](https://www.contributor-covenant.org) to set community standards and the response procedure. [Version 3.0](https://www.contributor-covenant.org/version/3/0/) gives instructions for corrective actions and a tool to generate the code of conduct. Projects also use version 2.1. Give a role email address for reports, for example `conduct@example.com`. Make sure that a person monitors this address. Identify who receives reports. Give a procedure for conflicts of interest. Apply the same standards to maintainers, sponsors, and new contributors. ## Licensing Rust projects commonly use `MIT OR Apache-2.0`. The MIT license is compatible with GPLv2. The Apache 2.0 license gives a patent grant and has a patent termination clause. Include the two license files in the repository root: ```text LICENSE-MIT # Full MIT license text LICENSE-APACHE # Full Apache License 2.0 text ``` Record the license terms for contributions in `CONTRIBUTING.md`. Refer to Section 5 of the Apache 2.0 license. > Unless you explicitly state otherwise, any contribution intentionally > submitted for inclusion in this project by you, as defined in the Apache-2.0 > license, shall be dual-licensed as above (`MIT OR Apache-2.0`), without any > additional terms or conditions. ## The `CONTRIBUTING.md` file Include this information in `CONTRIBUTING.md`. 1. Link to the code of conduct and `SECURITY.md`. Direct private reports to the process in `SECURITY.md`. 2. Give the installation commands for `rustup` and `cargo binstall`. 3. Give the purpose of the `just ci`, `just fmt-fix`, `just lint`, and `just test` recipes. 4. State the Rust edition, MSRV, lint policy, test requirements, dependency policy, and rules for panics. 5. Give the pull request and release processes. Include [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) and the release pull requests that `release-plz` creates. ### Example code standards ```markdown ## Code standards - Put unit tests in `mod tests` next to the code. Put integration tests in `tests/`. Add a regression test that fails without the bug fix. - Enable the `all`, `pedantic`, and applicable policy lints. Set `-D warnings`. If a lint does not apply to an item, add `#[expect(clippy::..., reason = "...")]`. Do not use `#[allow]` without a reason. - For a new crate, give the reason in the pull request description. Include the `cargo vet` audit or an exemption with a time limit. - Do not panic on untrusted input. Return a structured error or use a safe fallback when the input is incorrect. ``` ### Example pull request procedure ```markdown ## Pull requests 1. Create a branch from `main`. Repository rulesets block direct pushes to `main`. 2. Use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) in the pull request title. Examples are `feat:`, `fix:`, `docs:`, `chore:`, `ci:`, `refactor:`, and `test:`. CI checks the title. The squash merge uses the title as the commit message. 3. Before you request review, start the checks with `just ci`. 4. Do not manually edit `version` in `Cargo.toml`. Do not manually edit `CHANGELOG.md`. `release-plz` updates both in a release pull request. ``` ## Branch and tag protection with GitHub Rulesets Use GitHub **Repository or Organization Rulesets**. These rulesets apply to branches and release tags. You can export the rules as JSON. You can also apply organization rulesets to more than one repository. Apply the rules to `main`, active release branches, and `v*` release tags. For `v*` tags, limit creation, updates, and deletion to the release GitHub App. For protected branches, enable these options. - **Require a pull request before merging** - **Require review from Code Owners** for applicable paths - **Dismiss stale pull request approvals when new commits are pushed** - **Require approval of the most recent reviewable push** - **Require status checks to pass** - **Require conversation resolution** - **Require linear history** - **Block force pushes** Set the minimum number of independent approvals to one. Make the `test`, `lint & doc`, `semver`, `msrv`, `security`, `vet`, and `pr-title` checks mandatory. Refer to [Release automation](releases.md#enforcing-the-convention) for `pr-title`. Enable **Require branches to be up to date**. If you use a GitHub merge queue, enable **Only merge non-failing pull requests**. If the release GitHub App can make signed commits, enable **Require signed commits**. GitHub can add a web-flow signature to commits from its GraphQL or REST API. ## Further reading - [Contributor Covenant v3.0](https://www.contributor-covenant.org/version/3/0/) - [The Cargo Book: `cargo owner` (GitHub team ownership)](https://doc.rust-lang.org/cargo/commands/cargo-owner.html) - [Conventional Commits 1.0.0 specification](https://www.conventionalcommits.org/en/v1.0.0/) - [GitHub Rulesets documentation](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/about-rulesets) - [Rust API Guidelines: Licensing & Metadata](https://rust-lang.github.io/api-guidelines/necessities.html) --- # CLI and TUI Applications Command-line interface (CLI) and terminal user interface (TUI) programs give users fast, scriptable tools that operate in a terminal. Configure argument parsing, output streams, terminal state recovery, tests, and release packages before you publish a binary. ## Crate stack Select pure-Rust crates that operate on Linux, macOS, and Windows. | Purpose | Crate | Notes | |---------|-------|-------| | Argument parser | [`clap`](https://docs.rs/clap) | Use the `derive` feature for typed flags and subcommands. | | Shell completions | [`clap_complete`](https://docs.rs/clap_complete) | Generate completion scripts for Bash, Zsh, Fish, and PowerShell. | | Manual pages | [`clap_mangen`](https://docs.rs/clap_mangen) | Generate `man` pages from the `clap` command definition. | | TUI layout | [`ratatui`](https://docs.rs/ratatui) | Render terminal widgets with an immediate-mode frame loop. | | Terminal backend | [`crossterm`](https://docs.rs/crossterm) | Control raw mode, the alternate screen, and keyboard events across operating systems. | | Diagnostics | [`miette`](https://docs.rs/miette) or [`thiserror`](https://docs.rs/thiserror) | Use `thiserror` for library errors and `miette` for rich user diagnostics. | | ANSI styles | [`anstyle`](https://docs.rs/anstyle) | Add terminal colors without a heavy dependency tree. | Keep the core logic in `src/lib.rs` and keep only the entry point in `src/main.rs`. Refer to [Binary and library targets](scaffolding.md#binary-and-library-targets). ## Argument parsing and configuration Define arguments with `clap` derive macros. Enable the `env` feature so users can set options with environment variables. ```rust use clap::Parser; use std::path::PathBuf; #[derive(Debug, Parser)] #[command(version, about = "Inspect project manifests")] pub struct Cli { /// Path to the configuration file. #[arg(short, long, env = "MY_TOOL_CONFIG")] pub config: Option, /// Write output as JSON. #[arg(long)] pub json: bool, } ``` Use this order of priority for configuration values. 1. Command-line flags 2. Environment variables 3. Configuration file 4. Default values Refer to [Configuration priority](testing.md#configuration-priority) for tests of each pair of sources. ## Output streams, colors, and exit codes Follow the [Command Line Interface Guidelines](https://clig.dev/) so scripts and human users can both use the tool reliably. - Write primary data to `stdout`. Write diagnostics, progress messages, and errors to `stderr`. - Add a `--json` flag or structured output mode when scripts consume the output. - Respect the [`NO_COLOR`](https://no-color.org/) environment variable. Disable ANSI color codes when `NO_COLOR` is set and not empty, or when `stdout` is not a terminal (`std::io::IsTerminal`). - Return standard exit codes: `0` for success, `1` for runtime errors, and `2` for command-line usage errors. - Do not panic on malformed files, invalid UTF-8, or broken pipes. Return a clear error message and a non-zero exit code. ## TUI architecture and terminal recovery Separate application state from rendering in a TUI. Use a Model-View-Update structure: - **Model**: A struct holds the application state, selection indices, and data buffers. - **View**: A pure function draws widgets onto a `ratatui::Frame` from the model. - **Update**: An event loop reads `crossterm::event::Event` values and updates the model. If a TUI stops or panics while raw mode is active, the user terminal can stay in an unusable state. Always restore the terminal on normal exit and on panic. `ratatui::run` initializes the terminal, installs a panic hook that restores the terminal, and cleans up on exit. ```rust use ratatui::DefaultTerminal; use std::io; fn main() -> io::Result<()> { ratatui::run(app) } fn app(terminal: &mut DefaultTerminal) -> io::Result<()> { loop { terminal.draw(|frame| { // Render widgets here. })?; // Read events with crossterm::event::poll and break on quit. break; } Ok(()) } ``` If the TUI reads network data or large files, move that work to a background thread or a `tokio` task. Send updates to the render loop through a bounded channel so the interface stays responsive. ## Security considerations - Do not pass secrets such as API tokens as command-line arguments. Other local users can inspect command-line arguments in the process table. Read secrets from environment variables, files with restricted permissions, or `stdin`. - Validate file paths before you write or extract archives to prevent path traversal. - Do not pass untrusted input to a shell command. Use `std::process::Command` with explicit argument arrays. Refer to [Secure development lifecycle](secure-development.md) for threat models and input validation rules. ## Testing CLI and TUI code - Use [`assert_cmd`](https://docs.rs/assert_cmd) or `env!("CARGO_BIN_EXE_")` in `tests/` to check flags, exit codes, `stdout`, and `stderr`. Refer to [Integration and CLI tests](testing.md#integration-and-cli-tests). - Use [`insta`](https://insta.rs/) to save snapshots of help text, JSON output, and rendered terminal frames. - Use [`ratatui::backend::TestBackend`](https://docs.rs/ratatui/latest/ratatui/backend/struct.TestBackend.html) to render TUI screens into an in-memory buffer during unit tests. Assert on the buffer text without a real terminal. ```rust #[cfg(test)] mod tests { use ratatui::{backend::TestBackend, Terminal}; #[test] fn renders_title_bar() { let backend = TestBackend::new(40, 10); let mut terminal = Terminal::new(backend).expect("create test terminal"); terminal .draw(|frame| { frame.render_widget(ratatui::widgets::Paragraph::new("Status: OK"), frame.area()); }) .expect("draw frame"); let buffer = terminal.backend().buffer(); let line: String = (0..10).map(|x| buffer[(x, 0)].symbol()).collect(); assert_eq!(line, "Status: OK"); } } ``` ## Packaging and distribution - Build precompiled archives for `x86_64` and `aarch64` targets on Linux, macOS, and Windows. Tools such as [`cargo-dist`](https://opensource.axo.dev/cargo-dist/) generate GitHub Actions workflows, shell installers, PowerShell installers, and Homebrew formulas. - Include generated shell completions and `man` pages in each release archive. - Publish SHA-256 checksums, build provenance attestations, and a software bill of materials (SBOM) with each release. Refer to [Release automation](releases.md). - Configure `[package.metadata.binstall]` if users install the binary with [`cargo-binstall`](https://github.com/cargo-bins/cargo-binstall). ## Further reading - [Command Line Interface Guidelines](https://clig.dev/) - [Rust CLI Working Group Book](https://rust-cli.github.io/book/) - [NO_COLOR standard](https://no-color.org/) - [clap documentation](https://docs.rs/clap) - [Ratatui documentation](https://ratatui.rs/) - [cargo-dist documentation](https://opensource.axo.dev/cargo-dist/) --- # Desktop GUI Applications Desktop graphical user interface (GUI) applications in Rust use either a system webview or a native GPU renderer. Select a framework that matches your platform targets, licensing terms, and accessibility requirements. ## Framework selection Compare the main production frameworks before you create the repository. | Framework | Architecture | Best fit | Notes | |-----------|--------------|----------|-------| | [Tauri v2](https://v2.tauri.app/) | Rust backend with system webview frontend | Consumer desktop and mobile applications | Small binaries, web UI ecosystem, strict IPC permissions. | | [Iced](https://iced.rs/) | Pure-Rust retained mode (Elm architecture) on `wgpu` | Native cross-platform desktop applications | Type-safe message loop. Powers System76 COSMIC. | | [egui](https://www.egui.rs/) (`eframe`) | Pure-Rust immediate mode on `wgpu` or `glow` | Developer tools, debuggers, and internal dashboards | Fast to write. Limited custom layout and accessibility. | | [Slint](https://slint.dev/) | Declarative `.slint` UI language compiled to Rust | Commercial desktop and embedded interfaces | Clear split between UI and logic. Dual GPLv3 and commercial license. | | [GPUI](https://www.gpui.rs/) | Pure-Rust GPU-accelerated retained and immediate hybrid | High-frame-rate editors and power-user tools | Built for Zed. Smaller general widget ecosystem. | Check the license of each framework and its transitive dependencies with `cargo-deny`. Refer to [Supply chain security](supply-chain.md). ## Architecture and thread safety Never block the UI thread with disk I/O, network requests, or heavy computation. A blocked UI thread freezes window redraws and causes the operating system to mark the application as unresponsive. - Keep domain state and business logic in a separate library crate that does not depend on GUI types. - Start background tasks on a `tokio` runtime or worker thread pool. - Send results back to the UI thread through typed messages, commands, or async channels. - Store user configuration and data in operating system standard directories with [`directories`](https://docs.rs/directories) instead of hardcoded paths. ## Security controls Desktop applications operate with the privileges of the local user. Apply least privilege to every boundary. ### Tauri v2 capabilities and CSP In Tauri v2, define granular capability files in `src-tauri/capabilities/`. Grant each window only the commands and plugin permissions that it needs. ```json { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", "description": "Permissions for the main window", "windows": ["main"], "permissions": [ "core:default" ] } ``` Set a strict Content Security Policy (CSP) in `tauri.conf.json` to block cross-site scripting (XSS) in the webview. Do not expose arbitrary filesystem or shell commands to the frontend. Validate every IPC command argument in Rust. ### Secrets and updates - Store tokens and credentials in the operating system keychain, not in plain-text configuration files. - Sign auto-update packages with an offline signing key and check signatures before installation. In Tauri v2, use `tauri-plugin-updater` with a pinned public key. - Use pure-Rust TLS (`rustls`) configured with a platform certificate verifier (such as `rustls-platform-verifier`) or an explicit enterprise CA bundle, or use OS-native TLS stores. `rustls` with bundled public roots alone does not trust enterprise proxy CAs installed only in the operating system store. ## Accessibility Support keyboard navigation, high-contrast themes, and screen readers from the start of the project. - Webview frameworks such as Tauri inherit browser accessibility trees when the frontend uses semantic HTML and ARIA attributes. - Native Rust toolkits such as `egui`, `Slint`, and custom `winit` applications integrate with [AccessKit](https://accesskit.dev/). AccessKit maps Rust UI trees to UI Automation on Windows, NSAccessibility on macOS, and AT-SPI on Linux. - Test keyboard focus order and screen reader announcements on each target operating system. ## Testing GUI applications Split tests into fast headless tests and focused UI tests. 1. Do tests of all business logic, state transitions, and persistence in the core library crate with `cargo nextest run --locked`. Refer to [Testing strategy](testing.md). 2. For Elm-architecture frameworks such as Iced, write unit tests that send `Message` values to the `update` function and assert on the new state. 3. For Tauri applications, check IPC commands with `tauri::test::mock_app` and check the frontend with Playwright or WebDriver. 4. Start platform builds in CI on Linux, macOS, and Windows runners to detect platform-specific linker or system-library errors early. Refer to [CI/CD pipeline](ci-cd.md). ## Packaging, code signing, and notarization Operating systems warn users or block unsigned desktop binaries. Automate packaging and signing in your release workflow. | Platform | Package formats | Signing requirement | |----------|-----------------|---------------------| | macOS | `.app`, `.dmg` | Sign with a Developer ID Application certificate (`codesign`) and notarize with Apple (`notarytool`). | | Windows | `.msi`, NSIS `.exe` | Sign with an Authenticode code-signing certificate (EV or cloud HSM such as Azure Trusted Signing). | | Linux | `.deb`, `.rpm`, AppImage, Flatpak | Sign package repositories or publish GPG signatures and SHA-256 checksums. | Store signing certificates and Apple API keys in protected CI secrets with environment approval gates. Publish checksums, SBOMs, and provenance attestations for every installer. Refer to [Release automation](releases.md). ## Further reading - [Tauri v2 documentation](https://v2.tauri.app/) - [Tauri v2 security guide](https://v2.tauri.app/security/) - [Iced documentation](https://iced.rs/) - [egui documentation](https://www.egui.rs/) - [Slint documentation](https://slint.dev/) - [AccessKit documentation](https://accesskit.dev/) - [Apple: Notarizing macOS Software Before Distribution](https://developer.apple.com/documentation/security/notarizing-macos-software-before-distribution) --- # Web UI (WebAssembly) Applications Rust compiles to WebAssembly (WASM) so you can build browser user interfaces with type safety and shared domain crates. Configure the framework, build toolchain, binary size limits, Content Security Policy (CSP), and browser tests before deployment. ## Framework selection Select a framework that matches your reactivity model, server-side rendering (SSR) needs, and target platforms. | Framework | Model | Build tool | Best fit | |-----------|-------|------------|----------| | [Leptos](https://leptos.dev/) | Fine-grained reactive signals without a Virtual DOM | `cargo-leptos` or `trunk` | High-performance web applications, SSR with hydration, and full-stack Rust | | [Dioxus](https://dioxuslabs.com/) | Virtual DOM with `rsx!` components | `dx` (Dioxus CLI) | Multi-platform products that share UI code across web, desktop, and mobile | | [Yew](https://yew.rs/) | Component and hook model | `trunk` | Mature single-page applications (SPAs) with stable APIs | Put shared request types, response types, and validation rules in a separate workspace crate. Compile that crate for both the browser (`wasm32-unknown-unknown`) and the [web API](web-api.md) server so client and server models stay consistent. ## Toolchain and build pipeline Add the WebAssembly compilation target to your toolchain and to [`rust-toolchain.toml`](scaffolding.md#toolchain-pinning-rust-toolchaintoml). ```toml # rust-toolchain.toml [toolchain] channel = "1.100.0" components = ["rustfmt", "clippy"] targets = ["wasm32-unknown-unknown"] ``` Use these standard tools to compile and package the frontend: - [`wasm-bindgen`](https://rustwasm.github.io/wasm-bindgen/): Generates the JavaScript glue code and bindings to Web APIs (`web-sys`, `js-sys`). Pin the `wasm-bindgen-cli` version in CI to match the `wasm-bindgen` crate version in `Cargo.lock`. - [`Trunk`](https://trunkrs.dev/): Builds, bundles, hashes, and serves client-side WASM applications from an `index.html` entry point. - [`wasm-pack`](https://rustwasm.github.io/wasm-pack/): Compiles Rust crates into reusable npm packages for JavaScript or TypeScript projects. - [`cargo-leptos`](https://github.com/leptos-rs/cargo-leptos): Compiles both the server binary and the client WASM bundle for full-stack Leptos applications. ## Binary size and performance optimization Large `.wasm` bundles slow page load times. Configure a dedicated release profile in `Cargo.toml` for WASM artifacts. ```toml [profile.wasm-release] inherits = "release" opt-level = "z" lto = true codegen-units = 1 panic = "abort" strip = true ``` Select the custom profile explicitly in your build tool so Cargo applies these settings instead of the default `release` profile: - **`cargo-leptos`**: Set `lib-profile-release = "wasm-release"` in `[package.metadata.leptos]` (single-package project) or in `[[workspace.metadata.leptos]]` (multi-package workspace with separate frontend and server crates). - **Cargo**: Pass `--profile wasm-release`. - **`Trunk`**: Pass `trunk build --cargo-profile wasm-release`, or set `data-cargo-profile="wasm-release"` on the `rust` `` in `index.html`. Apply these additional size controls: - Post-process release `.wasm` files with `wasm-opt` from Binaryen (`-Oz` for smallest size or `-O3` for speed). `Trunk` and `wasm-pack` can invoke `wasm-opt` automatically. - Keep `console_error_panic_hook` for readable browser panic messages during development. Avoid large formatting dependencies where size is critical. - Serve `.wasm` assets with the `Content-Type: application/wasm` header so browsers can use `WebAssembly.instantiateStreaming`. - Compress static `.wasm`, `.js`, and `.css` files with Brotli or gzip on the web server or content delivery network (CDN). ## Security controls Browser code operates in an untrusted environment. Apply browser security headers and keep all secrets on the server. ### Content Security Policy (CSP) Modern browsers support `'wasm-unsafe-eval'` in the `script-src` directive. This directive permits WebAssembly compilation without permitting JavaScript `eval()`. ```http Content-Security-Policy: default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; ``` - Do not use `'unsafe-eval'` in `script-src` when `'wasm-unsafe-eval'` satisfies your browser support policy. - Do not embed API secrets, private keys, or privileged tokens in a WASM binary. Any user can inspect or disassemble downloaded `.wasm` bytes. - Treat raw HTML injection APIs (such as `inner_html`) as high-risk sinks. Sanitize untrusted HTML on the server before rendering. - Use Subresource Integrity (SRI) hashes when you load third-party scripts or stylesheets. ## Testing WebAssembly code Combine native Rust tests with headless browser tests. 1. Keep pure state logic, reducers, and validators independent of `web-sys`. Check them on the host target with `cargo nextest run --locked`. Refer to [Testing strategy](testing.md). 2. Write browser-specific tests with [`wasm-bindgen-test`](https://rustwasm.github.io/wasm-bindgen/wasm-bindgen-test/index.html) for DOM manipulation, storage APIs, and `fetch` wrappers. 3. Start browser tests in CI with a headless browser driver: ```bash wasm-pack test --headless --chrome ``` 4. Add end-to-end tests with Playwright against the production bundle served with the real CSP headers. Make sure that the page loads without console errors or CSP violations. ## Deployment and caching - Include content hashes in `.wasm`, `.js`, and `.css` filenames. `Trunk` enables file hashing by default. `cargo-leptos` defaults `hash-files` to `false`; set `hash-files = true` in `[package.metadata.leptos]` (or `[[workspace.metadata.leptos]]` for multi-package workspaces), enable `LEPTOS_HASH_FILES=true` / `hash_files` at runtime, and deploy the generated `hash.txt` alongside the server executable (or configure its runtime path) before you apply an immutable cache policy. - Set `Cache-Control: public, max-age=31536000, immutable` on hashed asset files. - Set `Cache-Control: no-cache` on `index.html` so browsers get new asset hashes after a release. - Track `.wasm` bundle size in CI so unexpected dependency growth fails review. ## Further reading - [Rust and WebAssembly Book](https://rustwasm.github.io/docs/book/) - [The `wasm-bindgen` Guide](https://rustwasm.github.io/wasm-bindgen/) - [MDN: CSP `script-src` (`'wasm-unsafe-eval'`)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) - [Leptos Book](https://book.leptos.dev/) - [Dioxus documentation](https://dioxuslabs.com/learn/) - [Yew documentation](https://yew.rs/docs/getting-started/introduction) - [Trunk documentation](https://trunkrs.dev/) --- # Web API Services Production Rust web APIs combine compile-time type safety with predictable latency and low memory use. Configure the HTTP framework, middleware limits, structured errors, database queries, telemetry, graceful shutdown, and container builds before deployment. ## Crate stack Select crates that integrate cleanly with the `tokio` async runtime and pure-Rust TLS (`rustls`). | Purpose | Crate | Notes | |---------|-------|-------| | HTTP framework | [`axum`](https://docs.rs/axum) | Default choice. Macro-free extractors and native `tower` middleware support. | | High-throughput alternative | [`actix-web`](https://docs.rs/actix-web) | Thread-per-core runtime for specialized low-tail-latency workloads. | | Middleware | [`tower`](https://docs.rs/tower) and [`tower-http`](https://docs.rs/tower-http) | Timeouts, body size limits, CORS, compression, and HTTP trace layers. | | Database access | [`sqlx`](https://docs.rs/sqlx) | Async SQL with compile-time query checks and embedded migrations. | | Telemetry | [`tracing`](https://docs.rs/tracing) and [`tracing-subscriber`](https://docs.rs/tracing-subscriber) | Structured JSON logs and span-aware async diagnostics. | | OpenAPI specification | [`utoipa`](https://docs.rs/utoipa) | Derive OpenAPI schemas from Rust request and response structs. | | Outbound HTTP client | [`reqwest`](https://docs.rs/reqwest) | Use `default-features = false` with `rustls` (on `0.13+`, plus `ClientBuilder::tls_backend_rustls()` if another dependency can enable `native-tls`) or `rustls-tls` (on `0.12`, plus `use_rustls_tls()`), and share one `Client` across handlers. | ## Application structure and shared state Separate the service into clear layers so you can check domain logic without an HTTP server. - `routes` or `handlers`: Parse HTTP requests, validate inputs, and map domain results to HTTP responses. - `domain` or `services`: Implement business rules with no dependency on HTTP types. - `repositories`: Send database queries and external service calls. Bundle shared resources such as the database pool and `reqwest::Client` in an `AppState` struct. Pass `AppState` through the framework state extractor instead of global variables. ## Middleware, limits, and graceful shutdown Limit response creation time after headers are read, limit body size, and drain in-flight requests during deployments. `TimeoutLayer` bounds only the service response future after Hyper parses request headers—it does not protect against clients that send incomplete request headers or bound a streaming response body after headers are returned. Enforce header read timeouts at a reverse proxy. ```rust use axum::{routing::get, Router}; use std::net::SocketAddr; use std::time::Duration; use tokio::signal; use tower::ServiceBuilder; use tower_http::{ compression::CompressionLayer, limit::RequestBodyLimitLayer, timeout::TimeoutLayer, trace::TraceLayer, }; async fn health() -> &'static str { "ok" } async fn shutdown_signal() { let ctrl_c = async { let _ = signal::ctrl_c().await; }; #[cfg(unix)] let terminate = async { if let Ok(mut sig) = signal::unix::signal(signal::unix::SignalKind::terminate()) { sig.recv().await; } }; #[cfg(not(unix))] let terminate = std::future::pending::<()>(); tokio::select! { _ = ctrl_c => {}, _ = terminate => {}, } } pub async fn serve(addr: SocketAddr) -> std::io::Result<()> { let middleware = ServiceBuilder::new() .layer(TraceLayer::new_for_http()) .layer(CompressionLayer::new()) .layer(TimeoutLayer::new(Duration::from_secs(30))) .layer(RequestBodyLimitLayer::new(2 * 1024 * 1024)); let app = Router::new() .route("/healthz", get(health)) .layer(middleware); let listener = tokio::net::TcpListener::bind(addr).await?; axum::serve(listener, app) .with_graceful_shutdown(shutdown_signal()) .await } ``` Add explicit liveness (`/healthz`) and readiness (`/readyz`) endpoints. Make the readiness endpoint check database connectivity with a short timeout. ## Structured errors (RFC 9457) Do not call `unwrap` or `expect` in request handlers. Return a centralized error enum that maps domain errors to [RFC 9457](https://datatracker.ietf.org/doc/html/rfc9457) Problem Details (`application/problem+json`). - Include `type`, `title`, `status`, and `detail` fields in client error responses. - Record internal stack traces, SQL errors, and upstream failures in structured logs only. Never expose internal error strings to external callers. ## Database queries and offline CI builds Use `sqlx::query!` and `sqlx::query_as!` to check SQL syntax and column types at compile time. 1. Set explicit `max_connections`, `acquire_timeout`, and `idle_timeout` values on the connection pool. 2. Start `cargo sqlx prepare --workspace -- --all-targets` against a local database and commit the `.sqlx/` metadata directory. 3. Set `SQLX_OFFLINE=true` in CI and container builds so Cargo compiles without a live database connection. 4. Keep database migrations in `migrations/` and apply them in a controlled deployment step or startup hook. ## Observability and security controls - Write structured JSON logs with `tracing-subscriber` in production. Configure log levels with `RUST_LOG`. - Propagate W3C Trace Context (`traceparent`) headers across incoming requests and outbound `reqwest` calls with `tracing-opentelemetry`. - Validate authentication tokens, authorization scopes, and request schemas on every protected route. - Configure strict CORS origins in `tower_http::cors::CorsLayer`. Do not allow wildcard origins with credentials. - Apply rate limits to authentication and write endpoints at the reverse proxy or middleware layer. - Redact secrets, authorization headers, and personal data from logs and traces. Refer to [Secure development lifecycle](secure-development.md) for threat models and security verification. ## Testing web APIs Test HTTP routers directly in memory without opening a network socket. - Call `axum::Router` directly in integration tests with `tower::ServiceExt::oneshot`. - Use ephemeral databases in CI (for example, test containers or per-test schemas) to check migrations and SQL queries. - Add tests for unauthorized access, malformed JSON, oversized request bodies, and invalid query parameters. Make sure that each test returns the expected HTTP status code without a panic. Refer to [Never panic on untrusted input](testing.md#never-panic-on-untrusted-input). - Generate and check the OpenAPI document in CI so API documentation stays in sync with route handlers. ## Container packaging and deployment Use multi-stage container builds with [`cargo-chef`](https://github.com/LukeMathWalker/cargo-chef) to cache dependency compilation separately from application source changes. - Copy only the compiled binary into a minimal runtime image such as Distroless or `debian:bookworm-slim` with `ca-certificates`. - Operate the container as a non-root user with a read-only root filesystem. - Pin base images by SHA-256 digest in the `Dockerfile`. - Scan container images with Trivy and publish a container SBOM and provenance attestation. Refer to [Security scanning](security-scanning.md) and [Release automation](releases.md). ## Further reading - [Axum documentation](https://docs.rs/axum) - [Tower and tower-http documentation](https://docs.rs/tower-http) - [SQLx documentation](https://docs.rs/sqlx) - [Tracing documentation](https://docs.rs/tracing) - [RFC 9457: Problem Details for HTTP APIs](https://datatracker.ietf.org/doc/html/rfc9457) - [W3C Trace Context specification](https://www.w3.org/TR/trace-context/) - [OWASP API Security Top 10](https://owasp.org/API-Security/) - [cargo-chef repository](https://github.com/LukeMathWalker/cargo-chef) --- # Embedded Applications Embedded Rust firmware operates on resource-constrained microcontrollers without a host operating system. Select the hardware abstraction layer (HAL), concurrency model, memory safeguards, hardware security controls, and test strategy before you ship firmware to devices. ## Hardware families and HAL selection Target [`embedded-hal`](https://docs.rs/embedded-hal) version 1.0 or later so sensor and bus drivers stay portable across microcontrollers. | Target family | Primary HAL | Toolchain notes | Best fit | |---------------|-------------|-----------------|----------| | ESP32 (RISC-V and Xtensa) | [`esp-hal`](https://docs.rs/esp-hal) (`no_std`) | RISC-V uses standard `rustup` targets. Xtensa uses `espup`. | Bare-metal firmware, low power, and Embassy async workloads | | ESP32 (`std` on ESP-IDF) | [`esp-idf-svc`](https://docs.rs/esp-idf-svc) | Builds on Espressif ESP-IDF and FreeRTOS | Projects that need full ESP-IDF Wi-Fi, Bluetooth, or OTA stacks | | Arduino and 8-bit AVR | [`avr-hal`](https://github.com/Rahix/avr-hal) (`no_std`) | Requires `avr-gcc` and `ravedude` for flashing | Legacy 8-bit boards such as Arduino Uno and Mega with small RAM | | ARM Cortex-M (STM32, nRF, RP2040, RP2350) | `embassy-stm32`, `embassy-nrf`, `embassy-rp`, or vendor HALs | Standard `thumbv6m` / `thumbv7em` / `thumbv8m` targets via `rustup` | Industrial controllers, wearables, and connected sensors | ## Concurrency and runtime selection Select the concurrency model that matches your hardware limits and timing requirements. - **[Embassy](https://embassy.dev/)**: Use `embassy-executor` for async/await cooperative multitasking on 32-bit microcontrollers. It fits connected devices that manage networking, USB, timers, and sensors without a traditional RTOS. - **[RTIC](https://rtic.rs/)**: Use Real-Time Interrupt-driven Concurrency for hard real-time systems with strict deadlines. RTIC maps tasks directly to hardware interrupt priorities and checks resource locks at compile time. - **Synchronous loops**: On 8-bit AVR boards with a few kilobytes of RAM, use blocking `embedded-hal` traits and small interrupt handlers. Avoid async executors on 8-bit targets. Decouple slow peripheral transfers (such as I2C or SPI display writes) from fast input polling. Use a one-frame mailbox or signal from `embassy-sync` so a slow bus transfer does not stall input sampling. ## Toolchain, flashing, and diagnostics Pin the compiler channel and cross-compilation targets in [`rust-toolchain.toml`](scaffolding.md#toolchain-pinning-rust-toolchaintoml). ```toml # rust-toolchain.toml [toolchain] channel = "1.100.0" components = ["rustfmt", "clippy"] targets = ["thumbv7em-none-eabihf", "riscv32imc-unknown-none-elf"] ``` Configure the default target and flash runner in `.cargo/config.toml`. ```toml # .cargo/config.toml [build] target = "thumbv7em-none-eabihf" [target.thumbv7em-none-eabihf] runner = "probe-rs run --chip STM32F411RETx" ``` Use these standard diagnostic tools: - **[`probe-rs`](https://probe.rs/)**: Flash firmware, stream logs, and debug over SWD or JTAG on ARM Cortex-M and RISC-V targets. - **[`espflash`](https://github.com/esp-rs/espflash)**: Flash and monitor ESP32 devices over serial or USB-JTAG. - **[`defmt`](https://defmt.ferrous-systems.com/)**: Send compact binary log indices from the microcontroller and format strings on the host. This saves flash memory and CPU cycles compared to `core::fmt`. ### Flash layouts and release profiles - Commit custom flash partition tables (for example, `partitions.csv` on ESP32) and pass `--partition-table partitions.csv` to `espflash`. Keep application data and hidden device settings in separate partitions. - Set `opt-level = "s"` or `opt-level = "z"` in `[profile.release]` to reduce flash usage. Override `opt-level = 3` for timing-critical radio or cryptography crates that require high speed. ```toml [profile.release] opt-level = "s" # Radio stacks can require -O2 or higher for real-time timing. [profile.release.package.esp-radio] opt-level = 3 ``` - Document pin assignments by module label, voltage levels (for example, 3.3 V or 5 V), pull resistors, I2C addresses, and minimum flash or PSRAM sizes in `WIRING.md` or `README.md`. ## Memory safety and `no_std` controls Bare-metal firmware has no virtual memory manager. Prevent memory exhaustion and silent corruption at compile time and link time. - **Avoid dynamic allocation**: Keep firmware in `#![no_std]` without `alloc` where possible. Use fixed-capacity collections from [`heapless`](https://docs.rs/heapless) so memory use stays bounded and predictable. - **Detect stack overflows**: On ARM Cortex-M targets, use [`flip-link`](https://github.com/knurling-rs/flip-link) as the linker wrapper. `flip-link` puts the stack at the start of RAM so a stack overflow triggers a hardware fault instead of silent corruption of static variables. - **Select a production panic handler**: Use `panic-probe` during development so `probe-rs` prints a backtrace. In production firmware, use a handler that records fault metadata and resets the device (or triggers a hardware watchdog) into a safe state. - **Isolate `unsafe` register access**: Prefer HAL drivers over direct peripheral access crate (PAC) calls. Keep unavoidable `unsafe` blocks in small reviewed modules with `// SAFETY:` comments. Refer to [Restrict `unsafe` code](scaffolding.md#restrict-unsafe-code). ## Security and firmware updates Connected microcontrollers are exposed to both network and physical attackers. - **Enable hardware protections**: Configure Secure Boot and Flash Encryption before manufacturing so devices reject unsigned firmware and protect stored keys. - **Sign over-the-air (OTA) updates**: Sign every firmware image with an offline key. Check the cryptographic signature on the device before activation, and keep an A/B partition scheme for automatic rollback if boot fails. - **Disable debug ports in production**: Lock JTAG and SWD read-out protection on production units so an attacker cannot dump firmware or credentials from flash memory. - **Use hardware entropy**: Seed cryptographic operations and TLS sessions from the microcontroller hardware random number generator (TRNG). Refer to [Secure development lifecycle](secure-development.md) for threat models and security controls. ## Testing and simulation Separate hardware-independent logic from board-specific initialization so most tests operate on standard CI runners. Refer to [Testing strategy](testing.md). ### Host tests in an embedded workspace When the root `.cargo/config.toml` sets an embedded build target, `cargo test` targets the microcontroller by default. Use these patterns to check `no_std` logic on the host: 1. Put protocol parsers, state machines, and `embedded-hal` device drivers in separate workspace crates under `crates/`. Start host tests with an explicit host target and exclude the firmware package: ```bash cargo nextest run --locked --workspace --exclude my-firmware --target x86_64-unknown-linux-gnu ``` 2. For host-only integration tests (such as filesystem or storage image tests), create a separate Cargo package with its own `.cargo/config.toml` that sets the host target. Because Cargo ignores a member package's `.cargo/config.toml` when invoked from the workspace root, start those tests from that package's directory (`cargo nextest run --locked`) or select the package explicitly with an explicit host target from the workspace root (`cargo nextest run --locked -p --target x86_64-unknown-linux-gnu`). 3. Use [`embedded-hal-mock`](https://docs.rs/embedded-hal-mock) to simulate I2C, SPI, and GPIO transactions without physical boards. ### Hardware and desktop simulation Combine firmware simulation with host desktop simulators to detect regressions before you flash hardware. - **Wokwi CI simulation**: Define the board circuit in `diagram.json` and `wokwi.toml`. Use [`wokwi-cli`](https://docs.wokwi.com/wokwi-ci/cli-installation) with YAML test scenarios (`wait-serial` and `set-control`) to automate smoke checks in CI. Use a Cargo feature flag (for example, `--no-default-features --features sim`) for peripherals that the simulator cannot emulate. - **Desktop simulator**: Compile the same `no_std` UI and application crates into a host desktop window (for example, with Tauri or `eframe`) that replaces only display, input, storage, and radio drivers. Optional localhost-only control endpoints let automated scripts or coding agents send inputs and capture screen frames. - **Final hardware check**: Simulators do not model real ADC noise, display electrical timing, or brownout behavior. Always check initialization, timing, and thresholds on physical hardware before a release. ### Target builds and hardware-in-the-loop (HIL) - Add a CI job that compiles the firmware crate for every embedded target with `cargo build --release --locked` and tracks flash and RAM usage. - For hardware-in-the-loop (HIL) checks, use [`defmt-test`](https://github.com/knurling-rs/defmt-test) with `probe-rs` to start unit tests directly on target silicon. ## Release artifacts and compliance - Build firmware with `--locked` and record the exact compiler version, target triple, and linker script for each release. - Publish the `.elf` symbols (for internal crash analysis), flashable `.bin` or `.hex` images, SHA-256 checksums, and a software bill of materials (SBOM). Refer to [Release automation](releases.md). - For safety-critical industrial, automotive, or medical products (for example, IEC 61508 or ISO 26262), evaluate a qualified Rust compiler toolchain such as [Ferrocene](https://ferrocene.dev/). ## Further reading - [The Embedded Rust Book](https://docs.rust-embedded.org/book/) - [The Rust on ESP Book](https://docs.espressif.com/projects/rust/book/) - [embedded-hal documentation](https://docs.rs/embedded-hal) - [Embassy documentation](https://embassy.dev/book/) - [RTIC book](https://rtic.rs/) - [avr-hal repository](https://github.com/Rahix/avr-hal) - [probe-rs documentation](https://probe.rs/docs/) - [defmt book](https://defmt.ferrous-systems.com/) - [Wokwi CLI documentation](https://docs.wokwi.com/wokwi-ci/cli-installation)